Example usage for javax.tools ToolProvider getSystemJavaCompiler

List of usage examples for javax.tools ToolProvider getSystemJavaCompiler

Introduction

In this page you can find the example usage for javax.tools ToolProvider getSystemJavaCompiler.

Prototype

public static JavaCompiler getSystemJavaCompiler() 

Source Link

Document

Returns the Java™ programming language compiler provided with this platform.

Usage

From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java

/**
 * F2 test./*from w  ww .j a v  a  2  s.  c o  m*/
 * 
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 */
@Test
public void f2Test()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within
    // in it...
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar");

    File helloWorldJava = new File(System.getProperty("user.dir")
            + "/generated-code/caserunners/org/bigtester/ate/model/project/CaseRunner8187856223134148550.java");

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);
    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        System.out.println("Yipe");
        // Create a new custom class loader, pointing to the directory that
        // contains the compiled
        // classes, this should point to the top of the package structure!
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() });
        // Load the class from the classloader by name....
        Class<?> loadedClass = classLoader
                .loadClass("org.bigtester.ate.model.project.CaseRunner8187856223134148550");
        // Create a new instance...
        Object obj = loadedClass.newInstance();
        // Santity check
        if (obj instanceof IRunTestCase) {
            ((IRunTestCase) obj).setCurrentExecutingTCName("test case name example");
            Assert.assertEquals(((IRunTestCase) obj).getCurrentExecutingTCName(), "test case name example");
            System.out.println("pass");
        }
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(),
                    diagnostic.getSource().toUri());
        }
    }
}

From source file:org.commonjava.test.compile.CompilerFixture.java

public CompilerResult compile(final File directory, final CompilerFixtureConfig config) throws IOException {
    if (directory == null || !directory.isDirectory()) {
        return null;
    }/*from   ww  w .  j  a v a2  s.  c om*/

    final File target = temp.newFolder(directory.getName() + "-classes");

    final List<File> sources = scan(directory, "**/*.java");

    final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    final Set<JavaFileObject> objects = new HashSet<>();

    for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(sources)) {
        objects.add(jfo);
    }

    final DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();

    final List<String> options = new ArrayList<>(Arrays.asList("-g", "-d", target.getCanonicalPath()));

    options.addAll(config.getExtraOptions());

    final StringBuilder sp = new StringBuilder();
    sp.append(directory.getCanonicalPath()).append(';').append(target.getCanonicalPath());

    File generatedSourceDir = null;

    final List<String> procOptions = new ArrayList<>(options);
    procOptions.add("-proc:only");

    final Set<File> seenSources = new HashSet<>(sources);
    Boolean result = Boolean.TRUE;

    final List<Class<? extends AbstractProcessor>> annoProcessors = config.getAnnotationProcessors();
    if (!annoProcessors.isEmpty()) {
        final StringBuilder sb = new StringBuilder();
        for (final Class<? extends AbstractProcessor> annoProcessor : annoProcessors) {
            if (sb.length() > 0) {
                sb.append(",");
            }

            sb.append(annoProcessor.getCanonicalName());
        }

        procOptions.add("-processor");
        procOptions.add(sb.toString());

        generatedSourceDir = temp.newFolder(directory.getName() + "-generated-sources");
        procOptions.add("-s");
        procOptions.add(generatedSourceDir.getCanonicalPath());

        sp.append(';').append(generatedSourceDir.getCanonicalPath());

        procOptions.add("-sourcepath");
        procOptions.add(sp.toString());

        int pass = 1;
        List<File> nextSources;
        do {
            logger.debug("pass: {} Compiling/processing generated sources with: '{}':\n  {}\n", pass,
                    new JoinLogString(procOptions, ", "), new JoinLogString(sources, "\n  "));

            for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
                objects.add(jfo);
            }

            final CompilationTask task = javac.getTask(null, fileManager, diags, procOptions, null, objects);
            result = task.call();

            nextSources = scan(generatedSourceDir, "**/*.java");

            logger.debug("\n\nNewly scanned sources:\n  {}\n\nPreviously seen sources:\n  {}\n\n",
                    new JoinLogString(nextSources, "\n  "), new JoinLogString(seenSources, "\n  "));
            nextSources.removeAll(seenSources);
            seenSources.addAll(nextSources);
            pass++;
        } while (pass < config.getMaxAnnotationProcessorPasses() && !nextSources.isEmpty());
    }

    if (result) {
        options.add("-sourcepath");
        options.add(sp.toString());

        options.add("-proc:none");

        for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
            objects.add(jfo);
        }

        final CompilationTask task = javac.getTask(null, fileManager, diags, options, null, objects);
        result = task.call();

        logger.debug("Compiled classes:\n  {}\n\n", new JoinLogString(scan(target, "**/*.class"), "\n  "));
    } else {
        logger.warn("Annotation processing must have failed. Skipping compilation step.");
    }

    for (final Diagnostic<? extends JavaFileObject> diag : diags.getDiagnostics()) {
        logger.error(String.valueOf(diag));
    }

    final CompilerResult cr = new CompilerResultBuilder().withClasses(target).withDiagnosticCollector(diags)
            .withGeneratedSources(generatedSourceDir).withResult(result).build();

    results.add(cr);
    return cr;
}

