Java Code Examples for com.sun.source.util.JavacTask#call()

The following examples show how to use com.sun.source.util.JavacTask#call() . 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: InnerClassCannotBeVerified.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 File: IgnoreIgnorableCharactersInInput.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 3
Source File: T6430241.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void testTaskAPI(boolean expectWarnings, Iterable<? extends File> pcp) throws Exception {
    System.err.println("test task API: " + pcp);

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

    if (pcp != null)
        fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, pcp);

    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(testFile);

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavacTask task = tool.getTask(pw, fm, null, null, null, files);
    boolean ok = task.call();
    String out = showOutput(sw.toString());

    checkCompilationOK(ok);
    checkOutput(out, expectWarnings);
}
 
Example 4
Source File: DuplicateConstantPoolEntry.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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");
        }
    }
 
Example 5
Source File: Test.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void testTaskListener(JavacTool javac, StandardJavaFileManager fm,
        Iterable<? extends JavaFileObject> files, PrintWriter out,
        int expectedDocComments) {
    out.println("Test task listener");
    JavacTask task = javac.getTask(out, fm, null, null, null, files);
    TaskListnr tl = new TaskListnr(DocTrees.instance(task));
    task.addTaskListener(tl);
    task.call();
    tl.checker.checkDocComments(expectedDocComments);
}
 
Example 6
Source File: CheckACC_STRICTFlagOnPkgAccessClassTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void compile(JavaCompiler comp) {
    JavacTask ct = (JavacTask)comp.getTask(null, null, null, null, null,
            Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError(CompilationErrorMessage +
                    source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError(CompilationErrorMessage +
                source.getCharContent(true));
    }
}
 
Example 7
Source File: Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testTaskListener(JavacTool javac, StandardJavaFileManager fm,
        Iterable<? extends JavaFileObject> files, PrintWriter out,
        int expectedDocComments) {
    out.println("Test task listener");
    JavacTask task = javac.getTask(out, fm, null, null, null, files);
    TaskListnr tl = new TaskListnr(DocTrees.instance(task));
    task.addTaskListener(tl);
    task.call();
    tl.checker.checkDocComments(expectedDocComments);
}
 
Example 8
Source File: NativeHeaderTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The worker method for each test case.
 * Compile the files and verify that exactly the expected set of header files
 * is generated.
 */
void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception {
    List<String> args = new ArrayList<String>();
    if (gk == GenKind.FULL)
        args.add("-XDjavah:full");

    switch (rk) {
        case CMD:
            args.add("-d");
            args.add(classesDir.getPath());
            args.add("-h");
            args.add(headersDir.getPath());
            for (File f: files)
                args.add(f.getPath());
            int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]));
            if (rc != 0)
                throw new Exception("compilation failed, rc=" + rc);
            break;

        case API:
            fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir));
            fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir));
            fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir));
            JavacTask task = javac.getTask(null, fm, null, args, null,
                    fm.getJavaFileObjectsFromFiles(files));
            if (!task.call())
                throw new Exception("compilation failed");
            break;
    }

    Set<String> found = createSet(headersDir.list());
    checkEqual("header files", expect, found);
}
 
Example 9
Source File: T7042566.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    int id = checkCount.incrementAndGet();
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(id);
    ErrorChecker ec = new ErrorChecker();
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), ec,
            null, null, Arrays.asList(source));
    ct.call();
    check(source, ec, id);
}
 
Example 10
Source File: NativeHeaderTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The worker method for each test case.
 * Compile the files and verify that exactly the expected set of header files
 * is generated.
 */
