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.evosuite.junit.JUnitAnalyzer.java

private static List<File> compileTests(List<TestCase> tests, File dir) {

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);/*from ww w. ja  v a 2s .  c  om*/

    //to get name, remove all package before last '.'
    int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1;
    String name = Properties.TARGET_CLASS.substring(beginIndex);
    name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX; //postfix

    try {
        //now generate the JUnit test case
        List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST);
        for (File file : generated) {
            if (!file.exists()) {
                logger.error("Supposed to generate " + file + " but it does not exist");
                return null;
            }
        }

        //try to compile the test cases
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            logger.error("No Java compiler is available");
            return null;
        }

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        Locale locale = Locale.getDefault();
        Charset charset = Charset.forName("UTF-8");
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset);

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

        List<String> optionList = new ArrayList<>();
        String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath();
        if (JarPathing.containsAPathingJar(evosuiteCP)) {
            evosuiteCP = JarPathing.expandPathingJars(evosuiteCP);
        }

        String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();
        if (JarPathing.containsAPathingJar(targetProjectCP)) {
            targetProjectCP = JarPathing.expandPathingJars(targetProjectCP);
        }

        String classpath = targetProjectCP + File.pathSeparator + evosuiteCP;

        optionList.addAll(Arrays.asList("-classpath", classpath));

        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
                compilationUnits);
        boolean compiled = task.call();
        fileManager.close();

        if (!compiled) {
            logger.error("Compilation failed on compilation units: " + compilationUnits);
            logger.error("Classpath: " + classpath);
            //TODO remove
            logger.error("evosuiteCP: " + evosuiteCP);

            for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
                if (diagnostic.getMessage(null).startsWith("error while writing")) {
                    logger.error("Error is due to file permissions, ignoring...");
                    return generated;
                }
                logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber());
            }

            StringBuffer buffer = new StringBuffer();
            for (JavaFileObject sourceFile : compilationUnits) {
                List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath()));

                buffer.append(compilationUnits.iterator().next().toString() + "\n");

                for (int i = 0; i < lines.size(); i++) {
                    buffer.append((i + 1) + ": " + lines.get(i) + "\n");
                }
            }
            logger.error(buffer.toString());
            return null;
        }

        return generated;

    } catch (IOException e) {
        logger.error("" + e, e);
        return null;
    }
}

From source file:org.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));

    ArrayList<String> options = new ArrayList<String>();
    options.add("-classpath");
    options.add(classpath);//from www .  ja  v a 2  s .c  o m
    options.add("-encoding");
    options.add("UTF8");
    if (compilationUnits.iterator().hasNext()) {
        Boolean success = javaCompiler.getTask(null, fileManager, null, options, null, compilationUnits).call();
        assertThat("Compilation was not successful, check stdout for errors", success, is(true));
    }

}

From source file:org.kantega.dogmaticmvc.java.JavaScriptCompiler.java

@Override
public Class compile(HttpServletRequest request) {

    String className = request.getServletPath().substring(1).replace('/', '.');

    List<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();
    for (String path : (Set<String>) servletContext.getResourcePaths("/WEB-INF/dogmatic/")) {
        if (path.endsWith("java")) {
            try {
                String classNAme = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                compilationUnits.add(new JavaSourceFromURL(classNAme, servletContext.getResource(path)));
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }//from  ww w.  j  a va2 s  . c  om
        }
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(
            compiler.getStandardFileManager(null, null, null),
            new ClassLoaderImpl(getClass().getClassLoader()));

    String cp = "";
    for (ClassLoader cl : Arrays.asList(getClass().getClassLoader(), getClass().getClassLoader().getParent())) {
        if (cl instanceof URLClassLoader) {
            URLClassLoader ucl = (URLClassLoader) cl;

            for (URL url : ucl.getURLs()) {
                if (cp.length() > 0) {
                    cp += File.pathSeparator;
                }
                cp += url.getFile();
            }
        }
    }
    List<String> options = new ArrayList(Arrays.asList("-classpath", cp));

    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
            compilationUnits);

    boolean success = task.call();
    StringWriter sw = new StringWriter();
    PrintWriter w = new PrintWriter(sw);

    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        w.println(diagnostic.getCode());
        w.println(diagnostic.getKind());
        w.println(diagnostic.getPosition());
        w.println(diagnostic.getStartPosition());
        w.println(diagnostic.getEndPosition());
        w.println(diagnostic.getSource());
        w.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            return fileManager.getClassLoader(null).loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("Compilation failed: " + sw);
    }
}

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

