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: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  . jav a2  s.  co  m*/
    task.call();
}

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

/**
 * ??/* w ww  .ja  va 2s.  c o m*/
 * @param sourcePath 
 * @param outputPath ?
 * @param encoding 
 * @param operatorClasses ?
 * @throws IOException ???????
 * @throws IllegalArgumentException ?{@code null}????
 */
public static void compile(File sourcePath, File outputPath, Charset encoding, List<Class<?>> operatorClasses)
        throws IOException {
    if (sourcePath == null) {
        throw new IllegalArgumentException("sourcePath must not be null"); //$NON-NLS-1$
    }
    if (outputPath == null) {
        throw new IllegalArgumentException("outputPath must not be null"); //$NON-NLS-1$
    }
    if (encoding == null) {
        throw new IllegalArgumentException("encoding must not be null"); //$NON-NLS-1$
    }
    if (operatorClasses == null) {
        throw new IllegalArgumentException("operatorClasses must not be null"); //$NON-NLS-1$
    }

    // ??JSR-199?????
    List<File> sourceFiles = toSources(sourcePath, operatorClasses);
    LOG.info(MessageFormat.format("Compiling {0}", sourceFiles));
    List<String> arguments = toArguments(sourcePath, outputPath, encoding);
    LOG.debug("Compiler arguments {}", arguments); //$NON-NLS-1$
    if (outputPath.isDirectory() == false && outputPath.mkdirs() == false) {
        throw new IOException(MessageFormat.format("Failed to create {0}", outputPath));
    }
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new IOException("Failed to create a compiler");
    }
    StandardJavaFileManager files = compiler.getStandardFileManager(null, null, encoding);
    try {
        CompilationTask task = compiler.getTask(null, files, null, arguments, Collections.<String>emptyList(),
                files.getJavaFileObjectsFromFiles(sourceFiles));
        if (task.call() == false) {
            LOG.error("Compilation Failed");
        }
    } finally {
        files.close();
    }
    LOG.info("Completed");
}

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

