Example usage for javax.tools JavaCompiler getTask

List of usage examples for javax.tools JavaCompiler getTask

Introduction

In this page you can find the example usage for javax.tools JavaCompiler getTask.

Prototype

CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options,
        Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits);

Source Link

Document

Creates a future for a compilation task with the given components and arguments.

Usage

From source file:gov.va.vinci.leo.tools.AutoCompile.java

/**
 * Compile the files in the list.  Optionally provide a destination directory where the
 * compiled files should be placed./* ww w.  j a v  a  2  s  . c  om*/
 *
 * @param files           List of java files to be compiled
 * @param outputDirectory Optional, output directory where the compiled files will be written
 * @throws Exception If there are errors compiling the files or we are unable to get a compiler
 */
public static void compileFiles(File[] files, String outputDirectory) throws Exception {
    //If the list is null there is nothing to do
    if (files == null) {
        return;
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new Exception("Unable to get a Compiler from the ToolProvider");
    }
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<String> compilationOptions = (StringUtils.isBlank(outputDirectory)) ? null
            : Arrays.asList(new String[] { "-d", outputDirectory });
    try {
        Iterable<? extends JavaFileObject> compilationUnits = stdFileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(files));
        compiler.getTask(null, stdFileManager, null, compilationOptions, null, compilationUnits).call();
    } finally {
        stdFileManager.close();
    } //finally

}

From source file:de.xirp.ate.ATEManager.java

/**
 * Compiles the given Java {@link java.io.File} to the
 * corresponding byte code class files./*w  ww .j  a  va 2s.  c  o  m*/
 * 
 * @param javaFile
 *            The file containing the Java code.
 */
public static void compile(File javaFile) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Collections.singletonList(javaFile));
    compiler.getTask(new PrintWriter(System.out), fileManager, null, null, null, compilationUnits).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
}

From source file:cop.raml.processor.AbstractProcessorTest.java

protected static boolean runAnnotationProcessor(File dir) throws URISyntaxException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Set<JavaFileObject> compilationUnits = new LinkedHashSet<>();

    for (File file : (List<File>) FileUtils.listFiles(dir, JAVA_FILE_FILTER, DirectoryFileFilter.INSTANCE))
        compilationUnits.add(new SimpleJavaFileObjectImpl(file, JavaFileObject.Kind.SOURCE));

    List<String> options = new ArrayList<>();
    //        options.put("-Apackages=com.bosch");
    //        options.put("-AfilterRegex=AnalysisController");
    //        options.put("-Aversion=0.8");
    options.add("-d");
    options.add("target");

    JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null, compilationUnits);
    task.setProcessors(Collections.singleton(new RestProcessor()));

    return task.call();
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder,
        GeneratorContext context) {/*from   www.  ja v  a  2s  .  c o m*/
    StandardJavaFileManager fileManager = null;
    boolean success = true;
    try {
        List<String> compilerFiles = GeneratorUtil.getFiles(srcFolder, new String[] { "java" });

        GeneratorUtil.createOutputDir(destFolder);

        List<String> options = new ArrayList<String>();
        options.add("-classpath");
        String classPathStr = GeneratorUtil.getFiles(libFolder, new String[] { "jar" }, File.pathSeparator);

        options.add(classPathStr);
        options.add("-nowarn");
        options.add("-Xlint:-unchecked");
        options.add("-d");
        options.add(destFolder);

        options.add("-s");
        options.add(srcFolder);

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(compilerFiles);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
                compilationUnits);
        success = task.call();

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            //context.getLogger().error(diagnostic.getCode());
            //context.getLogger().error(diagnostic.getKind().toString());
            //context.getLogger().error(diagnostic.getPosition() + "");
            //context.getLogger().error(diagnostic.getStartPosition() + "");
            //context.getLogger().error(diagnostic.getEndPosition() + "");
            //context.getLogger().error(diagnostic.getSource().toString());
            context.getLogger().error(diagnostic.toString());
        }
    } catch (Throwable t) {
        context.getLogger().error("Error compiling java code", t);
    } finally {
        try {
            fileManager.close();
        } catch (Throwable t) {
        }
    }
    return success;
}

From source file:com.jhash.oimadmin.Utils.java

public static DiagnosticCollector<JavaFileObject> compileJava(String className, String code,
        String outputFileLocation) {
    logger.trace("Entering compileJava({},{},{})", new Object[] { className, code, outputFileLocation });
    File outputFileDirectory = new File(outputFileLocation);
    logger.trace("Validating if the output location {} exists and is a directory", outputFileLocation);
    if (outputFileDirectory.exists()) {
        if (outputFileDirectory.isDirectory()) {
            try {
                logger.trace("Deleting the directory and its content");
                FileUtils.deleteDirectory(outputFileDirectory);
            } catch (IOException exception) {
                throw new OIMAdminException(
                        "Failed to delete directory " + outputFileLocation + " and its content", exception);
            }/*from  w  w  w  .j  av a  2  s .co  m*/
        } else {
            throw new InvalidParameterException(
                    "The location " + outputFileLocation + " was expected to be a directory but it is a file.");
        }
    }
    logger.trace("Creating destination directory for compiled class file");
    outputFileDirectory.mkdirs();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
                "Failed to locate a java compiler. Please ensure that application is being run using JDK (Java Development Kit) and NOT JRE (Java Runtime Environment) ");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<File> files = Arrays.asList(new File(outputFileLocation));
    boolean success = false;
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    try {
        JavaFileObject javaFileObject = new InMemoryJavaFileObject(className, code);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, files);

        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics,
                Arrays.asList("-source", "1.6", "-target", "1.6"), null, Arrays.asList(javaFileObject));
        success = task.call();
        fileManager.close();
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to compile " + className, exception);
    }

    if (!success) {
        logger.trace("Exiting compileJava(): Return Value {}", diagnostics);
        return diagnostics;
    } else {
        logger.trace("Exiting compileJava(): Return Value null");
        return null;
    }
}

