Java Code Examples for javax.tools.JavaCompiler#getStandardFileManager()

The following examples show how to use javax.tools.JavaCompiler#getStandardFileManager() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SchemaGenerator.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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();
        }
 
Example 2
Source File: T7159016.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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");
        }
    }
}
 
Example 3
Source File: T6963934.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
    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);
}
 
Example 4
Source File: GenericConstructorAndDiamondTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 (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);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 5
Source File: BadLambdaExpr.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 (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);
    }
 
Example 6
Source File: TestDefaultMethodsSyntax.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 (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);
    }
 
Example 7
Source File: MRJARCachingFileManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 8
Source File: GenericConstructorAndDiamondTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 (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);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 9
Source File: FileManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** 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;
	
   }
 
Example 10
Source File: T6458823.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 11
Source File: InterfaceMethodHidingTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 (MethodKind mk1 : MethodKind.values()) {
            for (SignatureKind sk1 : SignatureKind.values()) {
                for (BodyExpr be1 : BodyExpr.values()) {
                    for (MethodKind mk2 : MethodKind.values()) {
                        for (SignatureKind sk2 : SignatureKind.values()) {
                            for (BodyExpr be2 : BodyExpr.values()) {
                                for (MethodKind mk3 : MethodKind.values()) {
                                    for (SignatureKind sk3 : SignatureKind.values()) {
                                        for (BodyExpr be3 : BodyExpr.values()) {
                                            new InterfaceMethodHidingTest(mk1, mk2, mk3, sk1, sk2, sk3, be1, be2, be3).run(comp, fm);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
Example 12
Source File: DocletPathTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verify that an alternate doclet can be specified, and located via
 * the file manager's DOCLET_PATH.
 */
@Test
public void testDocletPath() throws Exception {
    JavaFileObject docletSrc =
            createSimpleJavaFileObject("DocletOnDocletPath", docletSrcText);
    File docletDir = getOutDir("classes");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager cfm = compiler.getStandardFileManager(null, null, null);
    cfm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(docletDir));
    Iterable<? extends JavaFileObject> cfiles = Arrays.asList(docletSrc);
    if (!compiler.getTask(null, cfm, null, null, null, cfiles).call())
        throw new Exception("cannot compile doclet");

    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir("api");
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    fm.setLocation(DocumentationTool.Location.DOCLET_PATH, Arrays.asList(docletDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    Iterable<String> options = Arrays.asList("-doclet", "DocletOnDocletPath");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentationTask t = tool.getTask(pw, fm, null, null, options, files);
    boolean ok = t.call();
    String out = sw.toString();
    System.err.println(">>" + out + "<<");
    if (ok) {
        if (out.contains(TEST_STRING)) {
            System.err.println("doclet executed as expected");
        } else {
            error("test string not found in doclet output");
        }
    } else {
        error("task failed");
    }
}
 
Example 13
Source File: TestModularizedEvent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static boolean compile(Path source, Path destination, String... options)
        throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        // no compiler available
        throw new UnsupportedOperationException("Unable to get system java compiler. "
                + "Perhaps, jdk.compiler module is not available.");
    }
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

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

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

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

    return task.call();
}
 
Example 14
Source File: T6665791.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    write(test_java, test);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager manager =
            compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
        final StringWriter sw = new StringWriter();
        JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null,
                null, units);

        new TreeScanner<Boolean, Void>() {
            @Override
            public Boolean visitClass(ClassTree arg0, Void arg1) {
                sw.write(arg0.toString());
                return super.visitClass(arg0, arg1);
            }
        }.scan(task.parse(), null);

        System.out.println("output:");
        System.out.println(sw.toString());
        String found = sw.toString().replaceAll("\\s+", " ").trim();
        String expect = test.replaceAll("\\s+", " ").trim();
        if (!expect.equals(found)) {
            System.out.println("expect: " + expect);
            System.out.println("found:  " + found);
            throw new Exception("unexpected output");
        }
    }
}
 
Example 15
Source File: DynamicEngine.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public Object execute(String fullClassName, String javaCode, String method, Class<?>[] paramsCls,Object[] params) throws Exception {
      Object result = null;
      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
      ClassFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(diagnostics, null, null));
 
      List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>();
      jfiles.add(new CharSequenceJavaFileObject(fullClassName, javaCode));
 
      List<String> options = new ArrayList<String>();
      options.add("-encoding");
      options.add(Constants.CHARSET.toString());
      options.add("-classpath");
      options.add(this.classpath);
 
      JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, jfiles);
      boolean success = task.call();
 
      if (success) {
          JavaClassObject jco = fileManager.getJavaClassObject();
          DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(this.parentClassLoader);
          Class<?> clazz = dynamicClassLoader.loadClass(fullClassName,jco);
          result = invoke(clazz, method, paramsCls, params);
          
//        instance = clazz.newInstance();
	dynamicClassLoader.close();
      } else {
          StringBuilder error = new StringBuilder();
          for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
          	error.append(compilePrint(diagnostic));
          }
          throw new Exception(error.toString());
      }

      return result;
  }
 
Example 16
Source File: QueryBeforeEnter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testSingleNamed(Path base) throws Exception {
    Path moduleSrc = base.resolve("module-src");
    Path m1 = moduleSrc.resolve("m1x");

    tb.writeJavaFiles(m1,
                      "module m1x { exports m1x; }",
                      "package m1x; public class M1 {}");

    Path m2 = moduleSrc.resolve("m2x");

    tb.writeJavaFiles(m2,
                      "module m2x { exports m2x; }",
                      "package m2x; public class M2 {}");

    Path modulePath = base.resolve("module-path");

    Files.createDirectories(modulePath);

    new JavacTask(tb)
            .options("--module-source-path", moduleSrc.toString())
            .outdir(modulePath)
            .files(findJavaFiles(moduleSrc))
            .run()
            .writeAll();

    Path cpSrc = base.resolve("cp-src");

    tb.writeJavaFiles(cpSrc,
                      "package cp; public class CP {}");

    Path cp = base.resolve("cp");

    Files.createDirectories(cp);

    new JavacTask(tb)
            .outdir(cp)
            .files(findJavaFiles(cpSrc))
            .run()
            .writeAll();

    Path src = base.resolve("src");

    tb.writeJavaFiles(src,
                      "module test { requires java.base; requires m1x; } ",
                      "package test; public class Test {}");

    Path out = base.resolve("out");

    Files.createDirectories(out);

    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) javaCompiler.getTask(null,
                                                          null,
                                                          d -> { throw new IllegalStateException(d.toString()); },
                                                          Arrays.asList("--module-path", modulePath.toString(),
                                                                        "--class-path", cp.toString(),
                                                                        "-sourcepath", src.toString()),
                                                          null,
                                                          fm.getJavaFileObjects(findJavaFiles(src)));
        assertNotNull(task.getElements().getTypeElement("java.lang.String"));
        assertNull(task.getElements().getTypeElement("javax.tools.ToolProvider"));
        assertNotNull(task.getElements().getTypeElement("m1x.M1"));
        assertNull(task.getElements().getTypeElement("m2x.M2"));
        assertNotNull(task.getElements().getTypeElement("test.Test"));
        assertNotNull(task.getElements().getModuleElement("java.base"));
        assertNull(task.getElements().getModuleElement("java.compiler"));
        assertNotNull(task.getElements().getModuleElement("m1x"));
        assertNull(task.getElements().getModuleElement("m2x"));
        assertNotNull(task.getElements().getModuleElement("test"));
    }
}
 
