Java 类javax.tools.ToolProvider 实例源码

项目: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");
        }
    }
}
项目:openjdk-jdk10    文件: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();
    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);
        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>(noIndexFiles);
            checkFiles(outDir, expectFiles);
        } else {
            error("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());
}
项目:openjdk-jdk10    文件:PackageInfoTest.java   
private void compile(String option, Path destDir, Path... files)
        throws IOException
{
    System.err.println("compile...");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> fileObjects =
            fm.getJavaFileObjectsFromPaths(Arrays.asList(files));

        List<String> options = new ArrayList<>();
        if (option != null) {
            options.add(option);
        }
        if (destDir != null) {
            options.add("-d");
            options.add(destDir.toString());
        }
        options.add("-cp");
        options.add(System.getProperty("test.classes", "."));

        JavaCompiler.CompilationTask task =
            compiler.getTask(null, fm, null, options, null, fileObjects);
        if (!task.call())
            throw new AssertionError("compilation failed");
    }
}
项目:openjdk-jdk10    文件:ModuleSourcePathTest.java   
@Test
public void getLocation_ISA(Path base) throws Exception {
    Path src1 = base.resolve("src1");
    tb.writeJavaFiles(src1.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path src2 = base.resolve("src2");
    tb.writeJavaFiles(src2.resolve("m2x").resolve("extra"), "module m2x { }", "package b; class B { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    String FS = File.separator;
    String PS = File.pathSeparator;
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.handleOption("--module-source-path",
                List.of(src1 + PS + src2 + FS + "*" + FS + "extra").iterator());

        try {
            Iterable<? extends Path> paths = fm.getLocationAsPaths(StandardLocation.MODULE_SOURCE_PATH);
            out.println("result: " + asList(paths));
            throw new Exception("expected IllegalStateException not thrown");
        } catch (IllegalStateException e) {
            out.println("Exception thrown, as expected: " + e);
        }

        // even if we can't do getLocation for the MODULE_SOURCE_PATH, we should be able
        // to do getLocation for the modules, which will additionally confirm the option
        // was effective as intended.
        Location locn1 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m1x");
        checkLocation(fm.getLocationAsPaths(locn1), List.of(src1.resolve("m1x")));
        Location locn2 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m2x");
        checkLocation(fm.getLocationAsPaths(locn2), List.of(src2.resolve("m2x").resolve("extra")));
    }
}
项目:ditb    文件:TestClassFinder.java   
/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter,
    String packageNameSuffix, String classNamePrefix) throws Exception {
  classNamePrefix = classNamePrefix + counter;
  String packageName = makePackageName(packageNameSuffix, counter);
  String javaPath = basePath + classNamePrefix + ".java";
  String classPath = basePath + classNamePrefix + ".class";
  PrintStream source = new PrintStream(javaPath);
  source.println("package " + packageName + ";");
  source.println("public class " + classNamePrefix
      + " { public static void main(String[] args) { } };");
  source.close();
  JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
  int result = jc.run(null, null, null, javaPath);
  assertEquals(0, result);
  File classFile = new File(classPath);
  assertTrue(classFile.exists());
  return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
项目:incubator-netbeans    文件:DefaultSourceLevelQueryImpl.java   
@NonNull
private static String parsePackage(@NonNull final FileObject javaFile) {
    String pkg = "";    //NOI18N
    try {
        JavacTask jt = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(
                null,
                null,
                null,
                Collections.EMPTY_LIST,
                Collections.EMPTY_LIST,
                Collections.singleton(new JFO(javaFile)));
        final Iterator<? extends CompilationUnitTree> cus = jt.parse().iterator();
        if (cus.hasNext()) {
            pkg = Optional.ofNullable(cus.next().getPackage())
                .map((pt) -> pt.getPackageName())
                .map((xt) -> xt.toString())
                .orElse(pkg);
        }
    } catch (IOException ioe) {
        //TODO: Log & pass
    }
    return pkg;
}
项目: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());
}
项目:incubator-netbeans    文件:FileManagerTest.java   
/** Crates the default javac file managare tro have something to comare 
    * our file managers against
    */
   public static JavaFileManager createGoldenJFM( File[] classpath, File[] sourcpath ) throws IOException {

JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
       StandardJavaFileManager fm = jc.getStandardFileManager (null, null, null);

if ( classpath != null ) {
           fm.setLocation(StandardLocation.CLASS_PATH,Arrays.asList(classpath));
}

if ( sourcpath != null ) {
    fm.setLocation(StandardLocation.SOURCE_PATH,Arrays.asList(sourcpath));
}

return fm;

   }
