Java Code Examples for javax.tools.StandardJavaFileManager#setLocation()

The following examples show how to use javax.tools.StandardJavaFileManager#setLocation() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdart   File: TemplateBasedCompiler.java    License: Apache License 2.0 6 votes vote down vote up
public File compile(Config config) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
  fileManager.setLocation(StandardLocation.SOURCE_PATH, Collections.singleton(tmpSrcDir));
  
  File tmpClassDir = File.createTempFile("jpf-testing", "classes");
  tmpClassDir.delete();
  tmpClassDir.mkdir();
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(tmpClassDir));
  
  File[] cp = config.getPathArray("classpath");
  fileManager.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(cp));
  
  CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(sourceFiles));
  if(!task.call())
    throw new RuntimeException("Compilation failed");
  
  return tmpClassDir;
}
 
Example 2
/**
 * Verify that expected output files are written for given options.
 */
@Test
public void testNoIndex() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    Iterable<String> options = Arrays.asList("-noindex");
    DocumentationTask t = tool.getTask(null, fm, null, null, options, files);
    if (t.call()) {
        System.err.println("task succeeded");
        Set<String> expectFiles = new TreeSet<String>(standardExpectFiles);
        expectFiles.remove("index-all.html");
        checkFiles(outDir, expectFiles);
    } else {
        error("task failed");
    }
}
 
Example 3
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
    if (classpaths.size() > 0)
        fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
    JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
    if (generate) {
        File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
        // @@@ Assert that this directory didn't exist, or start counter at max+1
        destDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
        ct.generate();
        return destDir;
    }
    else {
        ct.analyze();
        return nullDir;
    }
}
 
Example 4
@Test
public void testDirectAccess2() throws Exception {
    JavaFileObject srcFile = null; // error, provokes NPE
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    Context c = new Context();
    Messager.preRegister(c, "javadoc");
    StandardJavaFileManager fm = new JavacFileManager(c, true, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    try {
        DocumentationTask t = new JavadocTaskImpl(c, null, null, files);;
        error("getTask succeeded, no exception thrown");
    } catch (NullPointerException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
Example 5
@Test
public void testRawCall() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);

    @SuppressWarnings("rawtypes")
    Callable t = tool.getTask(null, fm, null, null, null, files);

    if (t.call() == Boolean.TRUE) {
        System.err.println("task succeeded");
    } else {
        throw new Exception("task failed");
    }
}
 
Example 6
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<String> options = Arrays.asList((String) null);
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, options, files);
        error("getTask succeeded, no exception thrown");
    } catch (NullPointerException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
Example 7
Source Project: dubbox   File: JdkCompiler.java    License: Apache License 2.0 6 votes vote down vote up
public JdkCompiler(){
    options = new ArrayList<String>();
    options.add("-target");
    options.add("1.6");
    StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader instanceof URLClassLoader 
            && (! loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                files.add(new File(url.getFile()));
            }
            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });
    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
Example 8
/**
 * Verify bad file object is handled correctly.
 */
@Test
public void testBadFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.class");  // unacceptable file kind
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        error("getTask succeeded, no exception thrown");
    } catch (IllegalArgumentException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
Example 9
/**
 * Verify bad file object is handled correctly.
 */
@Test
public void testBadFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.class");  // unacceptable file kind
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        error("getTask succeeded, no exception thrown");
    } catch (IllegalArgumentException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
Example 10
/**
 * Verify that a writer can be provided.
 */
@Test
public void testWriter() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentationTask t = tool.getTask(pw, fm, null, null, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
        String out = sw.toString();
        System.err.println(">>" + out + "<<");
        for (String f: standardExpectFiles) {
            String f1 = f.replace('/', File.separatorChar);
            if (f1.endsWith(".html") && !out.contains(f1))
                throw new Exception("expected string not found: " + f1);
        }
    } else {
        throw new Exception("task failed");
    }
}
 
Example 11
Source Project: domino-jackson   File: PolymorphicTest.java    License: Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
	Path tempFolder = Files.createTempDirectory("gwt-jackson-apt-tmp", new FileAttribute[0]);
	fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempFolder.toFile()));
	fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Arrays.asList(tempFolder.toFile()));
	CompilationTask task = compiler.getTask(
			new PrintWriter(System.out), 
			fileManager, 
			null, 
			null, 
			null, 
			fileManager.getJavaFileObjects(
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicTest.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicBaseInterface.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicBaseClass.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicChildClass.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicChildClass2.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/SecondPolymorphicBaseClass.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/SecondPolymorphicChildClass.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/SimpleGenericBeanObject.java"),
					new File("src/test/java/org/dominokit/jacksonapt/processor/PolymorphicGenericClass.java")));


	task.setProcessors(Arrays.asList(new ObjectMapperProcessor()));
	task.call();
}
 