void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception {
    List<String> args = new ArrayList<String>();
    if (gk == GenKind.FULL)
        args.add("-XDjavah:full");

    switch (rk) {
        case CMD:
            args.add("-d");
            args.add(classesDir.getPath());
            args.add("-h");
            args.add(headersDir.getPath());
            for (File f: files)
                args.add(f.getPath());
            int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]));
            if (rc != 0)
                throw new Exception("compilation failed, rc=" + rc);
            break;

        case API:
            fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir));
            fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir));
            fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir));
            JavacTask task = javac.getTask(null, fm, null, args, null,
                    fm.getJavaFileObjectsFromFiles(files));
            if (!task.call())
                throw new Exception("compilation failed");
            break;
    }

    Set<String> found = createSet(headersDir.list());
    checkEqual("header files", expect, found);
}
 
Example 11
Source File: T7190862.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void compile(JavaCompiler comp) {
    JavacTask ct = (JavacTask)comp.getTask(null, null, null, null, null, Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError("Error thrown when compiling the following source:\n" + source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling the following source:\n" + source.getCharContent(true));
    }
}
 
Example 12
Source File: T7093325.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    int id = checkCount.incrementAndGet();
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(id);
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), null,
            null, null, Arrays.asList(source));
    ct.call();
    verifyBytecode(source, id);
}
 
Example 13
Source File: TestGetScope.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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 14
Source File: Test.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void testTaskListener(JavacTool javac, StandardJavaFileManager fm,
        Iterable<? extends JavaFileObject> files, PrintWriter out,
        int expectedDocComments) {
    out.println("Test task listener");
    JavacTask task = javac.getTask(out, fm, null, null, null, files);
    TaskListnr tl = new TaskListnr(DocTrees.instance(task));
    task.addTaskListener(tl);
    task.call();
    tl.checker.checkDocComments(expectedDocComments);
}
 
Example 15
Source File: RunTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testInit(boolean expectOK, String[] args, List<? extends JavaFileObject> files) {
    JavacTool javac = JavacTool.create();
    JavacTask task = javac.getTask(null, null, null, null, null, files);
    try {
        DocLint dl = new DocLint();
        dl.init(task, args, true);
        if (!expectOK)
            error("expected IllegalArgumentException not thrown");
        task.call();
    } catch (IllegalArgumentException e) {
        System.err.println(e);
        if (expectOK)
            error("unexpected IllegalArgumentException caught");
    }
}
 
Example 16
Source File: RunTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void testInit(boolean expectOK, String[] args, List<? extends JavaFileObject> files) {
    JavacTool javac = JavacTool.create();
    JavacTask task = javac.getTask(null, null, null, null, null, files);
    try {
        DocLint dl = new DocLint();
        dl.init(task, args, true);
        if (!expectOK)
            error("expected IllegalArgumentException not thrown");
        task.call();
    } catch (IllegalArgumentException e) {
        System.err.println(e);
        if (expectOK)
            error("unexpected IllegalArgumentException caught");
    }
}
 
Example 17
Source File: RunTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void testInit(boolean expectOK, String[] args, List<? extends JavaFileObject> files) {
    JavacTool javac = JavacTool.create();
    JavacTask task = javac.getTask(null, null, null, null, null, files);
    try {
        DocLint dl = new DocLint();
        dl.init(task, args, true);
        if (!expectOK)
            error("expected IllegalArgumentException not thrown");
        task.call();
    } catch (IllegalArgumentException e) {
        System.err.println(e);
        if (expectOK)
            error("unexpected IllegalArgumentException caught");
    }
}
 
