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:gool.parser.java.JavaParser.java

/**
 * if the parser is called on a directory, wrap it into a compilation unit,
 * and call the parser on that file.//from   w  w  w.  j a v a2s.  com
 */
public Collection<ClassDef> parseGoolFiles(Platform defaultPlatform, List<File> dirs) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(dirs);
    return parseGool(defaultPlatform, compilationUnits);
}

From source file:com.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(Folder webAppRootFolder, Iterable<Folder> sources, Folder destination,
        Iterable<Resource> classpath) {
    try {/*from   w  w  w.j  a  v  a  2  s .  com*/
        if (webAppRootFolder != null) {
            copyRuntimeServiceFiles(webAppRootFolder, destination);
        }
        JavaCompiler compiler = new WaveMakerJavaCompiler();
        StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, getStandardClassPath());
        ResourceJavaFileManager projectFileManager = new ResourceJavaFileManager(standardFileManager);
        projectFileManager.setLocation(StandardLocation.SOURCE_PATH, sources);
        ArrayList<Folder> destinations = new ArrayList<Folder>();
        destinations.add(destination);
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT, destinations);
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
        Iterable<JavaFileObject> compilationUnits = projectFileManager.list(StandardLocation.SOURCE_PATH, "",
                Collections.singleton(Kind.SOURCE), true);
        StringWriter compilerOutput = new StringWriter();
        CompilationTask compilationTask = compiler.getTask(compilerOutput, projectFileManager, null,
                getCompilerOptions(), null, compilationUnits);
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Compile error: " + e);
    }
}

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 a 2 s .  co  m
 * 
 * @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();
}

From source file:com.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(final Project project) {
    try {/*from  w  w w  .  ja va 2s .  c o  m*/
        copyRuntimeServiceFiles(project.getWebAppRootFolder(), project.getClassOutputFolder());
        JavaCompiler compiler = new WaveMakerJavaCompiler();
        StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, getStandardClassPath());
        ResourceJavaFileManager projectFileManager = new ResourceJavaFileManager(standardFileManager);
        projectFileManager.setLocation(StandardLocation.SOURCE_PATH, project.getSourceFolders());
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                Collections.singleton(project.getClassOutputFolder()));
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, getClasspath(project));
        copyResources(project);
        Iterable<JavaFileObject> compilationUnits = projectFileManager.list(StandardLocation.SOURCE_PATH, "",
                Collections.singleton(Kind.SOURCE), true);
        StringWriter compilerOutput = new StringWriter();
        CompilationTask compilationTask = compiler.getTask(compilerOutput, projectFileManager, null,
                getCompilerOptions(project), null, compilationUnits);
        ServiceDefProcessor serviceDefProcessor = configure(new ServiceDefProcessor(), projectFileManager);
        ServiceConfigurationProcessor serviceConfigurationProcessor = configure(
                new ServiceConfigurationProcessor(), projectFileManager);
        compilationTask.setProcessors(Arrays.asList(serviceConfigurationProcessor, serviceDefProcessor));
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Unable to compile " + project.getProjectName(), e);
    }
}

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

@Override
public void visit(@NotNull VerbatimNode node) {
    if ("java".equals(node.getType())) {
        try {/*from   w w w  .  j av a 2  s .c  om*/
            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: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);/* ww w . j a  va2  s  . c om*/
    }
    System.out.print("Starting compilation....");
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    System.out.println("finished");
}

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:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Compiles the unit startup file from Java source to Java bytecode.
 *
 * This compiles the startup file. During this process, multiple class files
 * may be generated even though only a single input file to compile is
 * specified. The reason for this is that classes other than the main class
 * may be defined in the single file and are written to distinct class
 * files. All created files are collected and returned by the method.
 *
 * @param startupFile The file to be compiled.
 * @param startupDependencies Names of classpath entries to use for compilation.
 * @return List of names of created (class) files during compilation.
 * @exception UnitGenerationException Thrown when finding a Java compiler failed.
 *///from  w  w w. jav a2 s. com
private LinkedList<String> compile(final File startupFile, final Collection<String> startupDependencies)
        throws MissingToolException, InvalidConfigurationException {
    // code inspired by the examples at
    //   http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
    final LinkedList<String> createdFiles = new LinkedList<String>();

    // set the file manager, which records the written files
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new MissingToolException("Could not find system Java compiler.");
    }
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
    JavaFileManager fileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(stdFileManager) {
        /**
         * Collect the list of all output (class) files.
         *
         * Besides its side-effect on the createdFiles list of the containing
         * method, this method is functionally equivalent to its superclass
         * version.
         */
        public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className,
                JavaFileObject.Kind kind, FileObject sibling) throws IOException {
            JavaFileObject fileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
            createdFiles.addLast(fileForOutput.getName());
            return fileForOutput;
        }
    };

    // set the files to compile
    Iterable<? extends JavaFileObject> compilationUnits = stdFileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(startupFile));

    // do the actual compilation
    ArrayList<String> compileParams = new ArrayList<String>(2);

    boolean verbose = org.apache.log4j.Level.DEBUG.isGreaterOrEqual(config.getInstantiationLogLevel());
    if (verbose)
        compileParams.add("-verbose");

    compileParams
            .addAll(Arrays.asList("-classpath", StringUtils.join(startupDependencies, File.pathSeparator)));
    if (!compiler.getTask(null, fileManager, null, compileParams, null, compilationUnits).call()) {
        // could not compile all files without error
        //TODO: throw an exception ... see where to get the required information from
    }
    return createdFiles;
}

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);
    }/*  www.  j a  va 2s.  com*/

    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:me.dwtj.java.compiler.utils.CompilationTaskBuilder.java

private CompilationTask buildTask() throws IOException {
    // Configure the compiler itself and its file manager.
    JavaCompiler compiler = getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostic, null, null);
    fileManagerConfig.config(fileManager);

    // Use the file manager and the class list to get the compilation units to be compiled.
    for (String c : classes) {
        JavaFileObject srcFile = fileManager.getJavaFileForInput(SOURCE_PATH, c, SOURCE);
        if (srcFile == null) {
            throw new IOException("No such class found on the source path: " + c);
        } else {//from   w  ww . ja v  a 2  s. c  o m
            compilationUnits.add(srcFile);
        }
    }

    // Configure the compilation task itself.
    if (compilationUnits.isEmpty()) {
        String msg = "CompilationTaskBuilder: No compilation units have been added.";
        throw new IllegalStateException(msg);
    }
    CompilationTask task = compiler.getTask(null, // TODO: Support user-defined writer.
            fileManager, diagnostic, options, // TODO: Support more user-defined options.
            null, // TODO: Support user-defined classes.
            compilationUnits);
    task.setProcessors(processors);

    return task;
}