Example 12
/**
 * Verify that an alternate doclet can be specified, and located via
 * the file manager's DOCLET_PATH.
 */
@Test
public void testDocletPath() throws Exception {
    JavaFileObject docletSrc =
            createSimpleJavaFileObject("DocletOnDocletPath", docletSrcText);
    File docletDir = getOutDir("classes");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager cfm = compiler.getStandardFileManager(null, null, null);
    cfm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(docletDir));
    Iterable<? extends JavaFileObject> cfiles = Arrays.asList(docletSrc);
    if (!compiler.getTask(null, cfm, null, null, null, cfiles).call())
        throw new Exception("cannot compile doclet");

    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir("api");
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    fm.setLocation(DocumentationTool.Location.DOCLET_PATH, Arrays.asList(docletDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    Iterable<String> options = Arrays.asList("-doclet", "DocletOnDocletPath");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentationTask t = tool.getTask(pw, fm, null, null, options, files);
    boolean ok = t.call();
    String out = sw.toString();
    System.err.println(">>" + out + "<<");
    if (ok) {
        if (out.contains(TEST_STRING)) {
            System.err.println("doclet executed as expected");
        } else {
            error("test string not found in doclet output");
        }
    } else {
        error("task failed");
    }
}
 
Example 13
Source Project: hottub   File: GenStubs.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean run(String sourcepath, File outdir, List<String> classes) {
    //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes);
    if (sourcepath == null)
        throw new IllegalArgumentException("sourcepath not set");
    if (outdir == null)
        throw new IllegalArgumentException("source output dir not set");

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    try {
        fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir));
        fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath));
        List<JavaFileObject> files = new ArrayList<JavaFileObject>();
        for (String c: classes) {
            JavaFileObject fo = fm.getJavaFileForInput(
                    StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE);
            if (fo == null)
                error("class not found: " + c);
            else
                files.add(fo);
        }

        JavacTask t = tool.getTask(null, fm, null, null, null, files);
        Iterable<? extends CompilationUnitTree> trees = t.parse();
        for (CompilationUnitTree tree: trees) {
            makeStub(fm, tree);
        }
    } catch (IOException e) {
        error("IO error " + e, e);
    }

    return (errors == 0);
}
 
Example 14
public boolean run(String sourcepath, File outdir, List<String> classes) {
    //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes);
    if (sourcepath == null)
        throw new IllegalArgumentException("sourcepath not set");
    if (outdir == null)
        throw new IllegalArgumentException("source output dir not set");

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    try {
        fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir));
        fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath));
        List<JavaFileObject> files = new ArrayList<JavaFileObject>();
        for (String c: classes) {
            JavaFileObject fo = fm.getJavaFileForInput(
                    StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE);
            if (fo == null)
                error("class not found: " + c);
            else
                files.add(fo);
        }

        JavacTask t = tool.getTask(null, fm, null, null, null, files);
        Iterable<? extends CompilationUnitTree> trees = t.parse();
        for (CompilationUnitTree tree: trees) {
            makeStub(fm, tree);
        }
    } catch (IOException e) {
        error("IO error " + e, e);
    }

    return (errors == 0);
}
 
Example 15
private static boolean compile(Path source, Path destination, String... options)
        throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        // no compiler available
        throw new UnsupportedOperationException("Unable to get system java compiler. "
                + "Perhaps, jdk.compiler module is not available.");
    }
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
            = Files.find(source, Integer.MAX_VALUE,
                    (file, attrs) -> (file.toString().endsWith(".java")))
            .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocation(StandardLocation.CLASS_PATH, Collections.emptyList());
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
            Arrays.asList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
            = compiler.getTask(null, jfm, null, opts, null,
                    jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
 
Example 16
/**
 * Verify that a diagnostic listener can be specified.
 * Note that messages from the tool and doclet are imperfectly modeled
 * because the DocErrorReporter API works in terms of localized strings
 * and file:line positions. Therefore, messages reported via DocErrorReporter
 * and simply wrapped and passed through.
 */
@Test
public void testDiagListener() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", "package pkg; public error { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    DocumentationTask t = tool.getTask(null, fm, dc, null, null, files);
    if (t.call()) {
        throw new Exception("task succeeded unexpectedly");
    } else {
        List<String> diagCodes = new ArrayList<String>();
        for (Diagnostic d: dc.getDiagnostics()) {
            System.err.println(d);
            diagCodes.add(d.getCode());
        }
        List<String> expect = Arrays.asList(
                "javadoc.note.msg",         // Loading source file
                "compiler.err.expected3",   // class, interface, or enum expected
                "javadoc.note.msg");        // 1 error
        if (!diagCodes.equals(expect))
            throw new Exception("unexpected diagnostics occurred");
        System.err.println("diagnostics received as expected");
    }
}
 
Example 17
private static void compile(String path) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostic -> logger.error("{}, {}", diagnostic.getLineNumber(), diagnostic.getSource().toUri()), null, null);
  try {
    fm.setLocation(StandardLocation.CLASS_PATH, Lists.newArrayList(new File(System.getProperty("java.class.path"))));
  } catch (IOException e) {
    logger.error("Fail to set location for compiler file manager", e);
  }
  if (compiler.run(null, null, null, path) != 0) {
    ShutDownCenter.initShutDown(new InvalidConfigException());
  }
}
 
