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:com.kelveden.rastajax.core.DynamicClassCompiler.java

private void compileFromFiles(final Set<String> sourceFilePaths) {

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

    try {//from w  ww .j  a v  a2  s.  c om
        fileManager = compiler.getStandardFileManager(null, null, null);

        final Iterable<? extends JavaFileObject> fileObjects = fileManager
                .getJavaFileObjectsFromStrings(sourceFilePaths);

        if (!compiler.getTask(null, null, null, null, null, fileObjects).call()) {
            throw new RuntimeException("Failed to compile class.");
        }
    } finally {
        IOUtils.closeQuietly(fileManager);
    }
}

From source file:gruifo.output.jsni.BaseJsTest.java

private boolean compile(final String file) {
    final File fileToCompile = getJavaSourceFile(file);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("No compiler installed", compiler);
    final List<String> options = new ArrayList<>();
    options.add("-source");
    options.add("1.6");
    options.add("-Xlint:-options");
    options.add("-classpath");
    options.add(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final JavaCompiler.CompilationTask task = compiler.getTask(/*default System.err*/ null,
            /*std file manager*/ null, /*std DiagnosticListener */ null, /*compiler options*/ options,
            /*no annotation*/ null, fileManager.getJavaFileObjects(fileToCompile));
    return task.call();
}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

private static Class<FoundationLoggingMarkerFormatter> generateMarkerClass(String sourceCode,
        String newClassName) {/*from   www .  j  a  v  a  2 s.c o m*/

    try {

        // We get an instance of JavaCompiler. Then
        // we create a file manager
        // (our custom implementation of it)
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));

        // Dynamic compiling requires specifying
        // a list of "files" to compile. In our case
        // this is a list containing one "file" which is in our case
        // our own implementation (see details below)
        List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>();
        jfiles.add(new DynamicJavaSourceCodeObject(newClassName, sourceCode));

        List<String> optionList = new ArrayList<String>();
        // set compiler's classpath to be same as the runtime's
        optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));

        // We specify a task to the compiler. Compiler should use our file
        // manager and our list of "files".
        // Then we run the compilation with call()
        compiler.getTask(null, fileManager, null, optionList, null, jfiles).call();

        // Creating an instance of our compiled class and
        // running its toString() method
        Class<FoundationLoggingMarkerFormatter> clazz = (Class<FoundationLoggingMarkerFormatter>) fileManager
                .getClassLoader(null).loadClass(newClassName);

        return clazz;
    } catch (Exception e) {
        throw new UnsupportedOperationException("can't create class of: " + newClassName, e);
    }
}

From source file:adalid.util.meta.MetaJavaCompiler.java

public static void compile() {
    String dp1 = System.getProperties().getProperty("user.dir");
    String sep = System.getProperties().getProperty("file.separator");
    File src = new File(dp1 + sep + "src");
    File trg = new File(dp1 + sep + "bin");
    boolean dir = trg.isDirectory() || trg.mkdirs();
    List<File> files = getJavaFiles(src);
    // Get the java compiler provided with this platform
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // Get the writer for the compiler output
    StringWriter out = new StringWriter();
    // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics
    DiagnosticListener<JavaFileObject> diagnosticListener1 = null; // new DiagnosticCollector<JavaFileObject>();
    // Get the locale to apply when formatting diagnostics; null means the default locale
    Locale locale = null;/*from   w  w w .ja  va2 s. c  o m*/
    // Get the character set used for decoding bytes; if null use the platform default
    Charset charset = null;
    // Get an instance of the standard file manager implementation
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener1, locale, charset);
    // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics
    DiagnosticListener<JavaFileObject> diagnosticListener2 = null; // new DiagnosticCollector<JavaFileObject>();
    // Get the list of compiler options, null means no options
    List<String> options = Arrays
            .asList(new String[] { "-g", "-source", "1.7", "-Xlint:unchecked", "-d", trg.getAbsolutePath() });
    // Get the list of class names (for annotation processing), null means no class names
    List<String> classes = null;
    // Get the list of java file objects to compile
    Iterable<? extends JavaFileObject> units = fileManager.getJavaFileObjectsFromFiles(files);
    // Create the compilation task
    CompilationTask task = compiler.getTask(out, fileManager, diagnosticListener2, options, classes, units);
    // Perform the compilation task
    // task.call(); // java.lang.NullPointerException at com.sun.tools.javac.api.JavacTaskImpl.parse(JavacTaskImpl.java:228)
    if (task instanceof JavacTask) {
        javacTask(task);
    }
}

