pax_global_header00006660000000000000000000000064123410535720014514gustar00rootroot0000000000000052 comment=a34a2907123e0494cfe2e81799c740b557be86a0 Java-Runtime-Compiler-compiler-2.2.0/000077500000000000000000000000001234105357200173775ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/.gitignore000066400000000000000000000001051234105357200213630ustar00rootroot00000000000000*.class # Package Files # *.jar *.war *.ear *.iml compiler/target Java-Runtime-Compiler-compiler-2.2.0/LICENSE000066400000000000000000000240411234105357200204050ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Java-Runtime-Compiler-compiler-2.2.0/README.md000066400000000000000000000022761234105357200206650ustar00rootroot00000000000000Java-Runtime-Compiler ===================== This takes a String, compiles it and loads it returning you a class from what you built. By default it uses the current ClassLoader. It supports nested classes, but otherwise builds one class at a time. ## On maven central You can include in your project with net.openhft compiler 2.1.2 ## Simple example You needa CachedCompiler and access to you JDK's tools.jar. private final CachedCompiler cc = new CachedCompiler(null, null); // dynamically you can call Class aClass = cc.loadFromJava(className, javaCode); KnownInterface o = (KnownInterface) aClass.newInstance(); I suggest making you class implement a "KnownInterface" as this will allow you to call/manipulate instances of you generated class. Another more hacky way is to use this to override a class, provided it hasn't been loaded already. This means you can redefine an existing class and provided the methods and fields used match, you have compiler redefine a class and code already compiled to use the class will still work. Java-Runtime-Compiler-compiler-2.2.0/compiler/000077500000000000000000000000001234105357200212115ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/pom.xml000077500000000000000000000075021234105357200225350ustar00rootroot00000000000000 net.openhft java-parent-pom 1.0.1 4.0.0 compiler 2.2.0 bundle OpenHFT/Java-Runtime-Compiler Java Runtime Compiler library. net.openhft third-party-bom pom 3.4.0 import org.slf4j slf4j-api com.sun.java tools org.kohsuke.jetbrains annotations org.easymock easymock test junit junit test org.slf4j slf4j-simple test org.apache.felix maven-bundle-plugin true ${project.groupId}.${project.artifactId} ${project.artifactId} sonatype-nexus-staging https://oss.sonatype.org/content/repositories/staging true scm:git:git@github.com:OpenHFT/Java-Runtime-Compiler.git scm:git:git@github.com:OpenHFT/Java-Runtime-Compiler.git scm:git:git@github.com:OpenHFT/Java-Runtime-Compiler.git compiler-2.2.0 Java-Runtime-Compiler-compiler-2.2.0/compiler/src/000077500000000000000000000000001234105357200220005ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/000077500000000000000000000000001234105357200227245ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/000077500000000000000000000000001234105357200236455ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/000077500000000000000000000000001234105357200244335ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/000077500000000000000000000000001234105357200260765ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/compiler/000077500000000000000000000000001234105357200277105ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/compiler/CachedCompiler.java000066400000000000000000000111221234105357200334120ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.compiler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; import javax.tools.JavaFileObject; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import static net.openhft.compiler.CompilerUtils.writeBytes; import static net.openhft.compiler.CompilerUtils.writeText; @SuppressWarnings("StaticNonFinalField") public class CachedCompiler { private static final Map> loadedClassesMap = new WeakHashMap>(); @Nullable private final File sourceDir; @Nullable private final File classDir; private final List javaFileObjects = new ArrayList(); public CachedCompiler(@Nullable File sourceDir, @Nullable File classDir) { this.sourceDir = sourceDir; this.classDir = classDir; } public static void close() { try { CompilerUtils.s_fileManager.close(); } catch (IOException e) { throw new AssertionError(e); } } public Class loadFromJava(@NotNull String className, @NotNull String javaCode) throws ClassNotFoundException { return loadFromJava(getClass().getClassLoader(), className, javaCode); } @NotNull Map compileFromJava(@NotNull String className, @NotNull String javaCode) { Iterable compilationUnits; if (sourceDir != null) { String filename = className.replaceAll("\\.", '\\' + File.separator) + ".java"; File file = new File(sourceDir, filename); writeText(file, javaCode); compilationUnits = CompilerUtils.s_standardJavaFileManager.getJavaFileObjects(file); } else { javaFileObjects.add(new JavaSourceFromString(className, javaCode)); compilationUnits = javaFileObjects; } // reuse the same file manager to allow caching of jar files CompilerUtils.s_compiler.getTask(null, CompilerUtils.s_fileManager, null, null, null, compilationUnits).call(); return CompilerUtils.s_fileManager.getAllBuffers(); } public Class loadFromJava(@NotNull ClassLoader classLoader, @NotNull String className, @NotNull String javaCode) throws ClassNotFoundException { Class clazz = null; Map loadedClasses; synchronized (loadedClassesMap) { loadedClasses = loadedClassesMap.get(classLoader); if (loadedClasses == null) loadedClassesMap.put(classLoader, loadedClasses = new LinkedHashMap()); else clazz = loadedClasses.get(className); } if (clazz != null) return clazz; for (Map.Entry entry : compileFromJava(className, javaCode).entrySet()) { String className2 = entry.getKey(); synchronized (loadedClassesMap) { if (loadedClasses.containsKey(className2)) continue; } byte[] bytes = entry.getValue(); if (classDir != null) { String filename = className2.replaceAll("\\.", '\\' + File.separator) + ".class"; boolean changed = writeBytes(new File(classDir, filename), bytes); if (changed) { LoggerFactory.getLogger(CachedCompiler.class).info("Updated {} in {}", className2, classDir); } } Class clazz2 = CompilerUtils.defineClass(classLoader, className2, bytes); synchronized (loadedClassesMap) { loadedClasses.put(className2, clazz2); } } // CompilerUtils.s_fileManager.clearBuffers(); synchronized (loadedClassesMap) { loadedClasses.put(className, clazz = classLoader.loadClass(className)); } return clazz; } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/compiler/CompilerUtils.java000066400000000000000000000235431234105357200333550ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.compiler; import com.sun.tools.javac.api.JavacTool; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.tools.JavaCompiler; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.Arrays; /** * This class support loading and debugging Java Classes dynamically. */ public enum CompilerUtils { ; private static final Logger LOGGER = LoggerFactory.getLogger(CompilerUtils.class); public static final boolean DEBUGGING = ManagementFactory.getRuntimeMXBean().getInputArguments().contains("-Xdebug"); public static final CachedCompiler CACHED_COMPILER = new CachedCompiler(null, null); private static final Method DEFINE_CLASS_METHOD; private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final String JAVA_CLASS_PATH = "java.class.path"; static { try { DEFINE_CLASS_METHOD = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); DEFINE_CLASS_METHOD.setAccessible(true); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } static JavaCompiler s_compiler; static StandardJavaFileManager s_standardJavaFileManager; static MyJavaFileManager s_fileManager; private static void reset() { s_compiler = ToolProvider.getSystemJavaCompiler(); if (s_compiler == null) s_compiler = JavacTool.create(); s_standardJavaFileManager = s_compiler.getStandardFileManager(null, null, null); s_fileManager = new MyJavaFileManager(s_standardJavaFileManager); } static { reset(); } /** * Load a java class file from the classpath or local file system. * * @param className expected class name of the outer class. * @param resourceName as the full file name with extension. * @return the outer class loaded. * @throws IOException the resource could not be loaded. * @throws ClassNotFoundException the class name didn't match or failed to initialise. */ public static Class loadFromResource(@NotNull String className, @NotNull String resourceName) throws IOException, ClassNotFoundException { return loadFromJava(className, readText(resourceName)); } /** * Load a java class from text. * * @param className expected class name of the outer class. * @param javaCode to compile and load. * @return the outer class loaded. * @throws ClassNotFoundException the class name didn't match or failed to initialise. */ private static Class loadFromJava(@NotNull String className, @NotNull String javaCode) throws ClassNotFoundException { return CACHED_COMPILER.loadFromJava(Thread.currentThread().getContextClassLoader(), className, javaCode); } /** * Add a directory to the class path for compiling. This can be required with custom * * @param dir to add. * @return whether the directory was found, if not it is not added either. */ public static boolean addClassPath(@NotNull String dir) { File file = new File(dir); if (file.exists()) { String path; try { path = file.getCanonicalPath(); } catch (IOException ignored) { path = file.getAbsolutePath(); } if (!Arrays.asList(System.getProperty(JAVA_CLASS_PATH).split(File.pathSeparator)).contains(path)) System.setProperty(JAVA_CLASS_PATH, System.getProperty(JAVA_CLASS_PATH) + File.pathSeparator + path); } else { return false; } reset(); return true; } /** * Define a class for byte code. * * @param className expected to load. * @param bytes of the byte code. */ public static void defineClass(@NotNull String className, @NotNull byte[] bytes) { defineClass(Thread.currentThread().getContextClassLoader(), className, bytes); } /** * Define a class for byte code. * * @param classLoader to load the class into. * @param className expected to load. * @param bytes of the byte code. */ public static Class defineClass(@Nullable ClassLoader classLoader, @NotNull String className, @NotNull byte[] bytes) { try { return (Class) DEFINE_CLASS_METHOD.invoke(classLoader, className, bytes, 0, bytes.length); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new AssertionError(e.getCause()); } } private static String readText(@NotNull String resourceName) throws IOException { if (resourceName.startsWith("=")) return resourceName.substring(1); StringWriter sw = new StringWriter(); Reader isr = new InputStreamReader(getInputStream(resourceName), UTF_8); try { char[] chars = new char[8 * 1024]; int len; while ((len = isr.read(chars)) > 0) sw.write(chars, 0, len); } finally { close(isr); } return sw.toString(); } @NotNull private static String decodeUTF8(@NotNull byte[] bytes) { try { return new String(bytes, UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } @Nullable @SuppressWarnings("ReturnOfNull") private static byte[] readBytes(@NotNull File file) { if (!file.exists()) return null; long len = file.length(); if (len > Runtime.getRuntime().totalMemory() / 10) throw new IllegalStateException("Attempted to read large file " + file + " was " + len + " bytes."); byte[] bytes = new byte[(int) len]; DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream(file)); dis.readFully(bytes); } catch (IOException e) { close(dis); LOGGER.warn("Unable to read {}", file, e); throw new IllegalStateException("Unable to read file " + file, e); } return bytes; } private static void close(@Nullable Closeable closeable) { if (closeable != null) try { closeable.close(); } catch (IOException e) { LOGGER.trace("Failed to close {}", closeable, e); } } public static boolean writeText(@NotNull File file, @NotNull String text) { return writeBytes(file, encodeUTF8(text)); } @NotNull private static byte[] encodeUTF8(@NotNull String text) { try { return text.getBytes(UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } public static boolean writeBytes(@NotNull File file, @NotNull byte[] bytes) { File parentDir = file.getParentFile(); if (!parentDir.isDirectory() && !parentDir.mkdirs()) throw new IllegalStateException("Unable to create directory " + parentDir); // only write to disk if it has changed. File bak = null; if (file.exists()) { byte[] bytes2 = readBytes(file); if (Arrays.equals(bytes, bytes2)) return false; bak = new File(parentDir, file.getName() + ".bak"); file.renameTo(bak); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(bytes); } catch (IOException e) { close(fos); LOGGER.warn("Unable to write {} as {}", file, decodeUTF8(bytes), e); file.delete(); if (bak != null) bak.renameTo(file); throw new IllegalStateException("Unable to write " + file, e); } return true; } @NotNull private static InputStream getInputStream(@NotNull String filename) throws FileNotFoundException { if (filename.isEmpty()) throw new IllegalArgumentException("The file name cannot be empty."); if (filename.charAt(0) == '=') return new ByteArrayInputStream(encodeUTF8(filename.substring(1))); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream is = contextClassLoader.getResourceAsStream(filename); if (is != null) return is; InputStream is2 = contextClassLoader.getResourceAsStream('/' + filename); if (is2 != null) return is2; return new FileInputStream(filename); } } JavaSourceFromString.java000066400000000000000000000030441234105357200345520ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/compiler/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.compiler; import org.jetbrains.annotations.NotNull; import javax.tools.SimpleJavaFileObject; import java.net.URI; /* A file object used to represent source coming from a string. */ class JavaSourceFromString extends SimpleJavaFileObject { /** * The source code of this "file". */ private final String code; /** * Constructs a new JavaSourceFromString. * * @param name the name of the compilation unit represented by this file object * @param code the source code for the compilation unit represented by this file object */ JavaSourceFromString(@NotNull String name, String code) { super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); this.code = code; } @SuppressWarnings("RefusedBequest") @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } MyJavaFileManager.java000066400000000000000000000116331234105357200337620ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/main/java/net/openhft/compiler/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.compiler; import org.jetbrains.annotations.NotNull; import javax.tools.*; import javax.tools.JavaFileObject.Kind; import java.io.*; import java.net.URI; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; @SuppressWarnings("RefusedBequest") class MyJavaFileManager implements JavaFileManager { private final StandardJavaFileManager fileManager; private final Map buffers = new LinkedHashMap(); MyJavaFileManager(StandardJavaFileManager fileManager) { this.fileManager = fileManager; } public ClassLoader getClassLoader(Location location) { // System.out.println("getClassLoader(" + location + ')'); return fileManager.getClassLoader(location); } public Iterable list(Location location, String packageName, Set kinds, boolean recurse) throws IOException { // System.out.println("list(" + location + ',' + packageName + ',' + kinds + ',' + recurse + ')'); return fileManager.list(location, packageName, kinds, recurse); } public String inferBinaryName(Location location, JavaFileObject file) { // System.out.println("inferBinaryName(location=" + location + ", file=" + file + ')'); return fileManager.inferBinaryName(location, file); } public boolean isSameFile(FileObject a, FileObject b) { return fileManager.isSameFile(a, b); } public boolean handleOption(String current, Iterator remaining) { return fileManager.handleOption(current, remaining); } public boolean hasLocation(Location location) { // System.out.println("hasLocation(" + location + ')'); return fileManager.hasLocation(location); } public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException { // System.out.println("getJavaFileForInput(location=" + location + ", className=" + className + ", kind=" + kind + ')'); if (location == StandardLocation.CLASS_OUTPUT && buffers.containsKey(className) && kind == Kind.CLASS) { final byte[] bytes = buffers.get(className).toByteArray(); return new SimpleJavaFileObject(URI.create(className), kind) { @NotNull public InputStream openInputStream() { return new ByteArrayInputStream(bytes); } }; } return fileManager.getJavaFileForInput(location, className, kind); } @NotNull public JavaFileObject getJavaFileForOutput(Location location, final String className, Kind kind, FileObject sibling) throws IOException { return new SimpleJavaFileObject(URI.create(className), kind) { @NotNull public OutputStream openOutputStream() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); buffers.put(className, baos); return baos; } }; } public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { return fileManager.getFileForInput(location, packageName, relativeName); } public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { return fileManager.getFileForOutput(location, packageName, relativeName, sibling); } public void flush() throws IOException { // for (Map.Entry entry : buffers.entrySet()) // System.out.println("Compiled " + entry.getKey() + ", size=" + entry.getValue().toByteArray().length); } public void close() throws IOException { // System.out.println("close()"); fileManager.close(); } public int isSupportedOption(String option) { return fileManager.isSupportedOption(option); } public void clearBuffers() { buffers.clear(); } @NotNull public Map getAllBuffers() { Map ret = new LinkedHashMap(buffers.size() * 2); for (Map.Entry entry : buffers.entrySet()) { ret.put(entry.getKey(), entry.getValue().toByteArray()); } return ret; } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/000077500000000000000000000000001234105357200227575ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/000077500000000000000000000000001234105357200237005ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/000077500000000000000000000000001234105357200242735ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/FooBarTee.java000066400000000000000000000027161234105357200267520ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg; import eg.components.BarImpl; import eg.components.Foo; import eg.components.TeeImpl; public class FooBarTee { public final String name; public final TeeImpl tee; public final BarImpl bar; public final BarImpl copy; public final Foo foo; public FooBarTee(String name) { // when viewing this file, ensure it is synchronised with the copy on disk. System.out.println("generated test Tue Nov 06 20:54:52 GMT 2007"); this.name = name; tee = new TeeImpl("test"); bar = new BarImpl(tee, 55); copy = new BarImpl(tee, 555); // you should see the current date here after synchronisation. foo = new Foo(bar, copy, "generated test Tue Nov 06 20:54:52 GMT 2007", 5); } public void start() { } public void stop() { } public void close() { stop(); } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/000077500000000000000000000000001234105357200264605ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/Bar.java000066400000000000000000000012461234105357200300320ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg.components; interface Bar { Tee getTee(); int getI(); } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/BarImpl.java000066400000000000000000000015731234105357200306570ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg.components; public class BarImpl implements Bar { final int i; final Tee tee; public BarImpl(Tee tee, int i) { this.tee = tee; this.i = i; } public Tee getTee() { return tee; } public int getI() { return i; } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/Foo.java000066400000000000000000000016541234105357200300540ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg.components; @SuppressWarnings({"QuestionableName"}) public class Foo { public final Bar bar; public final Bar copy; public final String s; public final int i; public Foo(Bar bar, Bar copy, String s, int i) { this.bar = bar; this.copy = copy; this.s = s; this.i = i; } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/Tee.java000066400000000000000000000012261234105357200300410ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg.components; interface Tee { String getS(); } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/eg/components/TeeImpl.java000066400000000000000000000014331234105357200306630ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eg.components; public class TeeImpl implements Tee { final String s; public TeeImpl(String s) { this.s = s; } public String getS() { return s; } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/net/000077500000000000000000000000001234105357200244665ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/net/openhft/000077500000000000000000000000001234105357200261315ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/net/openhft/compiler/000077500000000000000000000000001234105357200277435ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/java/net/openhft/compiler/CompilerTest.java000066400000000000000000000121371234105357200332240ustar00rootroot00000000000000/* * Copyright 2013 Peter Lawrey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.compiler; import com.sun.tools.internal.xjc.util.NullStream; import eg.FooBarTee; import eg.components.Foo; import junit.framework.TestCase; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Date; public class CompilerTest extends TestCase { private static final String EG_FOO_BAR_TEE = "eg.FooBarTee"; static final File parent; static { File parent2 = new File("essence-file"); if (parent2.exists()) { parent = parent2; } else { parent = new File("."); } } public static void test_compiler() throws ClassNotFoundException { // CompilerUtils.setDebug(true); // added so the test passes in Maven. CompilerUtils.addClassPath("target/test-classes"); // ClassLoader loader = CompilerTest.class.getClassLoader(); // URLClassLoader urlClassLoader = new URLClassLoader(((URLClassLoader)loader).getURLs(), null); // Class fooBarTee1 = urlClassLoader.loadClass("eg.FooBarTee"); // this writes the file to disk only when debugging is enabled. CachedCompiler cc = CompilerUtils.DEBUGGING ? new CachedCompiler(new File(parent, "src/test/java"), new File(parent, "target/compiled")) : CompilerUtils.CACHED_COMPILER; String text = "generated test " + new Date(); cc.loadFromJava(EG_FOO_BAR_TEE, "package eg;\n" + '\n' + "import eg.components.BarImpl;\n" + "import eg.components.TeeImpl;\n" + "import eg.components.Foo;\n" + '\n' + "public class FooBarTee{\n" + " public final String name;\n" + " public final TeeImpl tee;\n" + " public final BarImpl bar;\n" + " public final BarImpl copy;\n" + " public final Foo foo;\n" + '\n' + " public FooBarTee(String name) {\n" + " // when viewing this file, ensure it is synchronised with the copy on disk.\n" + " System.out.println(\"" + text + "\");\n" + " this.name = name;\n" + '\n' + " tee = new TeeImpl(\"test\");\n" + '\n' + " bar = new BarImpl(tee, 55);\n" + '\n' + " copy = new BarImpl(tee, 555);\n" + '\n' + " // you should see the current date here after synchronisation.\n" + " foo = new Foo(bar, copy, \"" + text + "\", 5);\n" + " }\n" + '\n' + " public void start() {\n" + " }\n" + '\n' + " public void stop() {\n" + " }\n" + '\n' + " public void close() {\n" + " stop();\n" + '\n' + " }\n" + "}\n"); // add a debug break point here and step into this method. FooBarTee fooBarTee = new FooBarTee("test foo bar tee"); Foo foo = fooBarTee.foo; assertNotNull(foo); assertEquals(text, foo.s); } private static final int RUNS = 1000 * 1000; public void test_fromFile() throws ClassNotFoundException, IOException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class clazz = CompilerUtils.loadFromResource("eg.FooBarTee2", "eg/FooBarTee2.jcf"); // turn off System.out PrintStream out = System.out; try { System.setOut(new PrintStream(new NullStream())); final Constructor stringConstructor = clazz.getConstructor(String.class); long start = 0; for (int i = -RUNS / 10; i < RUNS; i++) { if (i == 0) start = System.nanoTime(); Object fooBarTee2 = stringConstructor.newInstance(getName()); Foo foo = (Foo) clazz.getDeclaredField("foo").get(fooBarTee2); assertNotNull(foo); assertEquals("load java class from file.", foo.s); } long time = System.nanoTime() - start; out.printf("Build build small container %,d ns.%n", time / RUNS); } finally { System.setOut(out); } } } Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/resources/000077500000000000000000000000001234105357200247715ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/resources/eg/000077500000000000000000000000001234105357200253645ustar00rootroot00000000000000Java-Runtime-Compiler-compiler-2.2.0/compiler/src/test/resources/eg/FooBarTee2.jcf000066400000000000000000000015241234105357200277420ustar00rootroot00000000000000package eg; import eg.components.BarImpl; import eg.components.Foo; import eg.components.TeeImpl; public class FooBarTee2 { public final String name; public final TeeImpl tee; public final BarImpl bar; public final BarImpl copy; public final Foo foo; public FooBarTee2(String name) { // when viewing this file, ensure it is synchronised with the copy on disk. System.out.println("load java class from file."); this.name = name; tee = new TeeImpl("test"); bar = new BarImpl(tee, 55); copy = new BarImpl(tee, 555); // you should see the current date here after synchronisation. foo = new Foo(bar, copy, "load java class from file.", 5); } public void start() { } public void stop() { } public void close() { stop(); } } Java-Runtime-Compiler-compiler-2.2.0/pom.xml000066400000000000000000000025521234105357200207200ustar00rootroot00000000000000 net.openhft root-parent-pom 1.1.0 4.0.0 Java-Runtime-Compiler 2.0-SNAPSHOT pom Java Compiler Parent Java Runtime Compiler library compiler