Example 18
Source Project: jprotobuf   File: JdkCompiler.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Instantiates a new jdk compiler.
 *
 * @param loader the loader
 * @param jdkVersion the jdk version
 */
public JdkCompiler(final ClassLoader loader, final String jdkVersion, List<File> classes) {
    options = new ArrayList<String>();
    options.add("-source");
    options.add(jdkVersion);
    options.add("-target");
    options.add(jdkVersion);

    // set compiler's classpath to be same as the runtime's
    if (compiler == null) {
        throw new RuntimeException(
                "compiler is null maybe you are on JRE enviroment please change to JDK enviroment.");
    }
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager manager =
            compiler.getStandardFileManager(diagnosticCollector, null, Charset.forName("utf-8"));
    if (loader instanceof URLClassLoader
            && (!loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {

        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {

                String file = url.getFile();
                files.add(new File(file));
                if (StringUtils.endsWith(file, "!/")) {
                    file = StringUtils.removeEnd(file, "!/");
                }
                if (file.startsWith("file:")) {
                    file = StringUtils.removeStart(file, "file:");
                }

                files.add(new File(file));

            }

            if (classes != null) {
                files.addAll(classes);
            }

            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });

    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
Example 19
public JavacErrorDetail[] compile(String className, Node.Nodes pageNodes)
        throws JasperException {

    final String source = charArrayWriter.toString();
    classFiles = new ArrayList<BytecodeFile>();

    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    if (javac == null) {
        errDispatcher.jspError("jsp.error.nojdk");
    }

    DiagnosticCollector<JavaFileObject> diagnostics =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager stdFileManager =
                javac.getStandardFileManager(diagnostics, null, null);

    String name = className.substring(className.lastIndexOf('.')+1);

    JavaFileObject[] sourceFiles = {
        new SimpleJavaFileObject(
                URI.create("string:///" + name.replace('.','/') +
                           Kind.SOURCE.extension),
                Kind.SOURCE) {
            public CharSequence getCharContent(boolean ignore) {
                return source;
            }
        }
    };

    try {
        stdFileManager.setLocation(StandardLocation.CLASS_PATH, this.cpath);
    } catch (IOException e) {
    }

    JavaFileManager javaFileManager = getJavaFileManager(stdFileManager);
    javax.tools.JavaCompiler.CompilationTask ct =
        javac.getTask(null,
                      javaFileManager,
                      diagnostics,
                      options,
                      null, 
                      Arrays.asList(sourceFiles));

    try {
        javaFileManager.close();
    } catch (IOException ex) {
    }

    if (ct.call()) {
        for (BytecodeFile bytecodeFile: classFiles) {
            rtctxt.setBytecode(bytecodeFile.getClassName(),
                               bytecodeFile.getBytecode());
        }
        return null;
    }

    // There are compilation errors!
    ArrayList<JavacErrorDetail> problems =
        new ArrayList<JavacErrorDetail>();
    for (Diagnostic dm: diagnostics.getDiagnostics()) {
        problems.add(ErrorDispatcher.createJavacError(
            javaFileName,
            pageNodes,
            new StringBuilder(dm.getMessage(null)),
            (int) dm.getLineNumber()));
    }
    return problems.toArray(new JavacErrorDetail[0]);
}
 
Example 20
Source Project: bazel   File: VanillaJavaBuilder.java    License: Apache License 2.0 4 votes vote down vote up
private static void setOutputLocation(
    StandardJavaFileManager fileManager, StandardLocation location, Path path)
    throws IOException {
  createOutputDirectory(path);
  fileManager.setLocation(location, ImmutableList.of(path.toFile()));
}