Java Code Examples for javax.tools.JavaCompiler.CompilationTask

The following are Jave code examples for showing how to use CompilationTask of the javax.tools.JavaCompiler class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: openjdk-jdk10   File: FailureAtomicity.java   Source Code and License Vote up 6 votes
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(null, null, null)) {
        List<File> files = sourceFiles.stream()
                                      .map(p -> p.toFile())
                                      .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                                Arrays.asList(dest.toFile()));
        fileManager.setLocation(StandardLocation.CLASS_PATH,
                                Arrays.asList(TEST_CLASSES.toFile()));
        JavaCompiler.CompilationTask task = compiler
                .getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
 
Example 2
Project: openjdk-jdk10   File: TestBase.java   Source Code and License Vote up 6 votes
private <S> InMemoryFileManager compile(
        List<String> options,
        Function<S, ? extends JavaFileObject> src2JavaFileObject,
        List<S> sources)
        throws IOException, CompilationException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<? extends JavaFileObject> src = sources.stream()
            .map(src2JavaFileObject)
            .collect(Collectors.toList());

    DiagnosticCollector<? super JavaFileObject> dc = new DiagnosticCollector<>();
    try (InMemoryFileManager fileManager
                 = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
        boolean success = task.call();
        if (!success) {
            String errorMessage = dc.getDiagnostics().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining("\n"));
            throw new CompilationException("Compilation Error\n\n" + errorMessage);
        }
        return fileManager;
    }
}
 
Example 3
Project: mybatis-generator-plugin   File: MyBatisGeneratorTool.java   Source Code and License Vote up 6 votes
/**
 * 动态编译java文件
 * @param files
 */
private void compileJavaFiles(List<File> files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //获取java文件管理类
    StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
    //获取java文件对象迭代器
    Iterable<? extends JavaFileObject> it = manager.getJavaFileObjectsFromFiles(files);
    //设置编译参数
    ArrayList<String> ops = new ArrayList<>();
    ops.add("-Xlint:unchecked");
    //获取编译任务
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, ops, null, it);
    //执行编译任务
    task.call();
}
 
Example 4
Project: openjdk-jdk10   File: CompilerUtils.java   Source Code and License Vote up 6 votes
/**
 * 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
 */
public static boolean compile(Path source, Path destination, String ... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    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.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 5
Project: openjdk-jdk10   File: JImageGenerator.java   Source Code and License Vote up 6 votes
public static boolean compile(Path source, Path destination, String... options) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (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.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));

        List<String> opts = Arrays.asList(options);
        JavaCompiler.CompilationTask task
                = compiler.getTask(null, jfm, null, opts, null,
                jfm.getJavaFileObjectsFromPaths(sources));
        List<String> list = new ArrayList<>(opts);
        list.addAll(sources.stream()
                .map(Path::toString)
                .collect(Collectors.toList()));
        System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
        return task.call();
    }
}
 
Example 6
Project: openjdk-jdk10   File: CompilerUtils.java   Source Code and License Vote up 6 votes
/**
 * 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
 */
public static boolean compile(Path source, Path destination, String... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    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.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 7
Project: openjdk-jdk10   File: CompilerUtils.java   Source Code and License Vote up 6 votes
/**
 * Compile the specified module from the given module sourcepath
 *
 * 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
 */
public static boolean compileModule(Path source, Path destination,
                                    String moduleName, String... options) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    try {
        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                                 Arrays.asList(destination));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    Stream<String> opts = Arrays.stream(new String[] {
        "--module-source-path", source.toString(), "-m", moduleName
    });
    List<String> javacOpts = Stream.concat(opts, Arrays.stream(options))
                                    .collect(Collectors.toList());
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, javacOpts, null, null);
    return task.call();
}
 
Example 8
Project: openjdk-jdk10   File: Basic.java   Source Code and License Vote up 6 votes
static void javac(Path dest, Path... sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null)) {

        List<File> files = Stream.of(sourceFiles)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        List<File> dests = Stream.of(dest)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);
        JavaCompiler.CompilationTask task =
                compiler.getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
 
Example 9
Project: Reer   File: JdkJavaCompiler.java   Source Code and License Vote up 5 votes
private JavaCompiler.CompilationTask createCompileTask(JavaCompileSpec spec) {
    List<String> options = new JavaCompilerArgumentsBuilder(spec).build();
    JavaCompiler compiler = javaHomeBasedJavaCompilerFactory.create();
    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 10
Project: GitHub   File: SimpleCompiler.java   Source Code and License Vote up 5 votes
@Override
public JavaCompiler.CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options, Iterable<String> classes,
        Iterable<? extends JavaFileObject> compilationUnits) {
    return compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
}
 