From source file:com.webcohesion.enunciate.modules.java_json_client.JavaJSONClientModule.java

protected File compileClientSources(File sourceDir) {
    File compileDir = getCompileDir();
    compileDir.mkdirs();/*from  w  w w .j av  a  2 s. c o  m*/

    //Compile the java files.
    if (!isDisableCompile()) {
        if (!isUpToDateWithSources(compileDir)) {
            List<File> sources = findJavaFiles(sourceDir);
            if (sources != null && !sources.isEmpty()) {
                String classpath = this.enunciate.writeClasspath(enunciate.getClasspath());
                JavaCompiler compiler = JavacTool.create();
                List<String> options = Arrays.asList("-source", "1.5", "-target", "1.5", "-encoding", "UTF-8",
                        "-cp", classpath, "-d", compileDir.getAbsolutePath(), "-nowarn");
                JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null,
                        compiler.getStandardFileManager(null, null, null).getJavaFileObjectsFromFiles(sources));
                if (!task.call()) {
                    throw new EnunciateException("Compile failed of Java JSON client-side classes.");
                }
            } else {
                debug("No Java JSON client classes to compile.");
            }
        } else {
            info("Skipping compilation of Java JSON client classes as everything appears up-to-date...");
        }
    }

    return compileDir;

}

From source file:de.uni_koblenz.jgralab.utilities.tgschema2java.TgSchema2Java.java

public void compile() throws Exception {
    String packageFolder = schema.getPathName();
    File folder = new File(commitPath + File.separator + packageFolder);
    List<File> files1 = findFilesInDirectory(folder);

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

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
    ArrayList<String> options = new ArrayList<>();
    if (classpath != null) {
        options.add("-cp");
        options.add(classpath);//  w  w w .ja  v a 2 s . co m
    }
    System.out.print("Starting compilation....");
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    System.out.println("finished");
}

From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java

private void compileWebServiceInterface() {
    java.util.Set<String> processedFocusDomainSet = (java.util.Set<String>) getScriptContext().getMemory()
            .get("processedFocusDomainSet");

    if (processedFocusDomainSet == null) {
        processedFocusDomainSet = new java.util.HashSet<String>();
        getScriptContext().getMemory().put("processedFocusDomainSet", processedFocusDomainSet);
    }/*from  w w w. ja v a2 s .  c  om*/

    processedFocusDomainSet.add(getScriptContext().getFocusDomain());

    if (processedFocusDomainSet.containsAll(getScriptContext().retrieveDomainSet()) == true) { //All domains have been processed so now we can compile and generate WSDL

        StandardJavaFileManager fileManager = null;

        try {
            String jaxbPojoPath = GeneratorUtil.getJaxbPojoPath(getScriptContext());
            String servicePath = GeneratorUtil.getServicePath(getScriptContext());
            String serviceImplPath = GeneratorUtil.getServiceImplPath(getScriptContext());
            String projectRoot = getScriptContext().getProperties().getProperty("PROJECT_ROOT");

            List<String> compilerFiles = GeneratorUtil.getFiles(jaxbPojoPath, new String[] { "java" });
            compilerFiles.addAll(GeneratorUtil.getFiles(servicePath, new String[] { "java" }));
            compilerFiles.addAll(GeneratorUtil.getFiles(serviceImplPath, new String[] { "java" }));

            getScriptContext().logInfo("Compiling files: " + compilerFiles);
            // Check if output directory exist, create it
            GeneratorUtil.createOutputDir(projectRoot + File.separator + "classes");

            List<String> options = new ArrayList<String>();
            options.add("-classpath");
            String classPathStr = GeneratorUtil
                    .getFiles(new java.io.File(getScriptContext().getGeneratorBase()).getAbsolutePath()
                            + File.separator + "lib", new String[] { "jar" }, File.pathSeparator)
                    + File.pathSeparator
                    + new java.io.File(projectRoot + File.separatorChar + "classes").getAbsolutePath();

            getScriptContext().logInfo("compiler classpath is: " + classPathStr);

            options.add(classPathStr);

            options.add("-d");
            options.add(projectRoot + File.separator + "classes");

            options.add("-s");
            options.add(projectRoot + File.separator + "src/generated");

            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);
            boolean success = task.call();

            for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
                getScriptContext().logInfo(diagnostic.getCode());
                getScriptContext().logInfo(diagnostic.getKind().toString());
                getScriptContext().logInfo(diagnostic.getPosition() + "");
                getScriptContext().logInfo(diagnostic.getStartPosition() + "");
                getScriptContext().logInfo(diagnostic.getEndPosition() + "");
                getScriptContext().logInfo(diagnostic.getSource().toString());
                getScriptContext().logInfo(diagnostic.getMessage(null));
            }
        } catch (Throwable t) {
            getScriptContext().logError(t);
        } finally {
            try {
                fileManager.close();
            } catch (Throwable t) {
            }
        }

        for (String focusDomain : getScriptContext().retrieveDomainSet()) {
            generateWebServiceArtifacts(focusDomain);
        }
    }
}