public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder,
        GeneratorContext context) {/*  w  w w.j a  v  a  2 s .  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:neembuu.uploader.zip.generator.NUCompiler.java

/**
 * Compile all the given files in the given build directory.
 *
 * @param files The array of files to compiles.
 * @param buildDirectory The build directory in which put all the compiled
 * files.//from   w w w.j  ava  2  s  . co m
 * @throws FileNotFoundException
 * @throws IOException
 */
private void compileFiles(File[] files, File buildDirectory) throws FileNotFoundException, IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    buildDirectory.mkdir();

    /**/
    List<String> optionList = new ArrayList<String>();
    // set compiler's classpath to be same as the runtime's
    //optionList.addAll(Arrays.asList("-classpath", "C:\\neembuuuploader\\modules\\libs\\jsoup-1.7.2.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-codec-1.6.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-logging-1.1.1.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-cache-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpcore-4.2.4.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpmime-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\json-java.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-utils\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-api\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-interfaces-abstractimpl\\build\\classes;C:\\neembuuuploader\\modules\\libs\\neembuu-now-api-ui.jar;C:\\neembuuuploader\\modules\\libs\\neembuu-release1-ui-mc.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-uploaders\\build\\classes;C:\\neembuuuploader\\modules\\NeembuuUploader\\build\\classes"));
    optionList.addAll(Arrays.asList("-classpath", classPath));
    optionList.addAll(Arrays.asList("-d", buildDirectory.getAbsolutePath()));

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files));

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

    JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, optionList, null,
            compilationUnits);
    boolean result = task.call();

    if (result) {
        System.out.println("Compilation was successful");
    } else {
        System.out.println("Compilation failed");

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
        }
    }
}

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  av a2s.c  o 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);
        }

    }
}

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

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

    try {//  w  w w  .  j  a  v a  2  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:bear.main.JavaCompiler2.java

public List<File> compileScripts(File sourcesDir) {
    FileFilter filter = new SuffixFileFilter(extensions);

    final File[] files = sourcesDir.listFiles(filter);

    final ArrayList<String> params = newArrayListWithExpectedSize(files.length);

    if (!buildDir.exists()) {
        buildDir.mkdir();/*  w ww .  j  av a 2  s .  c  om*/
    }

    Collections.addAll(params, "-d", buildDir.getAbsolutePath());
    List<File> javaFilesList = newArrayList(files);

    List<File> filesListToCompile = ImmutableList.copyOf(Iterables.filter(javaFilesList, new Predicate<File>() {
        @Override
        public boolean apply(File javaFile) {
            File classFile = new File(buildDir, FilenameUtils.getBaseName(javaFile.getName()) + ".class");

            boolean upToDate = classFile.exists() && classFile.lastModified() > javaFile.lastModified();

            if (upToDate) {
                logger.info("{} is up-to-date", javaFile);
            }

            return !upToDate;
        }
    }));

    if (filesListToCompile.isEmpty()) {
        logger.info("all files are up-to-date");
        return javaFilesList;
    }

    final List<String> filePaths = Lists.transform(filesListToCompile, new Function<File, String>() {
        public String apply(File input) {
            return input.getAbsolutePath();
        }
    });

    params.addAll(filePaths);

    logger.info("compiling {}", params);

    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    final int r = compiler.run(null, null, null, params.toArray(new String[params.size()]));

    if (r == 0) {
        logger.info("compilation OK.");
    } else {
        logger.info("compilation failed.");
    }

    return javaFilesList;
}

From source file:configuration.Config.java

public Config() {
    if (properties == null) {
        currentPath = new File("").getAbsolutePath();
        properties = new workflow_properties();
        if (!Load()) {
            setDefaultProperties();//w w w  . j av  a2  s.c  o  m
            Save();
        } else {
            //--Test path
            if (!Util.FileExists(this.databasePath())) {
                //--Case 1. test default path
                if (Util.FileExists(
                        currentPath + File.separator + "projects" + File.separator + "Untitled.db")) {
                    //Reset path to database                    
                    setDefaultProperties();
                    Save();
                }
            }
        }
        //--Set compiler properties
        try {
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            set("CompilerFound", (compiler == null ? false : true));
            // System.out.println("Testing Java compiler: "+isCompilerFound());
        } catch (Exception e) {
            Config.log("Unable to determine compiler: " + e.getMessage());
        }
        // -- Get armadillo icon
        if (image == null)
            loadIcon();
        if (log == null) {
            try {
                log = new PrintWriter(new FileWriter(new File(log_file), true));
            } catch (Exception e) {
                //Config.log("Unable to open log file: "+log_file);
                return;
            }
        }
    }
}

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  w  w. jav  a 2s  .  c o  m*/
        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:de.monticore.codegen.GeneratorTest.java

/**
 * Instantiates all the parameters required for a CompilationTask and returns
 * the finished task./*from  ww w .j  a v a2s  .  c om*/
 * 
 * @param sourceCodePath the source directory to be compiled
 * @param diagnostics a bin for any error messages that may be generated by
 * the compiler
 * @return the compilationtask that will compile any entries in the given
 * directory
 */
protected Optional<CompilationTask> setupCompilation(Path sourceCodePath,
        DiagnosticCollector<JavaFileObject> diagnostics) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler != null) {
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        // set compiler's classpath to be same as the runtime's
        String sPath = Paths.get("target/generated-sources/monticore/codetocompile").toAbsolutePath()
                .toString();
        List<String> optionList = Lists.newArrayList("-classpath",
                System.getProperty("java.class.path") + File.pathSeparator + sPath, "-sourcepath", sPath);
        // System.out.println("Options" + optionList);
        Iterable<? extends JavaFileObject> javaFileObjects = getJavaFileObjects(sourceCodePath, fileManager);
        // System.out.println("Java files" + javaFileObjects);
        return Optional.of(compiler.getTask(null, fileManager, diagnostics, optionList, null, javaFileObjects));
    }
    return Optional.empty();
}