Java 类javax.tools.StandardJavaFileManager 实例源码

项目:openjdk-jdk10    文件: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();
    try (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);
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_FileObjectsTest.java   
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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((JavaFileObject) null);
        try {
            DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
            error("getTask succeeded, no exception thrown");
        } catch (NullPointerException e) {
            System.err.println("exception caught as expected: " + e);
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_DocletClassTest.java   
/**
 * Verify that an alternate doclet can be specified.
 *
 * There is no standard interface or superclass for a doclet;
 * the only requirement is that it provides static methods that
 * can be invoked via reflection. So, for now, the doclet is
 * specified as a class.
 * Because we cannot create and use a unique instance of the class,
 * we verify that the doclet has been called by having it record
 * (in a static field!) the comment from the last time it was invoked,
 * which is randomly generated each time the test is run.
 */
@Test
public void testDoclet() throws Exception {
    Random r = new Random();
    int key = r.nextInt();
    JavaFileObject srcFile = createSimpleJavaFileObject(
            "pkg/C",
            "package pkg; /** " + key + "*/ public class C { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        DocumentationTask t = tool.getTask(null, fm, null, TestDoclet.class, null, files);
        if (t.call()) {
            System.err.println("task succeeded");
            if (TestDoclet.lastCaller.equals(String.valueOf(key)))
                System.err.println("found expected key: " + key);
            else
                error("Expected key not found");
            checkFiles(outDir, Collections.<String>emptySet());
        } else {
            throw new Exception("task failed");
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_FileObjectsTest.java   
/**
 * Verify that expected output files are written via the file manager,
 * for a source file read from the file system with StandardJavaFileManager.
 */
@Test
public void testStandardFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.java");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        if (t.call()) {
            System.err.println("task succeeded");
            checkFiles(outDir, standardExpectFiles);
        } else {
            throw new Exception("task failed");
        }
    }
}
项目:incubator-netbeans    文件:MRJARCachingFileManagerTest.java   
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
项目:moduletools    文件:JavacModuleParser.java   
public static void parse(Path moduleInfoPath, ModuleClassVisitor moduleClassVisitor) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(moduleInfoPath);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    JavacTask javacTask = (JavacTask)task;
    Iterable<? extends CompilationUnitTree> units= javacTask.parse();
    CompilationUnitTree unit = units.iterator().next();

    ModuleHandler moduleHandler = new ModuleHandler(moduleClassVisitor);
    TreeVisitor<?,?> visitor = (TreeVisitor<?,?>)Proxy.newProxyInstance(TreeVisitor.class.getClassLoader(), new Class<?>[]{ TreeVisitor.class},
        (proxy, method, args) -> {
          ModuleHandler.METHOD_MAP
          .getOrDefault(method.getName(), (handler, node, v) -> { 
            throw new AssertionError("invalid node " + node.getClass());
          })
          .visit(moduleHandler, (Tree)args[0], (TreeVisitor<?,?>)proxy);
          return null;
        });

    unit.accept(visitor, null);
  }
}
项目:openjdk-jdk10    文件:TestDefaultMethodsSyntax.java   
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (VersionKind vk : VersionKind.values()) {
                for (EnclosingKind ek : EnclosingKind.values()) {
                    for (MethodKind mk : MethodKind.values()) {
                        for (ModifierKind modk1 : ModifierKind.values()) {
                            for (ModifierKind modk2 : ModifierKind.values()) {
                                new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm);
                            }
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
项目:openjdk-jdk10    文件:SetLocationForModule.java   
@Test
public void testSystemModules(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location locn = StandardLocation.SYSTEM_MODULES;

        Location javaCompiler = fm.getLocationForModule(locn, "java.compiler");
        // cannot easily verify default setting: could be jrt: or exploded image

        Path override1 = Files.createDirectories(base.resolve("override1"));
        fm.setLocationForModule(locn, "java.compiler", List.of(override1));
        checkEqual("override setting 1",
                fm.getLocationAsPaths(javaCompiler), override1);

        Path override2 = Files.createDirectories(base.resolve("override2"));
        fm.setLocationFromPaths(javaCompiler, List.of(override2));
        checkEqual("override setting 2",
                fm.getLocationAsPaths(javaCompiler), override2);
    }
}
项目:javaide    文件:JavacProcessingEnvironment.java   
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocation(CLASS_PATH);

        if (needClassLoader(options.get(PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
项目:openjdk-jdk10    文件:ContainsTest.java   
void checkContains(StandardJavaFileManager fm, Location l, FileObject fo, boolean expect) throws IOException {
    boolean found = fm.contains(l, fo);
    if (found) {
        if (expect) {
            out.println("file found, as expected: " + l + " " + fo.getName());
        } else {
            error("file not found: " + l + " " + fo.getName());
        }
    } else {
        if (expect) {
            error("file found unexpectedly: " + l + " " + fo.getName());
        } else {
            out.println("file not found, as expected: " + l + " " + fo.getName());
        }
    }
}
项目:openjdk-jdk10    文件:T7159016.java   
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
        JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
                                                       fm.getJavaFileObjects(src));
        task.setProcessors(Collections.singleton(new Proc()));
        if (!task.call()) {
            throw new Error("Test failed");
        }
    }
}
项目:OpenJSharp    文件:JavacProcessingEnvironment.java   
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocation(CLASS_PATH);

        if (needClassLoader(options.get(PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
项目:OpenJSharp    文件:DocFileFactory.java   
/**
 * Get the appropriate factory, based on the file manager given in the
 * configuration.
 */
static synchronized DocFileFactory getFactory(Configuration configuration) {
    DocFileFactory f = factories.get(configuration);
    if (f == null) {
        JavaFileManager fm = configuration.getFileManager();
        if (fm instanceof StandardJavaFileManager)
            f = new StandardDocFileFactory(configuration);
        else {
            try {
                Class<?> pathFileManagerClass =
                        Class.forName("com.sun.tools.javac.nio.PathFileManager");
                if (pathFileManagerClass.isAssignableFrom(fm.getClass()))
                    f = new PathDocFileFactory(configuration);
            } catch (Throwable t) {
                throw new IllegalStateException(t);
            }
        }
        factories.put(configuration, f);
    }
    return f;
}
项目:openjdk-jdk10    文件:SetLocationForModule.java   
@Test
public void testBasic(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location[] locns = {
            StandardLocation.SOURCE_PATH,
            StandardLocation.CLASS_PATH,
            StandardLocation.PLATFORM_CLASS_PATH,
        };
        // set a value
        Path out = Files.createDirectories(base.resolve("out"));
        for (Location locn : locns) {
            checkException("unsupported for location",
                    IllegalArgumentException.class,
                    "location is not an output location or a module-oriented location: " + locn,
                    () -> fm.setLocationForModule(locn, "m", List.of(out)));
        }
    }
}
项目:openjdk-jdk10    文件:JavacProcessingEnvironment.java   
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocationAsPaths(CLASS_PATH);

        if (needClassLoader(options.get(Option.PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
项目:openjdk-jdk10    文件:FailureAtomicity.java   
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(null, null, null)) {
        List<File> files = sourceFiles.stream()
                                      .map(p -> p.toFile())
                                      .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                                Arrays.asList(dest.toFile()));
        fileManager.setLocation(StandardLocation.CLASS_PATH,
                                Arrays.asList(TEST_CLASSES.toFile()));
        JavaCompiler.CompilationTask task = compiler
                .getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
项目:openjdk-jdk10    文件:TestSelfRef.java   
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (EnclosingKind ek : EnclosingKind.values()) {
                for (SiteKind sk : SiteKind.values()) {
                    if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
                        continue;
                    for (InnerKind ik : InnerKind.values()) {
                        if (ik != InnerKind.NONE && sk == SiteKind.NONE)
                            break;
                        for (RefKind rk : RefKind.values()) {
                            new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
项目:openjdk-jdk10    文件:ModuleInfoTreeAccess.java   
@Test
public void testTreePathForModuleDecl(Path base) throws Exception {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "/** Test module */ module m1x {}");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(src));
        JavacTask task = (JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();
        JavacTrees trees = JavacTrees.instance(task);
        ModuleElement mdle = (ModuleElement) task.getElements().getModuleElement("m1x");

        TreePath path = trees.getPath(mdle);
        assertNotNull("path", path);

        ModuleElement mdle1 = (ModuleElement) trees.getElement(path);
        assertNotNull("mdle1", mdle1);

        DocCommentTree docCommentTree = trees.getDocCommentTree(mdle);
        assertNotNull("docCommentTree", docCommentTree);
    }
}
项目:openjdk-jdk10    文件:EdgeCases.java   
@Test
public void testModuleSymbolOutterMostClass(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path moduleSrc = base.resolve("module-src");
        Path m1 = moduleSrc.resolve("m1x");

        tb.writeJavaFiles(m1, "module m1x { }");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(moduleSrc));
        com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();

        ModuleSymbol msym = (ModuleSymbol) task.getElements().getModuleElement("m1x");

        msym.outermostClass();
    }
}
项目:dubbocloud    文件: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);
}
项目:openjdk-jdk10    文件:TestDuplicateImport.java   
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (ImportKind ik1 : ImportKind.values()) {
            for (ImportKind ik2 : ImportKind.values()) {
                for (QualifierKind qk1 : QualifierKind.values()) {
                    for (QualifierKind qk2 : QualifierKind.values()) {
                        for (NameKind nk1 : NameKind.values()) {
                            for (NameKind nk2 : NameKind.values()) {
                                new TestDuplicateImport(ik1, ik2, qk1, qk2, nk1, nk2).run(comp, fm);
                            }
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
项目:openjdk-jdk10    文件:JImageGenerator.java   
public static boolean compile(Path source, Path destination, String... options) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (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.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));

        List<String> opts = Arrays.asList(options);
        JavaCompiler.CompilationTask task
                = compiler.getTask(null, jfm, null, opts, null,
                jfm.getJavaFileObjectsFromPaths(sources));
        List<String> list = new ArrayList<>(opts);
        list.addAll(sources.stream()
                .map(Path::toString)
                .collect(Collectors.toList()));
        System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
        return task.call();
    }
}
项目:openjdk-jdk10    文件:GetTask_DocletClassTest.java   
/**
 * Verify that exceptions from a doclet are thrown as expected.
 */
@Test
public void testBadDoclet() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        DocumentationTask t = tool.getTask(null, fm, null, BadDoclet.class, null, files);
        try {
            t.call();
            error("call completed without exception");
        } catch (RuntimeException e) {
            e.printStackTrace();
            Throwable c = e.getCause();
            if (c.getClass() == UnexpectedError.class)
                System.err.println("exception caught as expected: " + c);
            else
                throw e;
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_FileManagerTest.java   
/**
 * Verify that an alternate file manager can be specified:
 * in this case, a TestFileManager.
 */
@Test
public void testFileManager() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = new TestFileManager();
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, null, Arrays.asList("-verbose"), files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
    } else {
        throw new Exception("task failed");
    }
}
项目:dremio-oss    文件:TestClassCompilers.java   
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
项目:openjdk-jdk10    文件:ModuleSourcePathTest.java   
@Test
public void setLocation(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, List.of(src));
        new JavacTask(tb)
                .options("-XDrawDiagnostics")
                .fileManager(fm)
                .outdir(modules)
                .files(findJavaFiles(src))
                .run()
                .writeAll();

        checkFiles(modules.resolve("m1x/module-info.class"), modules.resolve("m1x/a/A.class"));
    }
}
项目:openjdk-jdk10    文件:CompilerUtils.java   
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compile(Path source, Path destination, String... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    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.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();
}
项目:openjdk-jdk10    文件:CompilerUtils.java   
/**
 * Compile the specified module from the given module sourcepath
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compileModule(Path source, Path destination,
                                    String moduleName, String... options) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    try {
        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                                 Arrays.asList(destination));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    Stream<String> opts = Arrays.stream(new String[] {
        "--module-source-path", source.toString(), "-m", moduleName
    });
    List<String> javacOpts = Stream.concat(opts, Arrays.stream(options))
                                    .collect(Collectors.toList());
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, javacOpts, null, null);
    return task.call();
}
项目:openjdk-jdk10    文件:TestSuperclass.java   
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        int errors = 0;

        for (ClassKind ck: ClassKind.values()) {
            for (GenericKind gk: GenericKind.values()) {
                for (SuperKind sk: SuperKind.values()) {
                    errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
                }
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors found");
    }
}
项目:openjdk-jdk10    文件:TestSuperclass.java   
int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException {
    System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk);
    File testDir = new File(ck + "-" + gk + "-" + sk);
    testDir.mkdirs();
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir));

    JavaSource js = new JavaSource();
    System.err.println(js.getCharContent(false));
    CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js));
    if (!t.call())
        throw new Error("compilation failed");

    File testClass = new File(testDir, "Test.class");
    String out = javap(testClass);

    // Extract class sig from first line of Java source
    String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1");

    // Extract class sig from line from javap output
    String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1");

    checkEqual("class signature", expect, found);

    return errors;
}
项目:openjdk-jdk10    文件:GenericConstructorAndDiamondTest.java   
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
            for (BoundKind boundKind : BoundKind.values()) {
                for (ConstructorKind constructorKind : ConstructorKind.values()) {
                    for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
                        for (TypeArgArity arity : TypeArgArity.values()) {
                            for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
                                for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
                                    for (ArgumentKind argKind : ArgumentKind.values()) {
                                        new GenericConstructorAndDiamondTest(boundKind, constructorKind,
                                                declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
项目:openjdk-jdk10    文件: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();
    try (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);
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_FileObjectsTest.java   
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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((JavaFileObject) null);
        try {
            DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
            error("getTask succeeded, no exception thrown");
        } catch (NullPointerException e) {
            System.err.println("exception caught as expected: " + e);
        }
    }
}
项目:openjdk-jdk10    文件:ArrayCreationTree.java   
public static void main(String[] args) throws Exception {
    PrintWriter out = new PrintWriter(System.out, true);
    JavacTool tool = JavacTool.create();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File testSrc = new File(System.getProperty("test.src"));
        Iterable<? extends JavaFileObject> f =
            fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "ArrayCreationTree.java")));
        JavacTask task = tool.getTask(out, fm, null, null, null, f);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        out.flush();

        Scanner s = new Scanner();
        for (CompilationUnitTree t: trees)
            s.scan(t, null);
    }
}
项目:openjdk-jdk10    文件:BadLambdaExpr.java   
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (ParameterListKind plk : ParameterListKind.values()) {
                for (ParameterKind pk : ParameterKind.values()) {
                    for (ArrowKind ak : ArrowKind.values()) {
                        for (ExprKind ek : ExprKind.values()) {
                            new BadLambdaExpr(plk, pk, ak, ek).run(comp, fm);
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
项目:openjdk-jdk10    文件:GetTask_OptionsTest.java   
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        }
    }
}
项目:openjdk-jdk10    文件:TestGetScope.java   
public void run() throws IOException {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {

        List<String> opts = Arrays.asList("-proc:only", "-doe");
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
        JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
        t.setProcessors(Collections.singleton(this));
        boolean ok = t.call();
        if (!ok)
            throw new Error("compilation failed");
    }
}
项目:openjdk-jdk10    文件:GetTask_DocletClassTest.java   
/**
 * Verify that exceptions from a doclet are thrown as expected.
 */
@Test
public void testBadDoclet() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (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);
        DocumentationTask t = tool.getTask(null, fm, null, BadDoclet.class, null, files);
        try {
            t.call();
            error("call completed without exception");
        } catch (RuntimeException e) {
            Throwable c = e.getCause();
            if (c.getClass() == UnexpectedError.class)
                System.err.println("exception caught as expected: " + c);
            else
                throw e;
        }
    }
}
项目:openjdk-jdk10    文件:GetTask_FileManagerTest.java   
/**
 * Verify that an alternate file manager can be specified:
 * in this case, a TestFileManager.
 */
@Test
public void testFileManager() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = new TestFileManager();
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, null, Arrays.asList("-verbose"), files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
    } else {
        throw new Exception("task failed");
    }
}
项目:Reer    文件:JdkJavaCompiler.java   
private JavaCompiler.CompilationTask createCompileTask(JavaCompileSpec spec) {
    List<String> options = new JavaCompilerArgumentsBuilder(spec).build();
    JavaCompiler compiler = javaHomeBasedJavaCompilerFactory.create();
    CompileOptions compileOptions = spec.getCompileOptions();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, compileOptions.getEncoding() != null ? Charset.forName(compileOptions.getEncoding()) : null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(spec.getSource());
    return compiler.getTask(null, null, null, options, null, compilationUnits);
}