From source file:org.deventropy.shared.utils.ClassUtilTest.java

@Test
public void testCallerClassloader() throws Exception {

    // Write the source file - see
    // http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class
    final File sourceFolder = workingFolder.newFolder();
    // Prepare source somehow.
    final String source = "package test; public class Test { }";
    // Save source in .java file.
    final File sourceFile = new File(sourceFolder, "test/Test.java");
    sourceFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(sourceFile, source, "UTF-8");

    // Compile the file
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
    compiler.getTask(null, fileManager, null, null, null, compilationUnit).call();

    // Create the class loader
    final URLClassLoader urlcl = new URLClassLoader(new URL[] { sourceFolder.toURI().toURL() });
    final Class<?> loadedClass = urlcl.loadClass("test.Test");

    final ContextClNullingObject testObj = new ContextClNullingObject(loadedClass.newInstance());
    final Thread worker = new Thread(testObj);
    worker.start();/*  ww  w.jav a2s .co  m*/
    worker.join();

    assertEquals(urlcl, testObj.getReturnedCl());

    urlcl.close();
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Compila el java en tiempo real//from  w w w. j av a2 s  . c  o m
 *
 * @return xito de la operacin
 */
protected boolean compileEDMCrossWalk() {
    boolean status = false;

    SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(canonicalCrosswalkName,
            edmCrossWalkContent);
    JavaFileObject javaFileObjects[] = new JavaFileObject[] { fileObject };

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

    // libreras necesarias para linkar con el fuente a compilar
    String myInstallerPackagesDirPath = myInstallerDirPath + fileSeparator + "packages" + fileSeparator;
    StringBuilder jars = (fileSeparator.equals("\\"))
            ? new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar;")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar;")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar")
            : new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar:")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar:")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar");

    String[] compileOptions = new String[] { "-d", myInstallerWorkDirPath, "-source", "1.6", "-target", "1.6",
            "-cp", jars.toString() };
    Iterable<String> compilationOptionss = Arrays.asList(compileOptions);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);

    JavaCompiler.CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics,
            compilationOptionss, null, compilationUnits);

    status = compilerTask.call();

    if (!status) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            installerEDMDisplay
                    .showMessage("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic);
        }
    }

    try {
        stdFileManager.close();
    } catch (IOException e) {
        showException(e);
    }
    return status;
}

From source file:org.ebayopensource.turmeric.eclipse.test.util.ProjectArtifactValidator.java

private void compileSrc(String filePath) {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    int result = compiler.run(null, null, null, filePath);
}

From source file:org.ebayopensource.turmeric.tools.codegen.AbstractServiceGeneratorTestCase.java

protected void compileJavaFile(String file) {
    JavaCompiler compiler = (JavaCompiler) ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, file);
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryFileGenerationTest.java

/**
 * Class files are generated under the same dir as java files
 * /*w ww  . java2  s .com*/
 * @param javaFile the java file to compile.
 * @throws Exception
 */
private void compileJavaFiles(File binDir, File javaFile) throws Exception {
    PathAssert.assertFileExists("Java Source", javaFile);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    LinkedList<File> classpath = ClassPathUtil.getClassPath();
    classpath.add(0, binDir);
    StringBuilder cp = new StringBuilder();
    ClassPathUtil.appendClasspath(cp, classpath);
    if (compiler.run(null, System.out, System.err, "-cp", cp.toString(), javaFile.getAbsolutePath()) != 0) {
        throw new Exception("Exception while compiling file");
    }
}

From source file:org.echocat.redprecursor.impl.sun.compilertree.SunNodeFactoryIntegrationTest.java

private void compile(File... files) {
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    final Iterable<? extends JavaFileObject> compilationUnits2 = fileManager.getJavaFileObjects(files);
    final DiagnosticCollector<Object> listener = null; //new DiagnosticCollector<Object>();
    final CompilationTask task = compiler.getTask(null, fileManager, listener,
            Arrays.<String>asList("-processor", RedprecursorProcessor.class.getName()), null,
            compilationUnits2);/*from  w  ww.j  a v  a  2  s. co m*/
    //final CompilationTask task = compiler.getTask(null, fileManager, listener, Arrays.<String>asList(), null, compilationUnits2);
    task.call();
}

From source file:org.evosuite.junit.FooTestClassLoader.java

private static boolean compileJavaFile(String javaBinDirName, File javaFile) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        return false; //fail
    }/*from  w w  w  . j a  va 2 s.  c om*/

    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;
}

From source file:org.evosuite.junit.JUnitAnalyzer.java

/**
 * Check if it is possible to use the Java compiler.
 * //from   www  .ja v  a2 s.  c  o m
 * @return
 */
public static boolean isJavaCompilerAvailable() {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    return compiler != null;
}