Example 17
Source File: TagletPathTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verify that a taglet can be specified, and located via
 * the file manager's TAGLET_PATH.
 */
@Test
public void testTagletPath() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File tagletSrcFile = new File(testSrc, "taglets/UnderlineTaglet.java");
    File tagletDir = getOutDir("classes");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager cfm = compiler.getStandardFileManager(null, null, null)) {
        cfm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tagletDir));
        Iterable<? extends JavaFileObject> cfiles = cfm.getJavaFileObjects(tagletSrcFile);
        if (!compiler.getTask(null, cfm, null, null, null, cfiles).call())
            throw new Exception("cannot compile taglet");
    }

    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", testSrcText);
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir("api");
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        fm.setLocation(DocumentationTool.Location.TAGLET_PATH, Arrays.asList(tagletDir));
        Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
        Iterable<String> options = Arrays.asList("-taglet", "UnderlineTaglet");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        DocumentationTask t = tool.getTask(pw, fm, null, null, options, files);
        boolean ok = t.call();
        String out = sw.toString();
        System.err.println(">>" + out + "<<");
        if (ok) {
            File f = new File(outDir, "pkg/C.html");
            List<String> doc = Files.readAllLines(f.toPath(), Charset.defaultCharset());
            for (String line: doc) {
                if (line.contains("<u>" + TEST_STRING + "</u>")) {
                    System.err.println("taglet executed as expected");
                    return;
                }
            }
            error("expected text not found in output " + f);
        } else {
            error("task failed");
        }
    }
}
 
Example 18
Source File: MemoryClassLoader.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
MemoryFileManager(JavaCompiler compiler) {
    super(compiler.getStandardFileManager(null, null, null));
}
 
Example 19
Source File: TreeEndPosTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static JavaFileManager getJavaFileManager(JavaCompiler compiler,
        DiagnosticCollector dc) {
    return compiler.getStandardFileManager(dc, null, null);
}
 
Example 20
Source File: ClassFileManager.java    From aion-germany with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Creates new ClassFileManager.
 *
 * @param compiler
 *            that will be used
 * @param listener
 *            class that will report compilation errors
 */
public ClassFileManager(JavaCompiler compiler, DiagnosticListener<? super JavaFileObject> listener) {
	super(compiler.getStandardFileManager(listener, null, null));
}