Java Code Examples for javax.tools.JavaCompiler

The following examples show how to use javax.tools.JavaCompiler. 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
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");
    }
}
 
Example 2
Source Project: netbeans   Source File: FileManagerTest.java    License: 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 3
Source Project: openjdk-jdk9   Source File: T6852595.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example 4
@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);
    }
}
 
Example 5
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");
    }
}
 
Example 6
Source Project: openjdk-jdk8u   Source File: TestSelfRef.java    License: 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 (EnclosingKind ek : EnclosingKind.values()) {
            for (SiteKind sk : SiteKind.values()) {
                if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
                    continue;
                for (InnerKind ik : InnerKind.values()) {
                    if (ik != InnerKind.NONE && sk == SiteKind.NONE)
                        break;
                    for (RefKind rk : RefKind.values()) {
                        new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
Example 7
Source Project: jdk8u60   Source File: T6557752.java    License: GNU General Public License v2.0 6 votes vote down vote up
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!");
    }
}
 
Example 8
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 (TypeKind a1 : TypeKind.values()) {
            for (TypeKind a2 : TypeKind.values()) {
                for (TypeKind a3 : TypeKind.values()) {
                    for (MethodCallKind mck : MethodCallKind.values()) {
                        new T7086601b(a1, a2, a3, mck).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
Example 9
Source Project: TencentKona-8   Source File: TestSuperclass.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    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");
}
 
Example 10
Source Project: TencentKona-8   Source File: TestSuperclass.java    License: 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 11
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);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 12
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 13
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 14
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 15
void run() throws Exception {
    Context context = new Context();
    JavacFileManager.preRegister(context);
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(new JavaSource()));
    Iterable<? extends CompilationUnitTree> elements = ct.parse();
    ct.analyze();
    Assert.check(elements.iterator().hasNext());
    JCTree topLevel = (JCTree)elements.iterator().next();
    new TreeScanner() {
        @Override
        public void visitReference(JCMemberReference tree) {
            Assert.check(tree.getOverloadKind() != null);
        }
    }.scan(topLevel);
}
 
Example 16
Source Project: netbeans   Source File: MRJARCachingFileManagerTest.java    License: 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 17
Source Project: openjdk-jdk9   Source File: TestSuperclass.java    License: GNU General Public License v2.0 6 votes vote down vote up
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");
    }
}
 
Example 18
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 19
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");
    }
}
 
Example 20
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 21
Source Project: TencentKona-8   Source File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    task.analyze();
    for (CompilationUnitTree ast : asts) {
        new MyVisitor().scan(ast, null);
    }
}
 
Example 22
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 23
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 24
Source Project: jdk8u60   Source File: T7042566.java    License: 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 25
Source Project: openjdk-jdk9   Source File: T7142086.java    License: GNU General Public License v2.0 5 votes vote down vote up
void run(List<JavaFileObject> sources) throws Exception {
    DiagnosticChecker dc = new DiagnosticChecker();
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        JavacTask ct = (JavacTask)comp.getTask(null, fm, dc,
                null, null, sources);
        ct.analyze();
    }
}
 
Example 26
Source Project: Bats   Source File: JDKClassCompiler.java    License: Apache License 2.0 5 votes vote down vote up
public static JDKClassCompiler newInstance(ClassLoader classLoader, boolean debug) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  if (compiler == null) {
    throw new RuntimeException("JDK Java compiler not available - probably you're running Drill with a JRE and not a JDK");
  }
  return new JDKClassCompiler(compiler, classLoader, debug);
}
 
Example 27
Source Project: Bats   Source File: JDKClassCompiler.java    License: Apache License 2.0 5 votes vote down vote up
private JDKClassCompiler(JavaCompiler compiler, ClassLoader classLoader, boolean debug) {
  super(debug);
  this.compiler = compiler;
  this.listener = new DrillDiagnosticListener();
  this.fileManager = new DrillJavaFileManager(compiler.getStandardFileManager(listener, null, Charsets.UTF_8), classLoader);
  this.compilerOptions = Lists.newArrayList(this.debug ? "-g:source,lines,vars" : "-g:none");
}
 
Example 28
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        int count = 0;
        for (SourceKind sk1 : SourceKind.values()) {
            for (SourceKind sk2 : SourceKind.values()) {
                for (TestKind tk : TestKind.values()) {
                    for (ClientKind ck : ClientKind.values()) {
                        new TestCircularClassfile("sub_"+count++, sk1, sk2, tk, ck).check(comp, fm);
                    }
                }
            }
        }
    }
}
 
Example 29
Source Project: chaosblade-exec-jvm   Source File: JavaCodeScriptEngine.java    License: Apache License 2.0 5 votes vote down vote up
private Class compileClass(ClassLoader classLoader, String className, String scriptId, String content) {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    if (javaCompiler == null) {
        throw new ScriptException("Not found system java compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaFileObject javaFileObject = new InputStringJavaFileObject(className, content);
    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(null, null, CHARSET_UTF8);
    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(classLoader, standardFileManager);
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(null, fileManager, diagnostics, null, null,
        Arrays.asList(javaFileObject));
    if (Boolean.TRUE.equals(compilationTask.call())) {
        try {
            return new CompiledClassLoader(classLoader, fileManager.getOutputs()).loadClass(className);
        } catch (Exception ce) {
            throw convertToScriptException("compile class failed:" + className, scriptId, ce);
        }
    } else {
        StringBuilder reporter = new StringBuilder(1024);
        reporter.append("Compilation failed.\n");
        try {
            generateDiagnosticReport(diagnostics, reporter);
        } catch (IOException e) {
            reporter.append("io exception:" + e.getMessage());
        }
        throw new ScriptException(reporter.toString());
    }
}
 
Example 30
Source Project: TencentKona-8   Source File: T7093325.java    License: 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);
}