Search in sources :

Example 81 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project grpc-java by grpc.

the class SimpleServiceTest method testRpcMethodAnnotations.

@Test
public void testRpcMethodAnnotations() throws Exception {
    File grpcJavaFile = new File("./src/generated/main/grpc/io/grpc/testing/protobuf/SimpleServiceGrpc.java");
    Assume.assumeTrue(grpcJavaFile.exists());
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    AnnotationProcessor processor = new AnnotationProcessor();
    Iterable<? extends JavaFileObject> obs = fileManager.getJavaFileObjects(grpcJavaFile);
    CompilationTask task = compiler.getTask(null, fileManager, null, Collections.singleton("-proc:only"), Collections.singleton(SimpleServiceGrpc.class.getCanonicalName()), obs);
    task.setProcessors(Collections.singleton(processor));
    assertTrue(task.call());
    assertTrue(processor.processedClass);
    fileManager.close();
}
Also used : JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Test(org.junit.Test)

Example 82 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project tomee by apache.

the class Compiler method internalJava6Compile.

protected boolean internalJava6Compile(JavaCompiler compiler, JavaFileManager fileManager, DiagnosticListener<JavaFileObject> listener, Iterable<? extends JavaFileObject> fileList) {
    List<String> args = new ArrayList<>();
    addArgs(args);
    CompilationTask task = compiler.getTask(null, fileManager, listener, args, null, fileList);
    Boolean ret = task.call();
    try {
        fileManager.close();
    } catch (IOException e) {
        System.err.print("[ERROR] IOException during compiling.");
        e.printStackTrace();
    }
    return ret;
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 83 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project jOOR by jOOQ.

the class Compile method compile.

static Class<?> compile(String className, String content, CompileOptions compileOptions) {
    Lookup lookup = MethodHandles.lookup();
    ClassLoader cl = lookup.lookupClass().getClassLoader();
    try {
        return cl.loadClass(className);
    } catch (ClassNotFoundException ignore) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new ReflectException("No compiler was provided by ToolProvider.getSystemJavaCompiler(). Make sure the jdk.compiler module is available.");
        try {
            ClassFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
            List<CharSequenceJavaFileObject> files = new ArrayList<>();
            files.add(new CharSequenceJavaFileObject(className, content));
            StringWriter out = new StringWriter();
            List<String> options = new ArrayList<>(compileOptions.options);
            if (!options.contains("-classpath")) {
                StringBuilder classpath = new StringBuilder();
                String separator = System.getProperty("path.separator");
                String prop = System.getProperty("java.class.path");
                if (prop != null && !"".equals(prop))
                    classpath.append(prop);
                if (cl instanceof URLClassLoader) {
                    for (URL url : ((URLClassLoader) cl).getURLs()) {
                        if (classpath.length() > 0)
                            classpath.append(separator);
                        if ("file".equals(url.getProtocol()))
                            classpath.append(new File(url.toURI()));
                    }
                }
                options.addAll(Arrays.asList("-classpath", classpath.toString()));
            }
            CompilationTask task = compiler.getTask(out, fileManager, null, options, null, files);
            if (!compileOptions.processors.isEmpty())
                task.setProcessors(compileOptions.processors);
            task.call();
            if (fileManager.isEmpty())
                throw new ReflectException("Compilation error: " + out);
            Class<?> result = null;
            // This works if we have private-access to the interfaces in the class hierarchy
            if (Reflect.CACHED_LOOKUP_CONSTRUCTOR != null) {
                result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> Reflect.on(cl).call("defineClass", name, bytes, 0, bytes.length).get());
            } else /* [java-9] */
            // Lookup.defineClass() has only been introduced in Java 9. It is
            // required to get private-access to interfaces in the class hierarchy
            {
                // This method is called by client code from two levels up the current stack frame
                // We need a private-access lookup from the class in that stack frame in order to get
                // private-access to any local interfaces at that location.
                Class<?> caller = StackWalker.getInstance(RETAIN_CLASS_REFERENCE).walk(s -> s.skip(2).findFirst().get().getDeclaringClass());
                // we can use the private-access Lookup of the caller class
                if (className.startsWith(caller.getPackageName() + ".") && // A better implementation is difficult at this point.
                Character.isUpperCase(className.charAt(caller.getPackageName().length() + 1))) {
                    Lookup privateLookup = MethodHandles.privateLookupIn(caller, lookup);
                    result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> privateLookup.defineClass(bytes));
                } else // Otherwise, use an arbitrary class loader. This approach doesn't allow for
                // loading private-access interfaces in the compiled class's type hierarchy
                {
                    ByteArrayClassLoader c = new ByteArrayClassLoader(fileManager.classes());
                    result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> c.loadClass(name));
                }
            }
            return result;
        } catch (ReflectException e) {
            throw e;
        } catch (Exception e) {
            throw new ReflectException("Error while compiling " + className, e);
        }
    }
}
Also used : OutputStream(java.io.OutputStream) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) RETAIN_CLASS_REFERENCE(java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JavaCompiler(javax.tools.JavaCompiler) JavaFileManager(javax.tools.JavaFileManager) URL(java.net.URL) StringWriter(java.io.StringWriter) MethodHandles(java.lang.invoke.MethodHandles) BiFunction(java.util.function.BiFunction) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) Collectors(java.util.stream.Collectors) File(java.io.File) FileObject(javax.tools.FileObject) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) Lookup(java.lang.invoke.MethodHandles.Lookup) URLClassLoader(java.net.URLClassLoader) Stream(java.util.stream.Stream) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Entry(java.util.Map.Entry) URI(java.net.URI) ToolProvider(javax.tools.ToolProvider) JavaCompiler(javax.tools.JavaCompiler) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) StringWriter(java.io.StringWriter) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) Lookup(java.lang.invoke.MethodHandles.Lookup) File(java.io.File)

