Java Code Examples for javax.tools.JavaCompiler.CompilationTask#call()

The following examples show how to use javax.tools.JavaCompiler.CompilationTask#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: TestGetResource2.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void testMissingResource(JavaCompiler javac) throws Exception {
    System.err.println("testMissingResource");
    File tmpdir = new File("testMissingResource");
    File srcdir = new File(tmpdir, "src");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result when missing resource: " + result);
    expect(result, false);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 2
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void test(List<String> options, String expect) throws Exception {
    System.err.println("test: " + options);
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileObject f = new MyFileObject("myfo://test", "class Bad { Missing x; }");
    List<? extends JavaFileObject> files = Arrays.asList(f);
    CompilationTask task = javac.getTask(pw, null, null, options, null, files);
    boolean ok = task.call();
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (ok)
        throw new Exception("Compilation succeeded unexpectedly");
    if (!out.contains(expect))
        throw new Exception("expected text not found: " + expect);
}
 
Example 3
Source File: T6378728.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    // Get a compiler tool
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String srcdir = System.getProperty("test.src");
    File source = new File(srcdir, "T6378728.java");
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);

    CompilationTask task =
        compiler.getTask(null,
                         new ExceptionalFileManager(fm),
                         null,
                         Arrays.asList("-proc:only"),
                         null,
                         fm.getJavaFileObjectsFromFiles(Arrays.asList(source)));
    if (!task.call())
        throw new RuntimeException("Unexpected compilation failure");
}
 
Example 4
Source File: TestSuperclass.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: TestSuperclass.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: TestGetResource2.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void testCompositeSourcePath(JavaCompiler javac) throws Exception {
    System.err.println("testCompositeSearchPath");
    File tmpdir = new File("testCompositeSourcePath");
    File srcdir = new File(tmpdir, "src");
    File rsrcdir = new File(tmpdir, "rsrc");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    write(rsrcdir, "resources/file.txt", "hello");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir + File.pathSeparator + rsrcdir, "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result with composite source path: " + result);
    expect(result, true);
}
 
Example 7
Source File: TestGetResource2.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void testSingleSourceDir(JavaCompiler javac) throws Exception {
    System.err.println("testSingleSourceDir");
    File tmpdir = new File("testSingleSourceDir");
    File srcdir = new File(tmpdir, "src");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    write(srcdir, "resources/file.txt", "hello");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result with single source dir: " + result);
    expect(result, true);
}
 
Example 8
Source File: TreePosRoundsTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    String testSrc = System.getProperty("test.src");
    String testClasses = System.getProperty("test.classes");
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);
    String thisName = TreePosRoundsTest.class.getName();
    File thisFile = new File(testSrc, thisName + ".java");
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
    List<String> options = Arrays.asList(
            "-proc:only",
            "-processor", thisName,
            "-processorpath", testClasses);
    CompilationTask t = c.getTask(null, fm, null, options, null, files);
    boolean ok = t.call();
    if (!ok)
        throw new Exception("processing failed");
}
 
Example 9
Source File: T6378728.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    // Get a compiler tool
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String srcdir = System.getProperty("test.src");
    File source = new File(srcdir, "T6378728.java");
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);

    CompilationTask task =
        compiler.getTask(null,
                         new ExceptionalFileManager(fm),
                         null,
                         Arrays.asList("-proc:only"),
                         null,
                         fm.getJavaFileObjectsFromFiles(Arrays.asList(source)));
    if (!task.call())
        throw new RuntimeException("Unexpected compilation failure");
}
 
Example 10
Source File: JdkCompiler.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 编译
 *
 * @param className 类名
 * @param context   内容
 * @return 编译好的内
 * @throws ClassNotFoundException 类没有找到
 */
public Class<?> compile(final String className, final CharSequence context) throws ClassNotFoundException {
    // compilation units
    JavaFileObject fileObject = new CharSequenceJavaFileObject(className, context);
    Iterable<? extends JavaFileObject> fileObjs = Collections.singletonList(fileObject);
    // compiler options
    ClassLoader classLoader = JdkCompiler.class.getClassLoader();
    String path = classLoader.getResource("").getPath();
    List<String> options = new ArrayList<>();
    options.add("-d");
    options.add(path);
    // compile the dynamic class
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        return null;
    }
    StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
    CompilationTask task = compiler.getTask(null, fileMgr, null, options, null, fileObjs);
    if (!task.call()) {
        throw new RuntimeException("Error occurs while compiling.");
    }
    return classLoader.loadClass(className);
}
 
Example 11
Source File: TestGetResource2.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void testCompositeSourcePath(JavaCompiler javac) throws Exception {
    System.err.println("testCompositeSearchPath");
    File tmpdir = new File("testCompositeSourcePath");
    File srcdir = new File(tmpdir, "src");
    File rsrcdir = new File(tmpdir, "rsrc");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    write(rsrcdir, "resources/file.txt", "hello");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir + File.pathSeparator + rsrcdir, "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result with composite source path: " + result);
    expect(result, true);
}
 
