Java Code Examples for javax.tools.JavaCompiler#CompilationTask

The following examples show how to use javax.tools.JavaCompiler#CompilationTask . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyProxy.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * @param proxyClassString 代理类的代码
 * @param myProxyFile 代理类的Java文件
 * @throws IOException
 */
private static void compile(StringBuffer proxyClassString, File myProxyFile) throws IOException {
    // in out
    FileCopyUtils.copy(proxyClassString.toString().getBytes(), myProxyFile);
    // 调用系统编译器
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null);

    Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(myProxyFile);

    JavaCompiler.CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, null, null, null, javaFileObjects);

    task.call();

    standardJavaFileManager.close();
}
 
Example 2
Source File: T7159016.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
        JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
                                                       fm.getJavaFileObjects(src));
        task.setProcessors(Collections.singleton(new Proc()));
        if (!task.call()) {
            throw new Error("Test failed");
        }
    }
}
 
Example 3
Source File: AvroCompatibilityHelperTest.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void assertCompiles(Collection<AvroGeneratedSourceCode> generatedCode) throws Exception {

    //write out generated code into a source tree
    Path tempRootFolder = Files.createTempDirectory(null);
    File[] fileArray = new File[generatedCode.size()];
    int i=0;
    for (AvroGeneratedSourceCode avroGeneratedSourceCode : generatedCode) {
      fileArray[i++] = avroGeneratedSourceCode.writeToDestination(tempRootFolder.toFile());
    }

    //spin up a java compiler task, use current runtime classpath, point at source tree created above
    List<String> optionList = new ArrayList<>();
    optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(fileArray);
    StringWriter compilerOutput = new StringWriter();
    JavaCompiler.CompilationTask task = compiler.getTask(compilerOutput, fileManager, null, optionList, null, javaFileObjects);
    compilerOutput.flush();

    //compile, assert no errors
    Assert.assertTrue(task.call(), "compilation failed with " + compilerOutput.toString());
  }
 
Example 4
Source File: T7159016.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    JavaCompiler.CompilationTask task = jc.getTask(null, null, null, null, null,
                                                   jc.getStandardFileManager(null, null, null).getJavaFileObjects(src));
    task.setProcessors(Collections.singleton(new Proc()));
    if (!task.call()) {
        throw new Error("Test failed");
    }
}
 
Example 5
Source File: SchemaGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            boolean res = task.call();
            //Print messages generated by compiler
            for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
                 System.err.println(d.toString());
            }
            return res;
        }
 
Example 6
Source File: JdkJavaCompiler.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JavaCompiler.CompilationTask createCompileTask(JavaCompileSpec spec) {
    List<String> options = new JavaCompilerArgumentsBuilder(spec).build();
    JavaCompiler compiler = findCompiler();
    if(compiler==null){
        throw new RuntimeException("Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory.");
    }
    CompileOptions compileOptions = spec.getCompileOptions();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, compileOptions.getEncoding() != null ? Charset.forName(compileOptions.getEncoding()) : null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(spec.getSource());
    return compiler.getTask(null, null, null, options, null, compilationUnits);
}
 
Example 7
Source File: TruffleJsonFunctionWrapperGeneratorTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private static void verifyGeneratedCode(String sourceFile) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    try (StandardJavaFileManager fileManager =
            compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(Collections.singletonList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(
                null, fileManager, diagnostics, null, null, compilationUnits);
        assertTrue("Generated contract contains compile time error", task.call());
    }
}
 
Example 8
Source File: SchemaGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            boolean res = task.call();
            //Print messages generated by compiler
            for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
                 System.err.println(d.toString());
            }
            return res;
        }
 
Example 9
Source File: TupleGeneratorTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void verifyGeneratedCode(List<String> sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(sourceFiles);
        JavaCompiler.CompilationTask task = compiler.getTask(
                null, fileManager, diagnostics, null, null, compilationUnits);
        assertTrue("Generated code contains compile time error", task.call());
    }
}
 
Example 10
Source File: Jdk6JavaCompiler.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JavaCompiler.CompilationTask createCompileTask(JavaCompileSpec spec) {
    List<String> options = new JavaCompilerArgumentsBuilder(spec).build();
    JavaCompiler compiler = findCompiler();
    if(compiler==null){
        throw new RuntimeException("Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory.");
    }
    CompileOptions compileOptions = spec.getCompileOptions();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, compileOptions.getEncoding() != null ? Charset.forName(compileOptions.getEncoding()) : null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(spec.getSource());
    return compiler.getTask(null, null, null, options, null, compilationUnits);
}
 
