Java Code Examples for com.sun.source.util.JavacTask

The following examples show how to use com.sun.source.util.JavacTask. These examples are extracted from open source projects. 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
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource();
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            null, null, Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError(errorMessage +
                    source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError(errorMessage +
                source.getCharContent(true));
    }
    check();
}
 
Example 2
Source Project: hottub   Source File: TestClose.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void add(ProcessingEnvironment env, Runnable r) {
    try {
        JavacTask task = JavacTask.instance(env);
        TaskListener l = ((BasicJavacTask) task).getTaskListeners().iterator().next();
        // The TaskListener is an instanceof TestClose, but when using the
        // default class loaders. the taskListener uses a different
        // instance of Class<TestClose> than the anno processor.
        // If you try to evaluate
        //      TestClose tc = (TestClose) (l).
        // you get the following somewhat confusing error:
        //   java.lang.ClassCastException: TestClose cannot be cast to TestClose
        // The workaround is to access the fields of TestClose with reflection.
        Field f = l.getClass().getField("runnables");
        @SuppressWarnings("unchecked")
        List<Runnable> runnables = (List<Runnable>) f.get(l);
        runnables.add(r);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
 
Example 3
Source Project: jdk8u60   Source File: T6733837.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example 4
Source Project: openjdk-jdk9   Source File: EdgeCases.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddExportUndefinedModule(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "package test; import undefPackage.Any; public class Test {}");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);

    List<String> log = new JavacTask(tb)
            .options("--add-exports", "undefModule/undefPackage=ALL-UNNAMED",
                     "-XDrawDiagnostics")
            .outdir(classes)
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutputLines(Task.OutputKind.DIRECT);

    List<String> expected = Arrays.asList("- compiler.warn.module.for.option.not.found: --add-exports, undefModule",
                                          "Test.java:1:34: compiler.err.doesnt.exist: undefPackage",
                                          "1 error", "1 warning");

    if (!expected.equals(log))
        throw new Exception("expected output not found: " + log);
}
 
Example 5
@Test
void testClassesInProfiles() throws Exception {
    for (Profile p: Profile.values()) {
        for (Map.Entry<Profile, List<JavaFileObject>> e: testClasses.entrySet()) {
            for (JavaFileObject fo: e.getValue()) {
                DiagnosticCollector<JavaFileObject> dl =
                        new DiagnosticCollector<JavaFileObject>();
                List<String> opts = (p == Profile.DEFAULT)
                        ? Collections.<String>emptyList()
                        : Arrays.asList("-profile", p.name);
                JavacTask task = (JavacTask) javac.getTask(null, fm, dl, opts, null,
                        Arrays.asList(fo));
                task.analyze();

                List<String> expectDiagCodes = (p.value >= e.getKey().value)
                        ? Collections.<String>emptyList()
                        : Arrays.asList("compiler.err.not.in.profile");

                checkDiags(opts + " " + fo.getName(), dl.getDiagnostics(), expectDiagCodes);
            }
        }
    }
}
 
Example 6
Source Project: openjdk-jdk9   Source File: T6457284.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Context context = new Context();
    MyMessages.preRegister(context);
    JavacTool tool = JavacTool.create();
    JavacTask task = tool.getTask(null, null, null, null, null,
                                  List.of(new MyFileObject()),
                                  context);
    task.parse();
    for (Element e : task.analyze()) {
        if (!e.getEnclosingElement().toString().equals("compiler.misc.unnamed.package"))
            throw new AssertionError(e.getEnclosingElement());
        System.out.println("OK: " + e.getEnclosingElement());
        return;
    }
    throw new AssertionError("No top-level classes!");
}
 
Example 7
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
    if (classpaths.size() > 0)
        fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
    JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
    if (generate) {
        File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
        // @@@ Assert that this directory didn't exist, or start counter at max+1
        destDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
        ct.generate();
        return destDir;
    }
    else {
        ct.analyze();
        return nullDir;
    }
}
 
Example 8
Source Project: openjdk-jdk9   Source File: TestGetScope.java    License: GNU General Public License v2.0 6 votes vote down vote up
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");
    }
}
 
Example 9
Source Project: openjdk-jdk8u   Source File: Abort.java    License: GNU General Public License v2.0 6 votes vote down vote up
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");
        }
    }
 
Example 10
Source Project: TencentKona-8   Source File: T6993305.java    License: GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File f = new File(testSrc, T6993305.class.getSimpleName() + ".java");
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(f);
    JavacTask task = tool.getTask(null, fm, null, null, null, fos);
    Iterable<? extends CompilationUnitTree> cus = task.parse();

    TestScanner s = new TestScanner();
    s.scan(cus, task);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 11
Source Project: openjdk-8   Source File: T6410706.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws IOException {
    String testSrc = System.getProperty("test.src", ".");
    String testClasses = System.getProperty("test.classes", ".");
    JavacTool tool = JavacTool.create();
    MyDiagListener dl = new MyDiagListener();
    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(testClasses)));
    Iterable<? extends JavaFileObject> files =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6410706.class.getName()+".java")));
    JavacTask task = tool.getTask(null, fm, dl, null, null, files);
    task.parse();
    task.analyze();
    task.generate();

    // expect 2 notes:
    // Note: T6410706.java uses or overrides a deprecated API.
    // Note: Recompile with -Xlint:deprecation for details.

    if (dl.notes != 2)
        throw new AssertionError(dl.notes + " notes given");
}
 