Example 12
Source File: InMemoryJavaCompiler.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compiles the class with the given name and source code.
 *
 * @param className The name of the class
 * @param sourceCode The source code for the class with name {@code className}
 * @throws RuntimeException if the compilation did not succeed
 * @return The resulting byte code from the compilation
 */
public static byte[] compile(String className, CharSequence sourceCode) {
    MemoryJavaFileObject file = new MemoryJavaFileObject(className, sourceCode);
    CompilationTask task = getCompilationTask(file);

    if(!task.call()) {
        throw new RuntimeException("Could not compile " + className + " with source code " + sourceCode);
    }

    return file.getByteCode();
}
 
Example 13
Source File: T7031108.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void compile(JavaCompiler comp, JavaFileManager fm,
        DiagnosticListener<JavaFileObject> dl,
        String processor, JavaFileObject... files) throws Exception {
    System.err.println("compile processor:" + processor + ", files:" + Arrays.asList(files));
    List<String> opts = new ArrayList<String>();
    if (processor != null) {
        // opts.add("-verbose");
        opts.addAll(Arrays.asList("-processor", processor));
    }
    CompilationTask task = comp.getTask(null, fm, dl, opts, null, Arrays.asList(files));
    boolean ok = task.call();
    if (dl == null && !ok)
        throw new Exception("compilation failed");
}
 
Example 14
Source File: T6458823.java    From jdk8u60 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 15
Source File: EagerInterfaceCompletionTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void compile(DiagnosticChecker dc, JavaSource... sources) {
    try {
        CompilationTask ct = javacTool.getTask(null, null, dc,
                Arrays.asList("-d", testDir.getAbsolutePath(), "-cp",
                testDir.getAbsolutePath(), versionKind.optsArr[0], versionKind.optsArr[1]),
                null, Arrays.asList(sources));
        ct.call();
    }
    catch (Exception e) {
        e.printStackTrace();
        error("Internal compilation error");
    }
}
 
Example 16
Source File: Example.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
    if (out != null && keys != null)
        throw new IllegalArgumentException();

    if (verbose)
        System.err.println("run_jsr199: " + opts + " " + files);

    DiagnosticCollector<JavaFileObject> dc = null;
    if (keys != null)
        dc = new DiagnosticCollector<JavaFileObject>();

    if (raw) {
        List<String> newOpts = new ArrayList<String>();
        newOpts.add("-XDrawDiagnostics");
        newOpts.addAll(opts);
        opts = newOpts;
    }

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager fm = c.getStandardFileManager(dc, null, null);
    if (fmOpts != null)
        fm = new FileManager(fm, fmOpts);

    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);

    CompilationTask t = c.getTask(out, fm, dc, opts, null, fos);
    Boolean ok = t.call();

    if (keys != null) {
        for (Diagnostic<? extends JavaFileObject> d: dc.getDiagnostics()) {
            scanForKeys(unwrap(d), keys);
        }
    }

    return ok;
}
 
Example 17
Source File: Helper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: InMemoryJavaCompiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compiles the class with the given name and source code.
 *
 * @param className The name of the class
 * @param sourceCode The source code for the class with name {@code className}
 * @throws RuntimeException if the compilation did not succeed
 * @return The resulting byte code from the compilation
 */
public static byte[] compile(String className, CharSequence sourceCode) {
    MemoryJavaFileObject file = new MemoryJavaFileObject(className, sourceCode);
    CompilationTask task = getCompilationTask(file);

    if(!task.call()) {
        throw new RuntimeException("Could not compile " + className + " with source code " + sourceCode);
    }

    return file.getByteCode();
}
 
Example 19
Source File: Example.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
    if (out != null && keys != null)
        throw new IllegalArgumentException();

    if (verbose)
        System.err.println("run_jsr199: " + opts + " " + files);

    DiagnosticCollector<JavaFileObject> dc = null;
    if (keys != null)
        dc = new DiagnosticCollector<JavaFileObject>();

    if (raw) {
        List<String> newOpts = new ArrayList<String>();
        newOpts.add("-XDrawDiagnostics");
        newOpts.addAll(opts);
        opts = newOpts;
    }

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager fm = c.getStandardFileManager(dc, null, null);
    if (fmOpts != null)
        fm = new FileManager(fm, fmOpts);

    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);

    CompilationTask t = c.getTask(out, fm, dc, opts, null, fos);
    Boolean ok = t.call();

    if (keys != null) {
        for (Diagnostic<? extends JavaFileObject> d: dc.getDiagnostics()) {
            scanForKeys(unwrap(d), keys);
        }
    }

    return ok;
}
 
Example 20
Source File: Helper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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;
}