Example 84 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project hutool by looly.

the class JavaSourceCompiler method compile.

/**
 * 编译所有文件并返回类加载器
 *
 * @return 类加载器
 */
public ClassLoader compile() {
    // 获得classPath
    final List<File> classPath = getClassPath();
    final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0]));
    final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader);
    if (sourceList.isEmpty()) {
        // 没有需要编译的源码文件返回加载zip或jar包的类加载器
        return ucl;
    }
    // 创建编译器
    final JavaClassFileManager javaFileManager = new JavaClassFileManager(ucl, CompilerUtil.getFileManager());
    // classpath
    final List<String> options = new ArrayList<>();
    if (false == classPath.isEmpty()) {
        final List<String> cp = CollUtil.map(classPath, File::getAbsolutePath, true);
        options.add("-cp");
        options.add(CollUtil.join(cp, FileUtil.isWindows() ? ";" : ":"));
    }
    // 编译文件
    final DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    final List<JavaFileObject> javaFileObjectList = getJavaFileObject();
    final CompilationTask task = CompilerUtil.getTask(javaFileManager, diagnosticCollector, options, javaFileObjectList);
    try {
        if (task.call()) {
            // 加载编译后的类
            return javaFileManager.getClassLoader(StandardLocation.CLASS_OUTPUT);
        }
    } finally {
        IoUtil.close(javaFileManager);
    }
    // 编译失败,收集错误信息
    throw new CompilerException(DiagnosticUtil.getMessages(diagnosticCollector));
}
Also used : ArrayList(java.util.ArrayList) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JavaFileObject(javax.tools.JavaFileObject) URLClassLoader(java.net.URLClassLoader) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Aggregations

CompilationTask (javax.tools.JavaCompiler.CompilationTask)84 JavaCompiler (javax.tools.JavaCompiler)38 File (java.io.File)33 JavaFileObject (javax.tools.JavaFileObject)32 StandardJavaFileManager (javax.tools.StandardJavaFileManager)28 DiagnosticCollector (javax.tools.DiagnosticCollector)27 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)18 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)14 URLClassLoader (java.net.URLClassLoader)10 StringWriter (java.io.StringWriter)9 URL (java.net.URL)6 JavaFileManager (javax.tools.JavaFileManager)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 Test (org.junit.Test)5 OutputStream (java.io.OutputStream)4 PrintWriter (java.io.PrintWriter)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3