项目: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    文件:T6963934.java   
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
                fileManager.getJavaFileObjects(thisSrc));
        CompilationUnitTree tree = task.parse().iterator().next();
        int count = 0;
        for (ImportTree importTree : tree.getImports()) {
            System.out.println(importTree);
            count++;
        }
        int expected = 7;
        if (count != expected)
            throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
    }
}
项目:openjdk-jdk10    文件:BadConstantValue.java   
private static BadClassFile loadBadClass(String className) {
    // load the class, and save the thrown BadClassFile exception
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
            Arrays.asList("-classpath", classesdir.getPath()), null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    BadClassFile badClassFile;
    try {
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
                .resolveIdent(syms.unnamedModule, className).complete();
    } catch (BadClassFile e) {
        return e;
    }
    return null;
}
项目:mybatis-generator-plugin    文件:MyBatisGeneratorTool.java   
/**
 * 动态编译java文件
 * @param files
 */
private void compileJavaFiles(List<File> files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //获取java文件管理类
    StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
    //获取java文件对象迭代器
    Iterable<? extends JavaFileObject> it = manager.getJavaFileObjectsFromFiles(files);
    //设置编译参数
    ArrayList<String> ops = new ArrayList<>();
    ops.add("-Xlint:unchecked");
    //获取编译任务
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, ops, null, it);
    //执行编译任务
    task.call();
}
项目:javaide    文件:Launcher.java   
public static void main(String... args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    /*JFileChooser fileChooser;
    Preferences prefs = Preferences.userNodeForPackage(Launcher.class);
    if (args.length > 0)
        fileChooser = new JFileChooser(args[0]);
    else {
        String fileName = prefs.get("recent.file", null);
        fileChooser = new JFileChooser();
        if (fileName != null) {
            fileChooser = new JFileChooser();
            fileChooser.setSelectedFile(new File(fileName));
        }
    }
    if (fileChooser.showOpenDialog(null) == fileChooser.APPROVE_OPTION) {
        String fileName = fileChooser.getSelectedFile().getPath();
        prefs.put("recent.file", fileName);
        javac.run(System.in, null, null, "-d", "/tmp", fileName);
    }*/
}
项目:openjdk-jdk10    文件:EagerInterfaceCompletionTest.java   
public static void main(String[] args) throws Exception {
    String SCRATCH_DIR = System.getProperty("user.dir");
    JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
    int n = 0;
    for (VersionKind versionKind : VersionKind.values()) {
        for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
            for (TestKind testKind : TestKind.values()) {
                for (ActionKind actionKind : ActionKind.values()) {
                    File testDir = new File(SCRATCH_DIR, "test"+n);
                    new EagerInterfaceCompletionTest(javacTool, testDir, versionKind,
                            hierarchyKind, testKind, actionKind).test();
                    n++;
                }
            }
        }
    }
    if (nerrors > 0) {
        throw new AssertionError("Some errors have been detected");
    }
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
public static void main(String... args) {
    // The following code allows the test to be skipped when run on
    // an exploded image.
    // See https://bugs.openjdk.java.net/browse/JDK-8155858
    Path javaHome = Paths.get(System.getProperty("java.home"));
    Path image = javaHome.resolve("lib").resolve("modules");
    Path modules = javaHome.resolve("modules");
    if (!Files.exists(image) && Files.exists(modules)) {
        System.err.println("Test running on exploded image");
        System.err.println("Test skipped!");
        return;
    }

    System.setSecurityManager(new SecurityManager());

    Objects.requireNonNull(ToolProvider.getSystemDocumentationTool());
    Objects.requireNonNull(ToolProvider.getSystemJavaCompiler());
    if (ToolProvider.getSystemToolClassLoader() != null) {
        throw new AssertionError("unexpected value for getSystemToolClassLoader");
    }
}
项目:OpenJSharp    文件:SchemaGenerator.java   
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            return task.call();
        }
项目:MaxSim    文件:TestBootNativeLibraryPath.java   
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
项目: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    文件:TestBase.java   
private <S> InMemoryFileManager compile(
        List<String> options,
        Function<S, ? extends JavaFileObject> src2JavaFileObject,
        List<S> sources)
        throws IOException, CompilationException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<? extends JavaFileObject> src = sources.stream()
            .map(src2JavaFileObject)
            .collect(Collectors.toList());

    DiagnosticCollector<? super JavaFileObject> dc = new DiagnosticCollector<>();
    try (InMemoryFileManager fileManager
                 = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
        boolean success = task.call();
        if (!success) {
            String errorMessage = dc.getDiagnostics().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining("\n"));
            throw new CompilationException("Compilation Error\n\n" + errorMessage);
        }
        return fileManager;
    }
}
项目:openjdk-jdk10    文件:DuplicateConstantPoolEntry.java   
void generateFilesNeeded() throws Exception {

        StringJavaFileObject[] CSource = new StringJavaFileObject[] {
            new StringJavaFileObject("C.java",
                "class C {C(String s) {}}"),
        };

        List<StringJavaFileObject> AandBSource = Arrays.asList(
                new StringJavaFileObject("A.java",
                    "class A {void test() {new B(null);new C(null);}}"),
                new StringJavaFileObject("B.java",
                    "class B {B(String s) {}}")
        );

        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
        JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null,
                Arrays.asList(CSource));
        if (!compileC.call()) {
            throw new AssertionError("Compilation error while compiling C.java sources");
        }
        JavacTask compileAB = (JavacTask)tool.getTask(null, null, null,
                Arrays.asList("-cp", "."), null, AandBSource);
        if (!compileAB.call()) {
            throw new AssertionError("Compilation error while compiling A and B sources");
        }
    }
