Java 类javax.tools.JavaCompiler 实例源码

项目: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    文件:ReleaseOptionThroughAPI.java   
void run() throws IOException {
    String lineSep = System.getProperty("line.separator");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
         StringWriter out = new StringWriter();
         PrintWriter outWriter = new PrintWriter(out)) {
        Iterable<? extends JavaFileObject> input =
                fm.getJavaFileObjects(System.getProperty("test.src") + "/ReleaseOption.java");
        List<String> options = Arrays.asList("--release", "7", "-XDrawDiagnostics");

        compiler.getTask(outWriter, fm, null, options, null, input).call();
        String expected =
                "ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.stream" + lineSep +
                "1 error" + lineSep;
        if (!expected.equals(out.toString())) {
            throw new AssertionError("Unexpected output: " + out.toString());
        }
    }
}
项目:monarch    文件:ClassBuilder.java   
/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 * 
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 * @throws IOException
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  OutputStreamJavaFileManager<JavaFileManager> fileManager =
      new OutputStreamJavaFileManager<JavaFileManager>(
          javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);

  List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
  fileObjects.add(new JavaSourceFromString(className, classCode));

  List<String> options = Arrays.asList("-classpath", this.classPath);
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
    StringBuilder errorMsg = new StringBuilder();
    for (Diagnostic d : diagnostics.getDiagnostics()) {
      String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
          d.getMessage(null));
      errorMsg.append(err);
      System.err.print(err);
    }
    throw new IOException(errorMsg.toString());
  }
  return byteArrayOutputStream.toByteArray();
}
项目: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    文件:ModuleInfoTreeAccess.java   
@Test
public void testTreePathForModuleDeclWithImport(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "import java.lang.Deprecated; /** Test module */ @Deprecated 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);
    }
}
项目:GitHub    文件:CompilerWarningIT.java   
@Parameters(name="{0}")
public static Collection<Object[]> parameters() {
  JavaCompiler systemJavaCompiler = Compiler.systemJavaCompiler();
  JavaCompiler eclipseCompiler = Compiler.eclipseCompiler();
  return Arrays.asList(new Object[][] {
    {
      "includeAccessorsWithSystemJavaCompiler",
      systemJavaCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      Matchers.empty()
    },
    {
      "includeAccessorsWithEclipseCompiler",
      eclipseCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      onlyCastExceptions()
    }
  });
}
项目:openjdk-jdk10    文件:InterruptedExceptionTest.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 (XlintOption xlint : XlintOption.values()) {
                for (SuppressLevel suppress_decl : SuppressLevel.values()) {
                    for (SuppressLevel suppress_use : SuppressLevel.values()) {
                        for (ClassKind ck : ClassKind.values()) {
                            for (ExceptionKind ek_decl : ExceptionKind.values()) {
                                for (ExceptionKind ek_use : ExceptionKind.values()) {
                                    new InterruptedExceptionTest(xlint, suppress_decl,
                                            suppress_use, ck, ek_decl, ek_use).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
项目: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    文件: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);
    }
}
项目: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    文件: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;
}
项目: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);
}
项目: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");
}
项目: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();
}
项目: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);
    }
}
项目: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    文件: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    文件: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    文件: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    文件: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    文件: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    文件:T7190862.java   
private void run(JavaCompiler comp) {
    String code;
    for (TypeWideInstructionMap typeInstructionMap: TypeWideInstructionMap.values()) {
        if (typeInstructionMap != TypeWideInstructionMap.OBJECT) {
            code = createWideLocalSource(typeInstructionMap.type, 300);
        } else {
            code = createWideLocalSourceForObject(300);
        }
        source = new JavaSource(code);
        compile(comp);
        check(typeInstructionMap.instructions);
    }

    //an extra test for the iinc instruction
    code = createIincSource();
    source = new JavaSource(code);
    compile(comp);
    check(new String[]{"iinc_w"});
}
项目: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    文件: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    文件:TestBootstrapMethodsCount.java   
public void run(JavaCompiler comp) {
    JavaSource source = new JavaSource();
    JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, null, dc,
            Arrays.asList("-g"), null, Arrays.asList(source));
    Context context = ct.getContext();
    Symtab syms = Symtab.instance(context);
    Names names = Names.instance(context);
    Types types = Types.instance(context);
    ct.addTaskListener(new Indifier(syms, names, types));
    try {
        ct.generate();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new AssertionError(
                String.format("Error thrown when compiling following code\n%s",
                        source.source));
    }
    if (dc.diagFound) {
        throw new AssertionError(
                String.format("Diags found when compiling following code\n%s\n\n%s",
                        source.source, dc.printDiags()));
    }
    verifyBytecode();
}
项目:openjdk-jdk10    文件:Abort.java   
public static void main(String... args) throws Exception {

        String SCRATCH_DIR = System.getProperty("user.dir");
        JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
        java.io.File testDir = new java.io.File(SCRATCH_DIR);

        sourceA.dumpTo(testDir);
        sourceB.dumpTo(testDir);

        DiagnosticChecker diagChecker = new DiagnosticChecker();
        JavacTask ct = (JavacTask)javacTool.getTask(null, null, diagChecker,
                Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()),
                null, Arrays.asList(sourceA.asJFO(testDir)));
        try {
            ct.analyze();
        } catch (Throwable ex) {
            //ignore abort exception thrown by javac
        }

        if (!diagChecker.errorFound) {
            throw new AssertionError("Missing diagnostic");
        }
    }