public void compile(String fileName) {
    ClassLoader cl = this.getClass().getClassLoader();
    List<URL> classpath = new ArrayList<URL>();
    if (cl instanceof URLClassLoader) {
        URLClassLoader cl2 = (URLClassLoader) cl;
        for (URL jar : cl2.getURLs()) {
            classpath.add(jar);/*  w ww  .j a  v a 2s. co  m*/
        }
    }
    String classPath = System.getProperty("java.class.path");
    for (String path : classPath.split(File.pathSeparator)) {
        try {
            classpath.add(new URL("file:" + path));
        } catch (MalformedURLException e) {
            System.err.println("Wrong url: " + e.getMessage());
            e.printStackTrace();
        }
    }

    StringBuffer sb = new StringBuffer();
    for (URL jar : classpath) {
        if (SystemUtils.IS_OS_WINDOWS == false) {
            sb.append(jar.getPath());
            sb.append(File.pathSeparatorChar);
        } else {
            sb.append(jar.getPath().substring(1));
            sb.append(File.pathSeparatorChar);
        }
    }
    String ops[] = new String[] { "-classpath", sb.toString() };

    List<String> opsIter = new ArrayList<String>();
    try {
        for (String s : ops) {
            // XXX test usage, removed use of deprecated method
            // ((ArrayList) opsIter).add(URLDecoder.decode(s));
            ((ArrayList) opsIter).add(URLDecoder.decode(s, Charset.forName("UTF-8").toString()));
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    File[] files1 = new File[1];
    files1[0] = new File(fileName);

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

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files1));

    compiler.getTask(null, fileManager, null, opsIter, null, compilationUnits1).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

public static JavaCompiler getJavaCompilerTool() {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    if (tool != null)
        return tool;

    // No system Java compiler found, try to locate Javac ourself
    // (maybe we found a "bundled" Javac class on our classpath).
    try {//from   w w  w  .j a va  2 s.  c o m
        Class<?> clazz = Class.forName(JAVAC_CLASSNAME);
        try {
            return (JavaCompiler) clazz.newInstance();
        } catch (Exception ex) {
            LOG.error(ex);
        }
    } catch (ClassNotFoundException e) {
        LOG.warn("getJavaCompilerTool failed: " + e);
    }
    return null;
}

From source file:org.openmrs.logic.CompilingClassLoader.java

private String compile(String javaFile) throws IOException {
    String errorMessage = null;/*ww  w.j a va2 s. co  m*/
    String ruleClassDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER);
    String ruleJavaDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    log.info("JavaCompiler is null: " + compiler == null);
    if (compiler != null) {
        // java compiler only available on JDK. This part of "IF" will not get executed when we run JUnit test
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] options = {};
        DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector,
                Context.getLocale(), Charset.defaultCharset());
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFolder));
        // create compiling classpath
        String stringProperties = System.getProperty("java.class.path");
        if (log.isDebugEnabled())
            log.debug("Compiler classpath: " + stringProperties);
        String[] properties = StringUtils.split(stringProperties, File.pathSeparator);
        List<File> classpathFiles = new ArrayList<File>();
        for (String property : properties) {
            File f = new File(property);
            if (f.exists())
                classpathFiles.add(f);
        }
        classpathFiles.addAll(getCompilerClasspath());
        fileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);
        // create the compilation task
        CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnosticCollector,
                Arrays.asList(options), null, fileManager.getJavaFileObjects(javaFile));
        boolean success = compilationTask.call();
        fileManager.close();
        if (success) {
            return null;
        } else {
            errorMessage = "";
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                errorMessage += diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Context.getLocale())
                        + "\n";
            }
            return errorMessage;
        }
    } else {
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] commands = { "javac", "-classpath", System.getProperty("java.class.path"), "-d",
                outputFolder.getAbsolutePath(), javaFile };
        // Start up the compiler
        File workingDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir);
        boolean success = LogicUtil.executeCommand(commands, workingDirectory);
        return success ? null : "Compilation error. (You must be using the JDK to see details.)";
    }
}

From source file:org.sonatype.maven.polyglot.java.JavaModelReader.java

