Search in sources :

Example 11 with JavaCompiler

use of javax.tools.JavaCompiler in project zoj by licheng.

the class CustomJavaCompiler method main.

public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("Invalid arg length " + args.length);
        System.exit(-1);
    }
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
    JavaFileManager fileManager = new CustomJavaFileManager(stdFileManager);
    System.out.println(new File(args[0]).getAbsolutePath());
    System.out.println(compiler.getTask(null, fileManager, null, null, null, stdFileManager.getJavaFileObjects(args[0])).call());
}
Also used : ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) JavaFileManager(javax.tools.JavaFileManager) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File)

Example 12 with JavaCompiler

use of javax.tools.JavaCompiler in project javapoet by square.

the class FileReadingTest method compileJavaFile.

@Test
public void compileJavaFile() throws Exception {
    final String value = "Hello World!";
    TypeSpec type = TypeSpec.classBuilder("Test").addModifiers(Modifier.PUBLIC).addSuperinterface(ParameterizedTypeName.get(Callable.class, String.class)).addMethod(MethodSpec.methodBuilder("call").returns(String.class).addModifiers(Modifier.PUBLIC).addStatement("return $S", value).build()).build();
    JavaFile javaFile = JavaFile.builder("foo", type).build();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8);
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(temporaryFolder.newFolder()));
    CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.singleton(javaFile.toJavaFileObject()));
    assertThat(task.call()).isTrue();
    assertThat(diagnosticCollector.getDiagnostics()).isEmpty();
    ClassLoader loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT);
    Callable<?> test = Class.forName("foo.Test", true, loader).asSubclass(Callable.class).newInstance();
    assertThat(Callable.class.getMethod("call").invoke(test)).isEqualTo(value);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) Callable(java.util.concurrent.Callable) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Test(org.junit.Test)

Example 13 with JavaCompiler

use of javax.tools.JavaCompiler in project bazel by bazelbuild.

the class BazelJavaCompiler method newInstance.

private static JavaCompiler newInstance(final JavaCompiler delegate) {
    // We forward most operations to the JavaCompiler implementation in langtools.jar.
    return new JavaCompiler() {

        @Override
        public CompilationTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) {
            // We prepend bazel's default javacopts to user javacopts,
            // so that the user can override them. javac supports this
            // "last option wins" style of option override.
            ImmutableList.Builder<String> fullOptions = ImmutableList.builder();
            fullOptions.addAll(getDefaultJavacopts());
            if (options != null) {
                fullOptions.addAll(options);
            }
            return delegate.getTask(out, fileManager, diagnosticListener, fullOptions.build(), classes, compilationUnits);
        }

        @Override
        public StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) {
            StandardJavaFileManager fileManager = delegate.getStandardFileManager(diagnosticListener, locale, charset);
            try {
                fileManager.setLocation(// bootclasspath
                StandardLocation.PLATFORM_CLASS_PATH, JavacBootclasspath.asFiles());
            } catch (IOException e) {
                // Should never happen, according to javadocs for setLocation
                throw new RuntimeException(e);
            }
            return fileManager;
        }

        @Override
        public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
            // prepend bazel's default javacopts to user arguments
            List<String> args = ImmutableList.<String>builder().addAll(getDefaultJavacopts()).add(arguments).build();
            return delegate.run(in, out, err, args.toArray(new String[0]));
        }

        @Override
        public Set<SourceVersion> getSourceVersions() {
            return delegate.getSourceVersions();
        }

        @Override
        public int isSupportedOption(String option) {
            return delegate.isSupportedOption(option);
        }
    };
}
Also used : Locale(java.util.Locale) JavaFileManager(javax.tools.JavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ImmutableList(com.google.common.collect.ImmutableList) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) JavaCompiler(javax.tools.JavaCompiler) Charset(java.nio.charset.Charset) DiagnosticListener(javax.tools.DiagnosticListener) SourceVersion(javax.lang.model.SourceVersion) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) Writer(java.io.Writer)

Example 14 with JavaCompiler

use of javax.tools.JavaCompiler in project bazel by bazelbuild.

the class BazelJavaCompilerTest method assertCompileSucceeds.

private void assertCompileSucceeds(final String uri, final String content) throws Exception {
    JavaCompiler javac = BazelJavaCompiler.newInstance();
    JavaFileObject source = new SimpleJavaFileObject(URI.create(uri), JavaFileObject.Kind.SOURCE) {

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return content;
        }
    };
    StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    // setting the output path by passing a flag to getTask is not reliable
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir()));
    DiagnosticCollector<JavaFileObject> messages = new DiagnosticCollector<>();
    JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, messages, null, null, Collections.singletonList(source));
    assertTrue(task.call());
    assertTrue(messages.getDiagnostics().isEmpty());
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 15 with JavaCompiler

use of javax.tools.JavaCompiler in project bazel by bazelbuild.

the class BazelJavaCompilerTest method testCompilerNewInstance.

@Test
public void testCompilerNewInstance() throws Exception {
    JavaCompiler javac = BazelJavaCompiler.newInstance();
    assertNotNull(javac.getStandardFileManager(null, null, null));
    // This is a simplified pattern of invoking the compiler API. Note, however, that
    // many examples cast to JavacTask or JavacTaskImpl and invoke the phases separately.
    // Currently, either cast will fail with something that looks like classloader issues:
    // "com.sun.tools.javac.api.JavacTask cannot be cast to com.sun.tools.javac.api.JavacTask"
    assertNotNull(javac.getTask(null, null, null, null, null, null));
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Test(org.junit.Test)

Aggregations

JavaCompiler (javax.tools.JavaCompiler)101 StandardJavaFileManager (javax.tools.StandardJavaFileManager)43 JavaFileObject (javax.tools.JavaFileObject)39 File (java.io.File)31 DiagnosticCollector (javax.tools.DiagnosticCollector)24 ArrayList (java.util.ArrayList)22 JavacTask (com.sun.source.util.JavacTask)20 IOException (java.io.IOException)17 CompilationTask (javax.tools.JavaCompiler.CompilationTask)16 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)15 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)11 Diagnostic (javax.tools.Diagnostic)11 PrintWriter (java.io.PrintWriter)9 Test (org.junit.Test)9 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 FileOutputStream (java.io.FileOutputStream)5 StringWriter (java.io.StringWriter)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStream (java.io.OutputStream)4