From source file:com.yahoo.maven.visitor.SuccessfulCompilationAsserter.java

public void assertNoCompilationErrors() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null,
            StandardCharsets.UTF_8)) {
        List<File> javaFiles = new ArrayList<>();
        try (Stream<Path> stream = Files.walk(scratchSpace)) {
            Iterator<Path> iterator = stream.iterator();
            while (iterator.hasNext()) {
                Path path = iterator.next();
                if (Files.isRegularFile(path) && "java".equals(FilenameUtils.getExtension(path.toString()))) {
                    javaFiles.add(path.toFile());
                }//ww w.  j a  v  a 2s.  co  m
            }
        }
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(javaFiles);
        compiler.getTask(null, fileManager, diagnostics,
                Arrays.asList("-classpath", System.getProperty("java.class.path")), null, compilationUnits)
                .call();
    }
    int errors = 0;
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        if (Diagnostic.Kind.ERROR.equals(diagnostic.getKind())) {
            System.err.println(diagnostic);
            errors++;
        }
    }
    assertEquals(0, errors);
}

From source file:com.webcohesion.enunciate.modules.java_xml_client.JavaXMLClientModule.java

protected File compileClientSources(File sourceDir) {
    File compileDir = getCompileDir();
    compileDir.mkdirs();//  w w w .j  a  v  a 2 s  .c om

    //Compile the java files.
    if (!isDisableCompile()) {
        if (!isUpToDateWithSources(compileDir)) {
            List<File> sources = findJavaFiles(sourceDir);
            if (sources != null && !sources.isEmpty()) {
                String classpath = this.enunciate.writeClasspath(enunciate.getClasspath());
                JavaCompiler compiler = JavacTool.create();
                List<String> options = Arrays.asList("-source", "1.5", "-target", "1.5", "-encoding", "UTF-8",
                        "-cp", classpath, "-d", compileDir.getAbsolutePath(), "-nowarn");
                JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null,
                        compiler.getStandardFileManager(null, null, null).getJavaFileObjectsFromFiles(sources));
                if (!task.call()) {
                    throw new EnunciateException("Compile failed of Java client-side classes.");
                }
            } else {
                debug("No Java XML client classes to compile.");
            }
        } else {
            info("Skipping compilation of Java client classes as everything appears up-to-date...");
        }
    }

    return compileDir;

}

From source file:com.sillelien.dollar.DocTestingVisitor.java

@Override
public void visit(@NotNull VerbatimNode node) {
    if ("java".equals(node.getType())) {
        try {/* w  w  w .j a va  2 s  .co m*/
            String name = "DocTemp" + System.currentTimeMillis();
            File javaFile = new File("/tmp/" + name + ".java");
            File clazzFile = new File("/tmp/" + name + ".class");
            clazzFile.getParentFile().mkdirs();
            FileUtils.write(javaFile,
                    "import com.sillelien.dollar.api.*;\n"
                            + "import static com.sillelien.dollar.api.DollarStatic.*;\n" + "public class "
                            + name + " implements java.lang.Runnable{\n" + "    public void run() {\n"
                            + "        " + node.getText() + "\n" + "    }\n" + "}");
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            final StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null);
            JavaCompiler.CompilationTask task;
            DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() {

                @Override
                public void report(Diagnostic diagnostic) {
                    System.out.println(diagnostic);
                    throw new RuntimeException(diagnostic.getMessage(Locale.getDefault()));
                }
            };

            try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(clazzFile)) {
                task = javac.getTask(new OutputStreamWriter(fileOutputStream), jfm, diagnosticListener, null,
                        null, jfm.getJavaFileObjects(javaFile));
            }
            task.call();

            try {
                // Convert File to a URL
                URL url = clazzFile.getParentFile().toURL();
                URL[] urls = new URL[] { url };
                ClassLoader cl = new URLClassLoader(urls);
                Class cls = cl.loadClass(name);
                ((Runnable) cls.newInstance()).run();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println("Parsed: " + node.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}