项目:openjdk-jdk10    文件:T7086601b.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 (TypeKind a1 : TypeKind.values()) {
                for (TypeKind a2 : TypeKind.values()) {
                    for (TypeKind a3 : TypeKind.values()) {
                        for (MethodCallKind mck : MethodCallKind.values()) {
                            new T7086601b(a1, a2, a3, mck).run(comp, fm);
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
项目:openjdk-jdk10    文件:Basic.java   
static void javac(Path dest, Path... sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null)) {

        List<File> files = Stream.of(sourceFiles)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        List<File> dests = Stream.of(dest)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);
        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    文件:T8068517.java   
void runTest(String aJava, String bJava) throws Exception {
    try (JavaFileManager fm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null)) {
        ToolBox tb = new ToolBox();
        ToolBox.MemoryFileManager memoryFM1 = new ToolBox.MemoryFileManager(fm);
        new JavacTask(tb).fileManager(memoryFM1)
                          .sources(aJava, bJava)
                          .run();
        ToolBox.MemoryFileManager memoryFM2 = new ToolBox.MemoryFileManager(fm);
        new JavacTask(tb).fileManager(memoryFM2)
                          .sources(bJava, aJava)
                          .run();

        Assert.check(Arrays.equals(memoryFM1.getFileBytes(StandardLocation.CLASS_OUTPUT, "B"),
                                   memoryFM2.getFileBytes(StandardLocation.CLASS_OUTPUT, "B")));
    }
}
项目:openjdk-jdk10    文件:InferenceRegressionTest02.java   
void run() throws Exception {
    Context context = new Context();
    JavacFileManager.preRegister(context);
    Trees trees = JavacTrees.instance(context);
    StringWriter strOut = new StringWriter();
    PrintWriter pw = new PrintWriter(strOut);
    DPrinter dprinter = new DPrinter(pw, trees);
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(new JavaSource()));
    Iterable<? extends CompilationUnitTree> elements = ct.parse();
    ct.analyze();
    Assert.check(elements.iterator().hasNext());
    dprinter.treeTypes(true).printTree("", (JCTree)elements.iterator().next());
    String output = strOut.toString();
    Assert.check(!output.contains("java.lang.Object"), "there shouldn't be any type instantiated to Object");
}
项目: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");
    }
}
项目: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    文件:IgnoreIgnorableCharactersInInput.java   
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    File classesDir = new File(System.getProperty("user.dir"), "classes");
    classesDir.mkdirs();
    JavaSource[] sources = new JavaSource[]{
        new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"),
        new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")};
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            Arrays.asList("-d", classesDir.getPath()),
            null, Arrays.asList(sources));
    try {
        if (!ct.call()) {
            throw new AssertionError("Error thrown when compiling test cases");
        }
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling test cases");
    }
    check(classesDir,
            "TestOneIgnorableChar.class",
            "TestOneIgnorableChar$AABB.class",
            "TestMultipleIgnorableChar.class",
            "TestMultipleIgnorableChar$AABB.class");
    if (errors > 0)
        throw new AssertionError("There are some errors in the test check the error output");
}
项目: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    文件: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    文件: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    文件:T6557752.java   
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    task.analyze();
    trees = Trees.instance(task);
    MyVisitor myVisitor = new MyVisitor();
    for (CompilationUnitTree ast : asts) {
        myVisitor.compilationUnit = ast;
        myVisitor.scan(ast, null);
    }

    if (!myVisitor.foundError) {
        throw new AssertionError("Expected error not found!");
    }
}
项目:openjdk-jdk10    文件:DetectMutableStaticFields.java   
private void run()
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor,
        URISyntaxException {

    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        for (String module: modules) {
            analyzeModule(fm, module);
        }
    }

    if (errors.size() > 0) {
        for (String error: errors) {
            System.err.println(error);
        }
        throw new AssertionError("There are mutable fields, "
            + "please check output");
    }
}
项目: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    文件: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_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");
    }
}