项目:openjdk-jdk10    文件:ElementStructureTest.java   
void run(Writer output, String version) throws Exception {
    List<String> options = Arrays.asList("--release", version, "-classpath", "");
    List<ToolBox.JavaSource> files = Arrays.asList(new ToolBox.JavaSource("Test", ""));
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, options, null, files);

    task.analyze();

    JavaFileManager fm = task.getContext().get(JavaFileManager.class);

    for (String pack : packages(fm)) {
        PackageElement packEl = task.getElements().getPackageElement(pack);
        if (packEl == null) {
            throw new AssertionError("Cannot find package: " + pack);
        }
        new ExhaustiveElementScanner(task, output, p -> true).visit(packEl);
    }
}
项目:openjdk-jdk10    文件:JavacExtensionTest.java   
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
项目: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    文件: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")));
    }
}
项目: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    文件:T6472751.java   
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    trees = Trees.instance(task);
    positions = trees.getSourcePositions();
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    for (CompilationUnitTree ast : asts) {
        new MyVisitor().scan(ast, null);
    }
}
项目:Reer    文件:JavaHomeBasedJavaCompilerFactory.java   
private JavaCompiler findCompiler() {
    File realJavaHome = currentJvmJavaHomeFactory.create();
    File javaHomeFromToolProvidersPointOfView = systemPropertiesJavaHomeFactory.create();
    if (realJavaHome.equals(javaHomeFromToolProvidersPointOfView)) {
        return systemJavaCompilerFactory.create();
    }

    return SystemProperties.getInstance().withJavaHome(realJavaHome, systemJavaCompilerFactory);
}
项目:openjdk-jdk10    文件:IntersectionTypeParserTest.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 (CastKind ck : CastKind.values()) {
            for (TypeKind t1 : TypeKind.values()) {
                for (ArrayKind ak1 : ArrayKind.values()) {
                    Type typ1 = new Type(t1, ak1);
                    if (ck.nBounds == 1) {
                        new IntersectionTypeParserTest(ck, typ1).run(comp, fm);
                        continue;
                    }
                    for (TypeKind t2 : TypeKind.values()) {
                        for (ArrayKind ak2 : ArrayKind.values()) {
                            Type typ2 = new Type(t2, ak2);
                            if (ck.nBounds == 2) {
                                new IntersectionTypeParserTest(ck, typ1, typ2).run(comp, fm);
                                continue;
                            }
                            for (TypeKind t3 : TypeKind.values()) {
                                for (ArrayKind ak3 : ArrayKind.values()) {
                                    Type typ3 = new Type(t3, ak3);
                                    new IntersectionTypeParserTest(ck, typ1, typ2, typ3).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
}
项目:openjdk-jdk10    文件:Helper.java   
public static boolean compileCode(String className, String contents,
        DiagnosticCollector<JavaFileObject> diagnostics) {
    boolean ok = false;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }

    JavaFileObject file = getFile(className, contents);
    Iterable<? extends JavaFileObject> compilationUnit = Arrays.asList(file);

    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit);
    ok = task.call();
    return ok;
}
项目: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);
}
项目:GitHub    文件:SimpleCompiler.java   
@Override
public JavaCompiler.CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options, Iterable<String> classes,
        Iterable<? extends JavaFileObject> compilationUnits) {
    return compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
}
项目:openjdk-jdk10    文件:CompleteOnClosed.java   
public static void main(String... args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
    String source = "class Test extends CompleteOnClosedOther {" +
                    "     class Inner extends Undefined { }" +
                    "}";
    Iterable<JavaFileObject> files = Arrays.<JavaFileObject>asList(new ToolBox.JavaSource(source));
    Iterable<String> options = Arrays.asList("-processor", "CompleteOnClosed");
    CompilationTask task = compiler.getTask(null, null, collector, options, null, files);
    task.call();
    for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
        System.out.println(d.toString());
    }
}
项目:GitHub    文件:Jsonschema2PojoRule.java   
public ClassLoader compile(JavaCompiler compiler, Writer out, List<File> classpath, Map<String, Object> config) {
    if (classLoader != null) {
        throw new IllegalStateException("cannot recompile sources");
    }
    DiagnosticListener<JavaFileObject> diagnosticListener = captureDiagnostics ? new CapturingDiagnosticListener() : null;
    classLoader = CodeGenerationHelper.compile(compiler, out, getGenerateDir(), getCompileDir(), classpath, config, diagnosticListener);
    return classLoader;
}