Example 18
Source File: Compiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
        File dir = cache.get(type.getName());
        if (dir != null) {
            return dir;
        }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum =
        (name, src) -> { files.add(new SourceFile(name, src)); };

    Collection<Type> deps = type.typeDependencies(type.isFullCompilation());
    for (Type dep : deps) {
        if (type.isFullCompilation())
            dep.generate(accum);
        else
            dep.generateAsDependency(accum, type.methodDependencies());
    }

    type.generate(accum);

    JavacTask ct = (JavacTask)this.systemJavaCompiler.getTask(
        null, this.fm, null, null, null, files);
    File destDir = null;
    do {
        int value = counter.incrementAndGet();
        destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());

    if (this.flags.contains(Flags.VERBOSE)) {
        System.out.println("Compilation unit for " + type.getName() +
            " : compiled into " + destDir);
        for (JavaFileObject jfo : files) {
            System.out.println(jfo.toString());
        }
    }

    try {
        destDir.mkdirs();
        this.fm.setLocation(
            StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
        throw new RuntimeException(
            "IOException encountered during compilation", e);
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
        throw new RuntimeException(
            "Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
        File existing = cache.putIfAbsent(type.getName(), destDir);
        if (existing != null) {
            deleteDir(destDir);
            return existing;
        }
    } else {
    this.tempDirs.add(destDir);
    }
    return destDir;
}
 
Example 19
Source File: TestClose2.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
void run() throws IOException {
    File testSrc = new File(System.getProperty("test.src"));
    File testClasses = new File(System.getProperty("test.classes"));

    JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
    final ClassLoader cl = getClass().getClassLoader();
    Context c = new Context();
    StandardJavaFileManager fm = new JavacFileManager(c, true, null) {
        @Override
        protected ClassLoader getClassLoader(URL[] urls) {
            return new URLClassLoader(urls, cl) {
                @Override
                public void close() throws IOException {
                    System.err.println(getClass().getName() + " closing");
                    TestClose2.this.closedCount++;
                    TestClose2.this.closedIsLast = true;
                    super.close();
                }
            };
        }
    };

    fm.setLocation(StandardLocation.CLASS_OUTPUT,
            Collections.singleton(new File(".")));
    fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH,
            Collections.singleton(testClasses));
    Iterable<? extends JavaFileObject> files =
            fm.getJavaFileObjects(new File(testSrc, TestClose2.class.getName() + ".java"));
    List<String> options = Arrays.asList(
            "-processor", TestClose2.class.getName());

    JavacTask task = tool.getTask(null, fm, null, options, null, files);
    task.setTaskListener(this);

    if (!task.call())
        throw new Error("compilation failed");

    if (closedCount == 0)
        throw new Error("no closing message");
    else if (closedCount > 1)
        throw new Error(closedCount + " closed messages");

    if (!closedIsLast)
        throw new Error("closing message not last");
}
 
Example 20
Source File: TestSuppression.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
void test(String src, WarningKind wk, int gen) throws Exception {
        count++;
        System.err.println("Test " + count + ": wk:" + wk + " gen:" + gen + " src:" +src);

        File testDir = new File("test" + count);
        File srcDir = createDir(testDir, "src");
        File gensrcDir = createDir(testDir, "gensrc");
        File classesDir = createDir(testDir, "classes");

        File x = writeFile(new File(srcDir, "X.java"), src);

        DiagListener dl = new DiagListener();
        JavacTool tool = JavacTool.create();
        StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
        fm.setLocation(StandardLocation.CLASS_PATH,
                Arrays.asList(classesDir, new File(System.getProperty("test.classes"))));
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classesDir));
        fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(gensrcDir));
        List<String> args = new ArrayList<String>();
//        args.add("-XprintProcessorInfo");
        args.add("-XprintRounds");
        args.add("-Agen=" + gen);
        if (wk == WarningKind.YES)
            args.add("-Xlint:serial");
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(x);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        JavacTask task = tool.getTask(pw, fm, dl, args, null, files);
        task.setProcessors(Arrays.asList(new AnnoProc()));
        boolean ok = task.call();
        pw.close();

        System.err.println("ok:" + ok + " diags:" + dl.counts);
        if (sw.toString().length() > 0) {
            System.err.println("output:\n" + sw.toString());
        }

        for (Diagnostic.Kind dk: Diagnostic.Kind.values()) {
            Integer v = dl.counts.get(dk);
            int found = (v == null) ? 0 : v;
            int expect = (dk == Diagnostic.Kind.WARNING && wk == WarningKind.YES) ? gen : 0;
            if (found != expect) {
                error("Unexpected value for " + dk + ": expected: " + expect + " found: " + found);
            }
        }

        System.err.println();
    }