Example 12
public static void main(String[] args) throws Exception {
    PrintWriter out = new PrintWriter(System.out, true);
    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File testSrc = new File(System.getProperty("test.src"));
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "AnnotatedArrayOrder.java")));
    JavacTask task = tool.getTask(out, fm, null, null, null, f);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    out.flush();

    Scanner s = new Scanner();
    for (CompilationUnitTree t: trees)
        s.scan(t, null);

}
 
Example 13
Source Project: openjdk-8   Source File: ArrayCreationTree.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    PrintWriter out = new PrintWriter(System.out, true);
    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File testSrc = new File(System.getProperty("test.src"));
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "ArrayCreationTree.java")));
    JavacTask task = tool.getTask(out, fm, null, null, null, f);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    out.flush();

    Scanner s = new Scanner();
    for (CompilationUnitTree t: trees)
        s.scan(t, null);

}
 
Example 14
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 15
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
    if (classpaths.size() > 0)
        fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
    JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
    if (generate) {
        File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
        // @@@ Assert that this directory didn't exist, or start counter at max+1
        destDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
        ct.generate();
        return destDir;
    }
    else {
        ct.analyze();
        return nullDir;
    }
}
 
Example 16
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example 17
Source Project: dragonwell8_jdk   Source File: FDTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 18
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            vk.getOptions(), null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 19
public static void main(String... args) throws Exception {
    JavacTool tool = JavacTool.create();
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, null);
    Context ctx = ((JavacTaskImpl)task).getContext();
    TreeMaker treeMaker = TreeMaker.instance(ctx);
    Symtab syms = Symtab.instance(ctx);

    String stringTree = printTree(treeMaker.QualIdent(syms.stringType.tsym));

    if (!"java.lang.String".equals(stringTree)) {
        throw new IllegalStateException(stringTree);
    }
}
 
Example 20
void doTest(String platformSpec, String expectedParameter) {
    ToolBox tb = new ToolBox();
    Task.Result result =
            new JavacTask(tb, Task.Mode.EXEC)
              .outdir(".")
              .options("-J--class-path=" + System.getProperty("test.classes"),
                       "-J--add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED",
                       "-J--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
                       "-XDrawDiagnostics",
                       "--release",
                       platformSpec,
                       System.getProperty("test.src") + "/PlatformProviderTestSource.java")
              .run();

    List<String> expectedOutput =
            Arrays.asList("getSupportedPlatformNames",
                          "getPlatform(name, " + expectedParameter + ")",
                          "getSourceVersion",
                          "getTargetVersion",
                          "getPlatformPath",
                          "testPlugin: [testPluginKey=testPluginValue]",
                          "process: {testAPKey=testAPValue}",
                          "process: {testAPKey=testAPValue}",
                          "PlatformProviderTestSource.java:4:49: compiler.warn.raw.class.use: java.util.ArrayList, java.util.ArrayList<E>",
                          "compiler.misc.count.warn",
                          "close");
    List<String> actualOutput = result.getOutputLines(Task.OutputKind.STDERR);
    result.writeAll();
    if (!expectedOutput.equals(actualOutput)) {
        throw new AssertionError(  "Expected output: " + expectedOutput +
                                 "; actual output: " + actualOutput);
    }
    result.writeAll();
}
 
Example 21
Source Project: openjdk-8   Source File: Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
void testAnnoProcessor(JavacTool javac, StandardJavaFileManager fm,
        Iterable<? extends JavaFileObject> files, PrintWriter out,
        int expectedDocComments) {
    out.println("Test annotation processor");
    JavacTask task = javac.getTask(out, fm, null, null, null, files);
    AnnoProc ap = new AnnoProc(DocTrees.instance(task));
    task.setProcessors(Arrays.asList(ap));
    task.call();
    ap.checker.checkDocComments(expectedDocComments);
}
 
Example 22
Source Project: deptective   Source File: DeptectiveTreeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public DeptectiveTreeVisitor(JavacTask task, Log log, PackageReferenceHandler packageReferenceHandler) {
    elements = task.getElements();
    types = task.getTypes();
    trees = Trees.instance(task);
    this.log = log;
    this.packageReferenceHandler = packageReferenceHandler;
}
 
Example 23
Source Project: TencentKona-8   Source File: FDTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 24
public void run() {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    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");
}
 
Example 25
Source Project: openjdk-8-source   Source File: Warn5.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc,
            Arrays.asList(xlint.getXlintOption(),
                "-source", sourceLevel.sourceKey),
            null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable t) {
        processException(t);
    }
    check();
}
 
Example 26
Source Project: jdk8u60   Source File: GenericOverrideTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
            level.opts != null ? Arrays.asList(level.opts) : null,
            null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling the following code:\n" +
                source.getCharContent(true));
    }
    check();
}
 
Example 27
Source Project: openjdk-jdk8u   Source File: T6665791.java    License: 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();
    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 28
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    checkCount++;
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    ct.parse();
    if (diagChecker.errorFound) {
        throw new Error("Unexpected parser error for source:\n" +
            source.getCharContent(true));
    }
}
 
Example 29
void test() throws Exception {
    System.out.println("\n====================================");
    System.out.println(fInterface + ", " +  context + ", " + methodReference);
    System.out.println(samSourceFile + "\n" + clientSourceFile);

    DiagnosticChecker dc = new DiagnosticChecker();
    JavacTask ct = (JavacTask)comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
    ct.analyze();
    if (dc.errorFound == checkSamConversion()) {
        throw new AssertionError(samSourceFile + "\n\n" + clientSourceFile);
    }
    count++;
}
 
Example 30
public static void main(String[] args) throws Exception {
    write(test_java, test);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    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");
    }
}