Example 11
Project: annotation-processor-demo   File: Main.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
  System.out.println("Sourcepath is " + args[0]);
  // We're interested in scanning all .java files under the sourcepath passed as an argument here.
  List<File> sourceFiles = Arrays.asList(new File(new File(args[0]).getAbsolutePath()).listFiles(f -> f.getName().endsWith(".java")));
  sourceFiles.stream().forEach(System.out::println); // Printing the detected class file paths.
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
  Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjectsFromFiles(sourceFiles);
  JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, javaFileObjects);
  task.setProcessors(Arrays.asList(new PrivateOnlyAnnotationProcessor(), new JavaBeanAnnotationProcessor()));
  System.out.println(task.call());
}
 
Example 12
Project: openjdk-jdk10   File: SchemaGenerator.java   Source Code and License Vote up 5 votes
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 13
Project: openjdk-jdk10   File: JavacTask.java   Source Code and License Vote up 5 votes
private int runAPI(PrintWriter pw) throws IOException {
        try {
//                if (compiler == null) {
                // TODO: allow this to be set externally
//                    compiler = ToolProvider.getSystemJavaCompiler();
                compiler = JavacTool.create();
//                }

            if (fileManager == null)
                fileManager = internalFileManager = compiler.getStandardFileManager(null, null, null);
            if (outdir != null)
                setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singletonList(outdir));
            if (classpath != null)
                setLocationFromPaths(StandardLocation.CLASS_PATH, classpath);
            if (sourcepath != null)
                setLocationFromPaths(StandardLocation.SOURCE_PATH, sourcepath);
            List<String> allOpts = new ArrayList<>();
            if (options != null)
                allOpts.addAll(options);

            Iterable<? extends JavaFileObject> allFiles = joinFiles(files, fileObjects);
            JavaCompiler.CompilationTask task = compiler.getTask(pw,
                    fileManager,
                    null,  // diagnostic listener; should optionally collect diags
                    allOpts,
                    classes,
                    allFiles);
            return ((JavacTaskImpl) task).doCall().exitCode;
        } finally {
            if (internalFileManager != null)
                internalFileManager.close();
        }
    }
 
Example 14
Project: Avatar   File: CompilerUtil.java   Source Code and License Vote up 5 votes
/**
 * Compiles the supplied sources with the system Java compiler and the supplied processor. All generated files are
 * stored in memory.
 *
 * @param processor
 * 		the processor to use when compiling, not null
 * @param sources
 * 		the sources to compile, not null, not containing null
 *
 * @throws CompilerMissingException
 * 		if no Java compiler is found at runtime
 * @throws IllegalArgumentException
 * 		if {@code processor} is null
 * @throws IllegalArgumentException
 * 		if {@code sources} is null
 * @throws IllegalArgumentException
 * 		if (@code sources} contains null
 */
public static CompilationResult compileUsingProcessor(
		final Processor processor,
		final Iterable<JavaFileObject> sources) {
	
	checkNotNull(processor, "Argument \'processor\' cannot be null.");
	checkNotNull(sources, "Argument \'sources\' cannot be null.");
	checkNotContainsNull(sources, "Argument \'sources\' cannot contain null.");
	
	final JavaCompiler compiler = checkNotNull(
			ToolProvider.getSystemJavaCompiler(),
			new CompilerMissingException("Cannot get elements if there is no Java compiler available at runtime."));
	
	final DiagnosticCollector<JavaFileObject> diagnostic = new DiagnosticCollector<>();
	final JavaFileManager baseFileManager = compiler.getStandardFileManager(diagnostic, Locale.getDefault(), UTF_8);
	final InMemoryJavaFileManager inMemoryFileManager = new InMemoryJavaFileManager(baseFileManager);
	
	final JavaCompiler.CompilationTask task = compiler.getTask(
			null,
			inMemoryFileManager,
			diagnostic,
			null,
			null,
			ImmutableSet.copyOf(sources));
	
	task.setProcessors(ImmutableSet.of(processor));
	
	final boolean success = task.call();
	
	return CompilationResult.create(success, diagnostic.getDiagnostics(), inMemoryFileManager.getOutputFiles());
}
 
Example 15
Project: openjdk-jdk10   File: PublicMethodsTest.java   Source Code and License Vote up 5 votes
/**
 * compile expanded template into a ClassLoader that sees compiled classes
 */