Example 11
Source File: SchemaGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty()) {
                LOGGER.log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            }
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            boolean res = task.call();
            //Print compiler generated messages
            for( Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics() ) {
                 System.err.println(d.toString());
            }
            return res;
        }
 
Example 12
Source File: TruffleJsonFunctionWrapperGeneratorTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static void verifyGeneratedCode(String sourceFile) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    try (StandardJavaFileManager fileManager =
            compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(Collections.singletonList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(
                null, fileManager, diagnostics, null, null, compilationUnits);
        assertTrue("Generated contract contains compile time error", task.call());
    }
}
 
Example 13
Source File: SnakeYAMLMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private void analyzeClasses(Map<String, Type> types, Set<Import> imports, Map<String, List<String>> interfaces,
        Collection<Path> pathsToCommpile, String note) {
    /*
     * There should not be compilation errors, but without our own diagnostic listener any compilation errors will
     * appear in the build output. We want to suppress those because we want to gather information about the interfaces
     * and classes, not actually compile them into .class files.
     */
    DiagnosticListener<JavaFileObject> diagListener = diagnostic -> {
        debugLog(() -> diagnostic.toString());
    };

    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null);

    JavaCompiler.CompilationTask task = jc.getTask(null, fm, diagListener, null, null,
            javaFilesToCompile(fm, pathsToCommpile));
    List<Processor> procs = new ArrayList<>();
    EndpointProcessor ep = new EndpointProcessor(new EndpointScanner(types, imports, interfaces));
    procs.add(ep);
    task.setProcessors(procs);
    task.call();

    getLog().info(String.format("Types prepared for %s: %d", note, types.size()));
    debugLog(() -> String.format("Types prepared for %s: %s", note, types));
    debugLog(() -> String.format("Imports after analyzing %s: %s", note,
            imports.stream().sorted().map(Import::toString).collect(Collectors.joining(","))));
    debugLog(() -> String.format("Interface impls after analyzing %s: %s", note, interfaces));
}
 
Example 14
Source File: CompilerUtil.java    From NullAway with MIT License 5 votes vote down vote up
private boolean compile(Iterable<JavaFileObject> sources, Iterable<String> args) {
  PrintWriter writer =
      new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)), true);
  JavaCompiler.CompilationTask task =
      compiler.getTask(
          writer,
          fileManager,
          diagnosticHelper.collector,
          args,
          null,
          ImmutableList.copyOf(sources));
  return task.call();
}
 
Example 15
Source File: CompilerUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException
 *         if there is an I/O error scanning the source tree or
 *         creating the destination directory
 * @throws UnsupportedOperationException
 *         if there is no system java compiler
 */
public static boolean compile(Path source, Path destination, String ... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        // no compiler available
        throw new UnsupportedOperationException("Unable to get system java compiler. " +
            "Perhaps, jdk.compiler module is not available.");
    }
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
        = Files.find(source, Integer.MAX_VALUE,
            (file, attrs) -> (file.toString().endsWith(".java")))
            .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocation(StandardLocation.CLASS_PATH, Collections.EMPTY_LIST);
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                             Arrays.asList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, opts, null,
            jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
 
Example 16
Source File: ClassBodyWrapper.java    From Quicksql with MIT License 5 votes vote down vote up
public CompilationPackage compile(Map<String, String> classesToCompile, String extraJars)
    throws CompilerException {
    //modified classpath acquirement mode
    String belongingJarPath = ClassBodyWrapper.class.getProtectionDomain().getCodeSource()
        .getLocation()
        .getPath();

    List<String> options = Arrays
        .asList("-classpath", extraJars
            + System.getProperty("path.separator")
            + System.getProperty("java.class.path")
            + System.getProperty("path.separator")
            + belongingJarPath
        );

    List<JavaSourceFromString> strFiles = Lists.newArrayList();
    Iterator it = classesToCompile.keySet().iterator();

    String compilationReport;
    while (it.hasNext()) {
        String className = (String) it.next();
        compilationReport = classesToCompile.get(className);
        strFiles.add(new JavaSourceFromString(className, compilationReport));
    }

    JavaCompiler compiler = this.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> collector = this.getDiagnosticCollector();
    InMemoryClassManager manager = this.getClassManager(compiler);
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager,
        collector, options, null, strFiles);
    boolean status = task.call();
    if (status) {
        List<CompilationUnit> compilationUnits = manager.getAllClasses();
        return new CompilationPackage(compilationUnits);
    } else {
        compilationReport = this.buildCompilationReport(collector, options);
        throw new CompilerException(compilationReport);
    }
}
 
