javax.tools.StandardJavaFileManager#setLocation ( )源码实例Demo

下面列出了javax.tools.StandardJavaFileManager#setLocation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jdart   文件: TemplateBasedCompiler.java
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;
}
 
源代码2 项目: openjdk-8   文件: GetTask_OptionsTest.java
/**
 * 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");
    }
}
 
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;
    }
}
 
源代码4 项目: openjdk-8   文件: JavadocTaskImplTest.java
@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);
    }
}
 
源代码5 项目: jdk8u60   文件: JavadocTaskImplTest.java
@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");
    }
}
 
源代码6 项目: openjdk-jdk8u   文件: GetTask_OptionsTest.java
/**
 * 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);
    }
}
 
源代码7 项目: dubbox   文件: JdkCompiler.java
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);
}
 
源代码8 项目: openjdk-jdk8u   文件: GetTask_FileObjectsTest.java
/**
 * 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);
    }
}
 
/**
 * 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);
    }
}
 
源代码10 项目: openjdk-jdk8u-backup   文件: GetTask_WriterTest.java
/**
 * 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");
    }
}
 
源代码11 项目: domino-jackson   文件: PolymorphicTest.java
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();
}
 
源代码12 项目: openjdk-8-source   文件: DocletPathTest.java
/**
 * 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");
    }
}
 
源代码13 项目: hottub   文件: GenStubs.java
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);
}
 
源代码14 项目: openjdk-jdk8u   文件: GenStubs.java
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);
}
 
源代码15 项目: TencentKona-8   文件: TestModularizedEvent.java
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();
}
 
源代码16 项目: TencentKona-8   文件: GetTask_DiagListenerTest.java
/**
 * 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");
    }
}
 
源代码17 项目: syncer   文件: JavaMethod.java
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());
  }
}
 
源代码18 项目: jprotobuf   文件: JdkCompiler.java
/**
 * 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);
}
 
源代码19 项目: packagedrone   文件: Jsr199JavaCompiler.java
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]);
}
 
源代码20 项目: bazel   文件: VanillaJavaBuilder.java
private static void setOutputLocation(
    StandardJavaFileManager fileManager, StandardLocation location, Path path)
    throws IOException {
  createOutputDirectory(path);
  fileManager.setLocation(location, ImmutableList.of(path.toFile()));
}