static TestClassLoader compile(String source) throws CompileException {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    if (javac == null) {
        throw new AssertionError("No Java compiler tool found.");
    }

    ErrorsCollector errorsCollector = new ErrorsCollector();
    StandardJavaFileManager standardJavaFileManager =
        javac.getStandardFileManager(errorsCollector, Locale.ROOT,
                                     Charset.forName("UTF-8"));
    TestFileManager testFileManager = new TestFileManager(
        standardJavaFileManager, source);

    JavaCompiler.CompilationTask javacTask;
    try {
        javacTask = javac.getTask(
            null, // use System.err
            testFileManager,
            errorsCollector,
            null,
            null,
            List.of(testFileManager.getJavaFileForInput(
                StandardLocation.SOURCE_PATH,
                TestFileManager.TEST_CLASS_NAME,
                JavaFileObject.Kind.SOURCE))
        );
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    javacTask.call();

    if (errorsCollector.hasError()) {
        throw new CompileException(errorsCollector.getErrors());
    }

    return new TestClassLoader(ClassLoader.getSystemClassLoader(),
                               testFileManager);
}
 
Example 16
Project: openjdk-jdk10   File: NegativeCyclicDependencyTest.java   Source Code and License Vote up 5 votes
/**
 * Compiles sources with -XDrawDiagnostics flag and
 * returns the output of compilation.
 *
 * @param sources sources
 * @return the result of compilation
 */
private String compile(ToolBox.JavaSource...sources) {
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StringWriter writer = new StringWriter();
    JavaCompiler.CompilationTask ct = jc.getTask(writer, null, null,
            Arrays.asList("-XDrawDiagnostics"),
            null, Arrays.asList(sources));
    if (ct.call()) {
        throw new RuntimeException("Expected compilation failure.");
    }
    return writer.toString().replace(ToolBox.lineSeparator, "\n");
}
 
Example 17
Project: openjdk-jdk10   File: TestTreePath.java   Source Code and License Vote up 5 votes
public void run() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager
            = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> tests
            = fileManager.getJavaFileObjects(writeTestFile());

        JavaCompiler.CompilationTask task =
            ToolProvider.getSystemJavaCompiler().getTask(
                    null, null, null,
                    Arrays.asList("-processor", this.getClass().getName()), null,
                    tests);
        task.call();
    }
}
 
Example 18
Project: pepper-box   File: InMemoryJavaCompiler.java   Source Code and License Vote up 4 votes
public static Class<?> compileSchemaClass(String className, String sourceCodeInText) throws Exception {

        //Java code source Object
        SourceCode sourceCode = new SourceCode(className, sourceCodeInText);

        //Java compiled code object
        CompiledCode compiledCode = new CompiledCode(className);

        //Custom classloader
        DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(InMemoryJavaCompiler.class.getClassLoader());

        //List of source codes to compile
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceCode);

        //Custom file manager takes source code object and classloader
        ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(compiler.getStandardFileManager(null, null, null), compiledCode, dynamicClassLoader);

        //Compile java code
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
        task.call();

         //Load and return class
        return dynamicClassLoader.loadClass(className);


    }
 
Example 19
Project: traute   File: JavacTestCompiler.java   Source Code and License Vote up 4 votes
@Override
@NotNull
public CompilationResult compile(@NotNull Collection<TestSource> testSources,
                                 @NotNull TrautePluginSettings settings)
{
    StringWriter output = new StringWriter();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    SimpleFileManager fileManager = new SimpleFileManager(compiler.getStandardFileManager(
            null,
            null,
            null
    ));
    List<SimpleSourceFile> compilationUnits = testSources.stream().map(SimpleSourceFile::new).collect(toList());
    List<String> arguments = new ArrayList<>();
    arguments.addAll(asList("-classpath", System.getProperty("java.class.path")));
    arguments.addAll(getAdditionalCompilerArgs(settings));
    JavaCompiler.CompilationTask task = compiler.getTask(output,
                                                         fileManager,
                                                         null,
                                                         arguments,
                                                         null,
                                                         compilationUnits);
    Boolean successfulCompilation = task.call();
    output.flush();
    if (!successfulCompilation) {
        return new CompilationResultImpl(() -> {
            throw new IllegalStateException(String.format(
                    "Failed to compile test class sources below:%n%n%s%nCompiler output: %s",
                    TestUtil.getSources(testSources), output));
            }, output.toString(), testSources);
    }

    Supplier<Collection<ClassFile>> compiledClassesSupplier = () -> {
        List<SimpleClassFile> compiledJavacClasses = fileManager.getCompiled();
        return compiledJavacClasses.stream().map(c -> {
            String className = c.getUri()
                                .getSchemeSpecificPart()
                                .replaceAll("/", "");
            return new ClassFileImpl(className, c.getCompiledBinaries());
        }).collect(toList());
    };

    return new CompilationResultImpl(compiledClassesSupplier, output.toString(), testSources);
}
 
Example 20
Project: javaide   File: JavacTrees.java   Source Code and License Vote up 4 votes
public static JavacTrees instance(JavaCompiler.CompilationTask task) {
    if (!(task instanceof JavacTaskImpl))
        throw new IllegalArgumentException();
    return instance(((JavacTaskImpl)task).getContext());
}