Example usage for javax.tools JavaCompiler getStandardFileManager

List of usage examples for javax.tools JavaCompiler getStandardFileManager

Introduction

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

Prototype

StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Locale locale, Charset charset);

Source Link

Document

Returns a new instance of the standard file manager implementation for this tool.

Usage

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   www  .j  av a2 s  .  c  o  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
    }/*  w  w w . j ava  2  s  . co  m*/

    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

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

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);// w  ww  .  jav a 2 s  .  c  o m

    //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.javascool.compiler.Compiler.java

/**
 * Lance la compilation des fichiers vers un autre rpertoire. Va compiler les fichier dans un autre rpertoire.
 *
 * @param binDirectory Rpertoire cible pour la compilation. Il doit dj exister et tre un dossier
 * @return Les erreurs de la compilation
 *///w  w  w. j a  v a2 s .  c  o m
public ArrayList<Diagnostic<? extends JavaFileObject>> compile(File binDirectory) {
    assertDirectoryExists(binDirectory);
    final ArrayList<Diagnostic<? extends JavaFileObject>> errors = new ArrayList<Diagnostic<? extends JavaFileObject>>();

    ArrayList<String> sourceFiles = new ArrayList<String>(filesToCompile.length);
    for (File srcFile : filesToCompile)
        sourceFiles.add(srcDirectory.toURI().relativize(srcFile.toURI()).getPath());
    classLoader = new JVSClassLoader(binDirectory);

    JavaCompiler eclipseCompiler;
    ArrayList<String> options;
    eclipseCompiler = new EclipseCompiler();
    options = getCompilerOptions();

    DiagnosticListener<? super JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            errors.add(diagnostic);
        }
    };

    StandardJavaFileManager fileManager = eclipseCompiler.getStandardFileManager(diagnosticListener, null,
            Charset.forName("UTF-8"));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjects(sourceFiles.toArray(new String[sourceFiles.size()]));

    eclipseCompiler.getTask(null, fileManager, diagnosticListener, options, null, compilationUnits).call();

    return errors;
}

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  w  w  w  . ja  v  a 2s .c  om
    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);
            }/* ww w . j a  v a 2  s.  co  m*/
        }
    }
    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 w  w  . j av a  2 s . c  o  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.openmrs.logic.CompilingClassLoader.java

private String compile(String javaFile) throws IOException {
    String errorMessage = null;/*from  w ww  .j a v a2 s  . c  om*/
    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:plaid.compilerjava.CompilerCore.java

private void generateCode(List<CompilationUnit> cus, final PackageRep plaidpath) throws Exception {
    if (cc.isVerbose()) {
        System.out.println("Generating code.");
    }/*from   w  w w. j  a va 2s.  c o m*/

    final List<File> allFiles = new ArrayList<File>();
    ExecutorService taskPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (final CompilationUnit cu : cus) {
        if (!cc.forceRecompile()) {
            boolean rebuild = false;
            for (Decl d : cu.getDecls()) {
                //System.out.println(d);
                StringBuilder packageName = new StringBuilder();
                for (String s : cu.getPackageName()) {
                    packageName.append(s);
                    packageName.append(System.getProperty("file.separator"));
                }
                File targetFile = new File(cc.getTempDir() + System.getProperty("file.separator") + packageName
                        + d.getName() + ".java");
                if (!targetFile.exists() || targetFile.lastModified() < cu.getSourceFile().lastModified()) {
                    rebuild = true;
                    break;
                }
            }
            if (!rebuild) {
                if (cc.isVerbose()) {
                    System.out.println("file up-to-date : " + cu.getSourceFile());
                }
                continue;
            }
            if (cc.isVerbose()) {
                System.out.println("Rebuild: " + cu.getSourceFile());
            }
        }
        Callable<Object> task = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    if (cc.isVerbose())
                        System.out.println("Generating code for:\n" + cu);
                    List<File> fileList = cu.codegen(cc, plaidpath);

                    synchronized (allFiles) {
                        allFiles.addAll(fileList);
                    }
                } catch (PlaidException p) {
                    System.err.println("Error while compiling " + cu.getSourceFile().toString() + ":");
                    System.err.println("");
                    printExceptionInformation(p);
                }
                return null;
            }
        };
        taskPool.submit(task);
    }
    taskPool.shutdown();
    while (!taskPool.isTerminated()) {
        taskPool.awaitTermination(1, TimeUnit.MINUTES);
    }

    if (!cc.isKeepTemporaryFiles()) {
        for (File f : allFiles) {
            f.deleteOnExit();
        }
    }

    if (cc.isVerbose()) {
        System.out.println("invoke Java compiler");
    }
    if (cc.isInvokeCompiler() && allFiles.size() > 0) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(allFiles);

        List<String> optionList = new ArrayList<String>();
        optionList.addAll(Arrays.asList("-target", "1.5"));
        // Set compiler's classpath to be same as the runtime's
        optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
        // TODO: Add a separate compiler flag for this.
        optionList.addAll(Arrays.asList("-d", cc.getOutputDir()));
        //         optionList.add("-verbose");

        // Invoke the compiler
        CompilationTask task = compiler.getTask(null, null, null, optionList, null, fileObjects);
        Boolean resultCode = task.call();
        if (!resultCode.booleanValue())
            throw new RuntimeException("Error while compiling generated Java files.");
    }
}

