Example usage for javax.tools StandardJavaFileManager getJavaFileObjectsFromFiles

List of usage examples for javax.tools StandardJavaFileManager getJavaFileObjectsFromFiles

Introduction

In this page you can find the example usage for javax.tools StandardJavaFileManager getJavaFileObjectsFromFiles.

Prototype

Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files);

Source Link

Document

Returns file objects representing the given files.

Usage

From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java

private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = getCompiler().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...//from  w  w w  .  ja va2s  .  c  o m
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(getAllJarsClassPathInMavenLocalRepo());
    optionList.add("-verbose");

    File helloWorldJava = new File(classFilePathName);

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);

    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        // 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!
        //TODO the / separator needs to be revised to platform awared 
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
        String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/";
        ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent());
        classLoader.loadClass(className);
        classLoader.close();
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(),
                    diagnostic.getSource(), diagnostic.getMessage(new Locale("en")));
        }
    }
}

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.
 *//*  ww  w .  j av a  2  s . co  m*/
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:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap)
        throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFiles = new ArrayList<>();
    for (JarContents jarContents : sourceFileToJarMap.values()) {
        sourceFiles.addAll(jarContents.sourceFiles);
    }//from  w  w w  . j a  va  2 s  .co m

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString())));

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles);

    boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    if (!compiled) {
        throw new RuntimeException("failed to compile");
    }

    for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");

        JarOutputStream target = new JarOutputStream(
                new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()),
                manifest);
        List<String> classesForJar = new ArrayList<>();
        for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) {
            //split the file on dot to get the filename from FILENAME.java
            String fileName = sourceFile.getName().split("\\.")[0];
            classesForJar.add(fileName);
        }

        File dir = new File(outputDir);
        File[] directoryListing = dir.listFiles();
        for (File compiledClass : directoryListing) {
            String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0];
            if (classesForJar.contains(classFileName)) {
                addFileToJar(compiledClass, target);
            }
        }

        for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) {
            addFileToJar(propertiesFile, target);
        }

        target.close();

    }
    //delete non jar files
    File dir = new File(outputDir);
    File[] directoryListing = dir.listFiles();
    for (File file : directoryListing) {
        String extension = file.getName().split("\\.")[1];
        if (!extension.equals("jar")) {
            file.delete();
        }
    }

    Map<String, String> jarMap = new HashMap<>();
    jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME);
    jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME);
    return jarMap;
}

From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java

private static Class<?> compileClassJavac(String name, String src) {
    try {/*from   w w w.ja v  a2  s  .  c om*/
        //create working dir on demand
        if (_workingDir == null)
            createWorkingDir();

        //write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);

        //get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");

        //prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

        //prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(ftmp));

        //prepare class path 
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);

        //compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();

        //output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics())
            if (tmp.getKind() == Kind.ERROR)
                System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);

        //dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir },
                    CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        LOG.error("Failed to compile class " + name + ": \n" + src);
        throw new DMLRuntimeException("Failed to compile class " + name + ".", ex);
    }
}

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

/**
 * F2 test.//from   w ww .  ja v  a2s  .  c om
 * 
 * @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   w w w . ja  v a2s  .c o m*/

    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();/*from   w w  w  .  java  2 s . c om*/
    worker.join();

    assertEquals(urlcl, testObj.getReturnedCl());

    urlcl.close();
}

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  a v a  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

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

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);/*w  w w . ja  v a  2s  .co  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.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);/*  ww  w.  j a  va 2 s .com*/
    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));
    }

}