@SuppressWarnings("unchecked")
private Model compileJavaCode(String src) {

    Model model = null;/*from   www  .  j a va 2 s  . com*/

    File tempDir = Files.createTempDir();
    String randomClassName = "POM" + UUID.randomUUID().toString().replaceAll("-", "");
    String filePath = tempDir.getAbsolutePath();
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }
    filePath = filePath + randomClassName + ".java";

    try {
        Files.write(replaceClassNameInSrc(src, randomClassName), new File(filePath), Charset.defaultCharset());
        log.debug("Created temp file " + filePath + " to compile POM.java");
    } catch (IOException e) {
        e.printStackTrace();
        log.debug("Error writing file " + filePath, e);
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, "-parameters", "-classpath", getClassPath(), filePath);
    log.debug("Dynamically compiled class " + filePath);

    try {
        URL comiledClassFolderURL = new URL("file:" + tempDir.getAbsolutePath() + "/");

        ClassRealm systemClassLoader = (ClassRealm) getClass().getClassLoader();
        systemClassLoader.addURL(comiledClassFolderURL);

        log.debug("Added URL " + comiledClassFolderURL + " to Maven class loader to load class dynamically");

        Class<ModelFactory> pomClass = (Class<ModelFactory>) Class.forName(randomClassName, false,
                systemClassLoader);

        model = pomClass.newInstance().getModel();

    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | MalformedURLException e) {
        log.error("Failed to dynamically load class " + randomClassName, e);
    } finally {
        try {
            FileUtils.deleteDirectory(tempDir);
        } catch (IOException e) {
            log.error("Failed to delete temp folder " + tempDir, e);
        }
    }

    return model;
}

From source file:org.spiffyui.maven.plugins.JavaCompileMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    ArgBuilder args = new ArgBuilder();

    String classpath = flatten(classpathElements.toString(), File.pathSeparator);

    if (debug) {/* w w  w  . j  av  a  2s.  co  m*/
        args.add("-g");
    }

    if (verbose) {
        args.add("-verbose");
    }

    if (deprecation) {
        args.add("-deprecation");
    }

    if (nowarn) {
        args.add("-nowarn");
    }

    if (!xlint.equals("none")) {
        if (xlint.equals("all")) {
            args.add("-Xlint");
        } else {
            args.add("-Xlint:" + xlint);
        }
    }

    args.add("-d").add(outputDirectory.getAbsolutePath()).add("-s")
            .add(generatedSourcesDirectory.getAbsolutePath()).add("-encoding").add(encoding).add("-cp")
            .add(classpath).add("-source").add(source).add("-target").add(target);

    String[] exts = { "java" };

    for (String extraArg : extraArgs) {
        args.add(extraArg);
    }

    List<String> sources = compileSourceRoots;
    sources.add(generatedSourcePath);

    for (String s : sources) {
        File path = new File(s);

        if (!path.exists()) {
            continue;
        }

        List<File> files = new ArrayList<File>(FileUtils.listFiles(path, exts, true));
        for (File file : files) {
            args.add(file.getAbsolutePath());
        }
    }

    ensureExists(outputDirectory);
    ensureExists(generatedSourcesDirectory);

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();

    if (javac == null) {
        throw new MojoExecutionException("The Java compiler could not be found.  "
                + "Make sure to point your Maven build to a full Java development environment.");
    }

    getLog().debug("Exec: javac " + args.toString());
    if (javac.run(null, null, null, args.get()) != 0) {
        throw new MojoExecutionException("Compilation failed");
    }
}

From source file:org.wso2.carbon.config.annotationprocessor.AnnotationProcessorTest.java

@BeforeClass
public void initClass() {
    //get the java compiler.
    compiler = ToolProvider.getSystemJavaCompiler();
    //configure the diagnostics collector.
    collector = new DiagnosticCollector<>();
    fileManager = compiler.getStandardFileManager(collector, Locale.US, Charset.forName("UTF-8"));
    packagePath = Paths.get("src", "test", "java", "org", "wso2", "carbon", "config", "annotationprocessor")
            .toString();//from www.j  a v  a  2  s  .c om
    classesToCompile = new String[] { Paths.get(packagePath, "Configurations.java").toString() };
}

From source file:org.wso2.carbon.config.test.annotationprocessor.AnnotationProcessorTest.java

@BeforeClass
public void initClass() {
    //get the java compiler.
    compiler = ToolProvider.getSystemJavaCompiler();
    //configure the diagnostics collector.
    collector = new DiagnosticCollector<>();
    fileManager = compiler.getStandardFileManager(collector, Locale.US, Charset.forName("UTF-8"));
    packagePath = Paths/* w w w  . j a va2  s . c  o  m*/
            .get("src", "test", "java", "org", "wso2", "carbon", "config", "test", "annotationprocessor")
            .toString();
    classesToCompile = new String[] { Paths.get(packagePath, "TestConfiguration.java").toString() };
}