From source file:rita.compiler.CompileString.java

/**
 * El mtodo compile crea el archivo compilado a partir de un codigo fuente
 * y lo deja en un directorio determinado
 * /*from   w w  w  .  j a v  a2  s.  com*/
 * @param sourceCode
 *            el codigo fuente
 * @param className
 *            el nombre que debera llevar la clase
 * @param packageName
 *            nombre del paquete
 * @param outputDirectory
 *            directorio donde dejar el archivo compilado
 * */
public static final Collection<File> compile(File sourceCode, File outputDirectory) throws Exception {
    diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>();
    JavaCompiler compiler = new EclipseCompiler();

    System.out.println(sourceCode);

    DiagnosticListener<JavaFileObject> listener = new DiagnosticListener<JavaFileObject>() {
        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            if (diagnostic.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) {
                System.err.println("=======================ERROR==========================");
                System.err.println("Tipo: " + diagnostic.getKind());
                System.err.println("mensaje: " + diagnostic.getMessage(Locale.ENGLISH));
                System.err.println("linea: " + diagnostic.getLineNumber());
                System.err.println("columna: " + diagnostic.getColumnNumber());
                System.err.println("CODE: " + diagnostic.getCode());
                System.err.println(
                        "posicion: de " + diagnostic.getStartPosition() + " a " + diagnostic.getEndPosition());
                System.err.println(diagnostic.getSource());
                diagnostics.add(diagnostic);
            }
        }

    };

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    /* guardar los .class y  directorios (packages) en un directorio separado; de esta manera
     * si se genera mas de 1 clase (porque p.ej. hay inner classes en el codigo) podemos identificar
     * a todas las clases resultantes de esta compilacion
     */
    File tempOutput = createTempDirectory();
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempOutput));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceCode);
    try {
        if (compiler.getTask(null, fileManager, listener, null, null, compilationUnits).call()) {
            // copiar .class y  directorios (packages) generados por el compilador en tempOutput al directorio final
            FileUtils.copyDirectory(tempOutput, outputDirectory);
            // a partir de los paths de los archivos .class generados en el dir temp, modificarlos para que sean relativos a outputDirectory
            Collection<File> compilationResults = new ArrayList<File>();
            final int tempPrefix = tempOutput.getAbsolutePath().length();
            for (File classFile : FileUtils.listFiles(tempOutput, new SuffixFileFilter(".class"),
                    TrueFileFilter.INSTANCE)) {
                compilationResults
                        .add(new File(outputDirectory, classFile.getAbsolutePath().substring(tempPrefix)));
            }
            // retornar los paths de todos los .class generados
            return compilationResults;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error al realizar el compilado");
    } finally {
        FileUtils.deleteDirectory(tempOutput);
        fileManager.close();
    }
    return null;
}