Search in sources :

Example 6 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project mapstruct by mapstruct.

the class JdkCompilingStatement method compileWithSpecificCompiler.

@Override
protected CompilationOutcomeDescriptor compileWithSpecificCompiler(CompilationRequest compilationRequest, String sourceOutputDir, String classOutputDir, String additionalCompilerClasspath) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(getSourceFiles(compilationRequest.getSourceClasses()));
    try {
        fileManager.setLocation(StandardLocation.CLASS_PATH, COMPILER_CLASSPATH_FILES);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(classOutputDir)));
        fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Arrays.asList(new File(sourceOutputDir)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ClassLoader processorClassloader;
    if (additionalCompilerClasspath == null) {
        processorClassloader = DEFAULT_PROCESSOR_CLASSLOADER;
    } else {
        processorClassloader = new ModifiableURLClassLoader(new FilteringParentClassLoader("org.mapstruct.")).withPaths(PROCESSOR_CLASSPATH).withPath(additionalCompilerClasspath).withOriginsOf(compilationRequest.getServices().values());
    }
    CompilationTask task = compiler.getTask(null, fileManager, diagnostics, compilationRequest.getProcessorOptions(), null, compilationUnits);
    task.setProcessors(Arrays.asList((Processor) loadAndInstantiate(processorClassloader, MappingProcessor.class)));
    boolean compilationSuccessful = task.call();
    return CompilationOutcomeDescriptor.forResult(SOURCE_DIR, compilationSuccessful, diagnostics.getDiagnostics());
}
Also used : Processor(javax.annotation.processing.Processor) MappingProcessor(org.mapstruct.ap.MappingProcessor) JavaCompiler(javax.tools.JavaCompiler) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) MappingProcessor(org.mapstruct.ap.MappingProcessor) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Example 7 with CompilationTask

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

the class CodegenUtils method compileClassJavac.

// //////////////////////////
// JAVAC-specific methods (used for hadoop environments)
private static Class<?> compileClassJavac(String name, String src) {
    try {
        // create working dir on demand
        if (_workingDir == null)
            createWorkingDir();
        // write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);
        // get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");
        // prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        // prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(ftmp));
        // prepare class path
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);
        // compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();
        // output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if (tmp.getKind() == Kind.ERROR)
            System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);
        // dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir }, CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        LOG.error("Failed to compile class " + name + ": \n" + src);
        throw new DMLRuntimeException("Failed to compile class " + name + ".", ex);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) IOException(java.io.IOException) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) JavaFileObject(javax.tools.JavaFileObject) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) URLClassLoader(java.net.URLClassLoader) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Example 8 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project dsl-json by ngs-doo.

the class AbstractAnnotationProcessorTest method compileTestCase.

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>
 * The compilation units and all their dependencies are expected to be on the classpath.
 *
 * @param compilationUnitPaths the paths of the source files to compile, as would be expected
 *                             by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 * as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 */
protected Boolean compileTestCase(String[] compilationUnitPaths, List<String> arguments, List<Diagnostic<? extends JavaFileObject>> diagnostics) {
    assert (compilationUnitPaths != null);
    Collection<File> compilationUnits;
    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units " + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);
    ArrayList<String> compileArgs = new ArrayList<String>();
    compileArgs.add("-proc:only");
    compileArgs.addAll(arguments);
    /*
         * Call the compiler with the "-proc:only" option. The "class names"
         * option (which could, in principle, be used instead of compilation
         * units for annotation processing) isn't useful in this case because
         * only annotations on the classes being compiled are accessible.
         *
         * Information about the classes being compiled (such as what they are annotated
         * with) is *not* available via the RoundEnvironment. However, if these classes
         * are annotations, they certainly need to be validated.
         */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, compileArgs, null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    Boolean compilationSuccessful = task.call();
    try {
        fileManager.close();
    } catch (IOException ignore) {
    }
    diagnostics.addAll(diagnosticCollector.getDiagnostics());
    if (diagnostics.size() > 0 && diagnostics.get(0).getKind() == Kind.WARNING && diagnostics.get(0).getMessage(Locale.ENGLISH).startsWith("Supported source version 'RELEASE_6' from " + "annotation processor 'com.dslplatform.json.CompiledJsonProcessor' less than -source")) {
        diagnostics.remove(0);
    }
    return compilationSuccessful;
}
Also used : IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) File(java.io.File)

Example 9 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project kalang by kasonyang.

the class MemoryCompiler method compile.

protected boolean compile(Collection<JavaFileObject> javaFileObjects) {
    StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
    fileManager = createFileManager(sfm);
    List<String> options = new LinkedList<>();
    String classPath = buildClassPathOption();
    if (classPath != null && !classPath.isEmpty()) {
        options.add("-classpath");
        options.add(classPath);
    }
    diagnosticCollector = new DiagnosticCollector();
    CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, options, null, javaFileObjects);
    return task.call();
}
Also used : StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 10 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project evosuite by EvoSuite.

the class FooTestClassLoader method compileJavaFile.

private static boolean compileJavaFile(String javaBinDirName, File javaFile) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        // fail
        return false;
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.getDefault(), Charset.forName("UTF-8"));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(javaFile));
    List<String> optionList;
    optionList = new ArrayList<String>();
    optionList.addAll(Arrays.asList("-d", javaBinDirName));
    CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits);
    boolean compiled = task.call();
    try {
        fileManager.close();
    } catch (IOException e) {
        return false;
    }
    return compiled;
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

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