From source file:org.glowroot.common2.repo.util.Compilations.java

public static Class<?> compile(String source) throws Exception {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();

    IsolatedClassLoader isolatedClassLoader = new IsolatedClassLoader();

    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(diagnosticCollector,
            Locale.ENGLISH, UTF_8);
    standardFileManager.setLocation(StandardLocation.CLASS_PATH, getCompilationClassPath());
    JavaFileManager fileManager = new IsolatedJavaFileManager(standardFileManager, isolatedClassLoader);
    try {// w w w.j  av  a 2  s.c  om
        List<JavaFileObject> compilationUnits = Lists.newArrayList();

        String className = getPublicClassName(source);
        int index = className.lastIndexOf('.');
        String simpleName;
        if (index == -1) {
            simpleName = className;
        } else {
            simpleName = className.substring(index + 1);
        }
        compilationUnits.add(new SourceJavaFileObject(simpleName, source));

        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnosticCollector, null,
                null, compilationUnits);
        task.call();

        List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
        if (!diagnostics.isEmpty()) {
            List<String> compilationErrors = Lists.newArrayList();
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
                compilationErrors.add(checkNotNull(diagnostic.toString()));
            }
            throw new CompilationException(compilationErrors);
        }
        if (className.isEmpty()) {
            throw new CompilationException(ImmutableList.of("Class must be public"));
        }
        return isolatedClassLoader.loadClass(className);
    } finally {
        fileManager.close();
    }
}

From source file:com.asual.summer.core.faces.FacesFunctionMapper.java

public Method resolveFunction(String namespace, final String fn) {

    try {/*ww  w  .  jav a2  s.c o m*/

        String className = fn + "Script";

        if (!classes.containsKey(className)) {

            StringBuilder out = new StringBuilder();
            out.append("public class " + className + " {");
            out.append("   private static String fn = \"" + fn + "\";");
            out.append("   public static Object call(Object... args) throws Exception {");
            out.append("      return Class.forName(\"com.asual.summer.core.util.ScriptUtils\")");
            out.append(
                    "         .getDeclaredMethod(\"call\", String.class, Object[].class).invoke(null, fn, args);");
            out.append("   }");
            out.append("}");

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            JavaFileManager jfm = new MemoryFileManager(compiler);
            JavaFileObject file = new JavaObjectFromString(className, out.toString());
            compiler.getTask(null, jfm, null, null, null, Arrays.asList(file)).call();
        }

        return Class.forName(className, true, classLoader).getDeclaredMethod("call", Object[].class);

    } catch (Exception e) {

        logger.error(e.getMessage(), e);
    }

    return null;
}

From source file:com.github.aliakhtar.annoTest.util.Compiler.java

private boolean compile(Processor processor, SourceFile... sourceFiles) throws Exception {
    Builder<String> builder = ImmutableList.builder();
    builder.add("-classpath").add(buildClassPath(outputDir));
    builder.add("-d").add(outputDir.getAbsolutePath());

    for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
        builder.add("-A" + entry.getKey() + "=" + entry.getValue());
    }//from www  .  ja va 2 s  . com

    File[] files = new File[sourceFiles.length];
    for (int i = 0; i < sourceFiles.length; i++) {
        files[i] = writeSourceFile(sourceFiles[i]);
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(files);
    CompilationTask compilationTask = compiler.getTask(null, null, null, builder.build(), null,
            javaFileObjects);
    if (processor != null)
        compilationTask.setProcessors(Arrays.asList(processor));

    Boolean success = compilationTask.call();
    fileManager.close();
    return success;
}

From source file:net.morematerials.manager.HandlerManager.java

private void compile(File file) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    CompilationTask task = compiler.getTask(null, fileManager, null, this.compilerOptions, null,
            compilationUnits);/*from w  w w  .j a v a2 s.  c  o  m*/
    task.call();
}

From source file:com.googlecode.jsonschema2pojo.integration.util.Compiler.java

public void compile(File directory, String classpath) {

    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(findAllSourceFiles(directory));

    if (compilationUnits.iterator().hasNext()) {
        Boolean success = javaCompiler
                .getTask(null, fileManager, null, asList("-classpath", classpath), null, compilationUnits)
                .call();/*from   w w  w  .j  a  v  a 2 s . co  m*/
        assertThat("Compilation was not successful, check stdout for errors", success, is(true));
    }

}