Example 17
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Processes a collection of class names. Names should fully qualified
 * names in the form "pkg.pkg.pkg.classname".
 *
 * @param classNames collection of fully qualified classnames to process
 * @return true for success, false for failure
 * @throws IOException if an I/O error occurs
 */
boolean doClassNames(Collection<String> classNames) throws IOException {
    if (verbose) {
        out.println("List of classes to process:");
        classNames.forEach(out::println);
        out.println("End of class list.");
    }

    // TODO: not sure this is necessary...
    if (fm instanceof JavacFileManager) {
        ((JavacFileManager)fm).setSymbolFileEnabled(false);
    }

    fm.setLocation(StandardLocation.CLASS_PATH, classPath);
    if (!bootClassPath.isEmpty()) {
        fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
    }

    if (!systemModules.isEmpty()) {
        fm.setLocation(StandardLocation.SYSTEM_MODULES, systemModules);
    }

    LoadProc proc = new LoadProc();
    JavaCompiler.CompilationTask task =
        compiler.getTask(null, fm, this, options, classNames, null);
    task.setProcessors(List.of(proc));
    boolean r = task.call();
    if (r) {
        if (forRemoval) {
            deprList = proc.getDeprecations().stream()
                           .filter(DeprData::isForRemoval)
                           .collect(toList());
        } else {
            deprList = proc.getDeprecations();
        }
    }
    return r;
}
 
Example 18
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static JavacTrees instance(JavaCompiler.CompilationTask task) {
    if (!(task instanceof BasicJavacTask))
        throw new IllegalArgumentException();
    return instance(((BasicJavacTask)task).getContext());
}
 
Example 19
Source File: JavacTrees.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static JavacTrees instance(JavaCompiler.CompilationTask task) {
    if (!(task instanceof BasicJavacTask))
        throw new IllegalArgumentException();
    return instance(((BasicJavacTask)task).getContext());
}
 
Example 20
Source File: GeneratorTest.java    From ask-sdk-frameworks-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsomorphism() throws Exception {
    // Generate java files for interaction models
    String path = "target/temp/generated-src/testIsomorphism";

    Application.main(new String[] {
        "--namespace", "com.example",
        "--output", path,
        "--skill-name", "PetSkill",
        "--model", "en-US=models/en-US.json",
        "--model", "de-DE=models/de-DE.json"
    });

    // Compile generated code
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    File typeFile = new File(path + "/src/main/java/com/example/slots/PetType.java");
    File intentFile = new File(path + "/src/main/java/com/example/intents/PetTypeIntent.java");
    File skillFile = new File(path + "/src/main/java/com/example/PetSkill.java");
    File javaDir = new File(path + "/src/main/java");
    File resourcesDir = new File(path + "/src/main/resources");
    Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(typeFile, intentFile, skillFile);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, files);
    assertTrue(task.call());
    fileManager.close();

    // Load the generated code
    URLClassLoader classLoader = new URLClassLoader(new URL[]{
        javaDir.toURI().toURL(),
        resourcesDir.toURI().toURL()
    });
    Class<?> clazz = classLoader.loadClass("com.example.PetSkill");
    SkillModelSupplier skillModelSupplier =  (SkillModelSupplier) clazz.newInstance();

    // Render the interaction model and ensure it equals the original interaction model
    for (Locale locale : Arrays.asList(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("de-DE"))) {
        InteractionModelEnvelope expectedModel = mapper.readValue(new File("models/" + locale.toLanguageTag() + ".json"), InteractionModelEnvelope.class);
        InteractionModelEnvelope actualModel = renderer.render(skillModelSupplier.getSkillModel(), locale);
        assertEquals(
            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(expectedModel),
            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(actualModel));
    }
}