Java Code Examples for javax.tools.ToolProvider#getSystemJavaCompiler()

The following examples show how to use javax.tools.ToolProvider#getSystemJavaCompiler() . 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: EagerInterfaceCompletionTest.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 {
    String SCRATCH_DIR = System.getProperty("user.dir");
    JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
    int n = 0;
    for (VersionKind versionKind : VersionKind.values()) {
        for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
            for (TestKind testKind : TestKind.values()) {
                for (ActionKind actionKind : ActionKind.values()) {
                    File testDir = new File(SCRATCH_DIR, "test"+n);
                    new EagerInterfaceCompletionTest(javacTool, testDir, versionKind,
                            hierarchyKind, testKind, actionKind).test();
                    n++;
                }
            }
        }
    }
    if (nerrors > 0) {
        throw new AssertionError("Some errors have been detected");
    }
}
 
Example 2
Source File: FunctionalInterfaceConversionTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();

    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc, null, null,
            Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile));
    try {
        ct.analyze();
    } catch (IOException ex) {
        throw new AssertionError("Test failing with cause", ex.getCause());
    }
    if (dc.errorFound == checkSamConversion()) {
        throw new AssertionError(samSourceFile + "\n\n" +
            pkgClassSourceFile + "\n\n" + clientSourceFile);
    }
}
 
Example 3
Source File: IgnoreIgnorableCharactersInInput.java    From TencentKona-8 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 4
Source File: SamConversionComboTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void test() throws Exception {
    System.out.println("\n====================================");
    System.out.println(fInterface + ", " +  context + ", " + lambdaKind + ", " + lambdaBody + ", " + returnValue);
    System.out.println(samSourceFile + "\n");
    String clientFileStr = clientSourceFile.toString();
    System.out.println(clientFileStr.substring(0, clientFileStr.indexOf("\n\n")));

    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    DiagnosticChecker dc = new DiagnosticChecker();
    JavacTask ct = (JavacTask)tool.getTask(null, null, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
    try {
        ct.analyze();
    } catch (Exception e) {
        throw new AssertionError("failing SAM source file \n" + samSourceFile + "\n\n" + "failing client source file \n"+ clientSourceFile);
    }
    if (dc.errorFound == checkSamConversion()) {
        throw new AssertionError(samSourceFile + "\n\n" + clientSourceFile);
    }
    count++;
}
 
Example 5
Source File: BadClassfile.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
Example 6
Source File: EndPositions.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 7
Source File: ParserTest.java    From TencentKona-8 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 (TypeQualifierArity arity : TypeQualifierArity.values()) {
            for (TypeArgumentKind tak1 : TypeArgumentKind.values()) {
                if (arity == TypeQualifierArity.ONE) {
                    new ParserTest(arity, tak1).run(comp, fm);
                    continue;
                }
                for (TypeArgumentKind tak2 : TypeArgumentKind.values()) {
                    if (arity == TypeQualifierArity.TWO) {
                        new ParserTest(arity, tak1, tak2).run(comp, fm);
                        continue;
                    }
                    for (TypeArgumentKind tak3 : TypeArgumentKind.values()) {
                        if (arity == TypeQualifierArity.THREE) {
                            new ParserTest(arity, tak1, tak2, tak3).run(comp, fm);
                            continue;
                        }
                        for (TypeArgumentKind tak4 : TypeArgumentKind.values()) {
                            new ParserTest(arity, tak1, tak2, tak3, tak4).run(comp, fm);
                        }
                    }
                }
            }
        }
    }
 
Example 8
Source File: Utils.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public static boolean executedByJDK() {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	if (compiler != null) {
		return true;
	}
	return false;
}
 
Example 9
Source File: ImplementationCacheTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    List<? extends JavaFileObject> files = Arrays.asList(new SourceFile());
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Context ctx = new Context();
    JavacFileManager.preRegister(ctx);
    checkImplementationCache(ct.analyze(), Types.instance(ctx));
}
 
Example 10
Source File: JavaCodeScriptEngine.java    From chaosblade-exec-jvm with 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 11
Source File: JavaToolUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Takes a list of files and compile these files into the working directory.
 *
 * @param files
 * @throws IOException
 */
public static void compileFiles(List<File> files) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.
            getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnit
                = fileManager.getJavaFileObjectsFromFiles(files);
        compiler.getTask(null, fileManager, null, null, null,
                compilationUnit).call();
    }
}
 
Example 12
Source File: T7116676.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testThroughFormatterFormat() throws IOException {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    DiagnosticChecker dc = new DiagnosticChecker("compiler.err.prob.found.req");
    JavacTask ct = (JavacTask)tool.getTask(null, null, dc, null, null, Arrays.asList(new JavaSource()));
    ct.analyze();
    DiagnosticFormatter<JCDiagnostic> formatter =
            Log.instance(((JavacTaskImpl) ct).getContext()).getDiagnosticFormatter();
    String msg = formatter.formatMessage(dc.diag, Locale.getDefault());
    //no redundant package qualifiers
    Assert.check(msg.indexOf("java.") == -1, msg);
}
 
Example 13
Source File: ClassLoaderUtils.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private static int compileClass(File sourceFile) {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	return compiler.run(null, null, null, "-proc:none", sourceFile.getPath());
}
 
Example 14
Source File: PojoSerializerUpgradeTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private static int compileClass(File sourceFile) {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	return compiler.run(null, null, null, "-proc:none", sourceFile.getPath());
}
 
Example 15
Source File: TestCompiler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public TestCompiler(TemporaryFolder temporaryFolder) throws IOException {
	this(ToolProvider.getSystemJavaCompiler(), temporaryFolder);
}
 
Example 16
Source File: TypeAnnotationsPretty.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
TypeAnnotationsPretty() {
    tool = ToolProvider.getSystemJavaCompiler();
}
 
Example 17
Source File: T8031967.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void runTestCase(boolean withErrors) throws IOException {
    StringBuilder code = new StringBuilder();

    code.append("public class Test {\n" +
                "    private void test() {\n" +
                "        GroupLayout l = new GroupLayout();\n" +
                "        l.setHorizontalGroup(\n");

    gen(code, depth);
    code.append("        );\n" +
                "    }\n");
    if (!withErrors) {
        code.append("    class GroupLayout {\n" +
                    "        ParallelGroup createParallelGroup() {return null;}\n" +
                    "        ParallelGroup createParallelGroup(int i) {return null;}\n" +
                    "        ParallelGroup createParallelGroup(int i, int j) {return null;}\n" +
                    "        void setHorizontalGroup(Group g) { }\n" +
                    "    }\n" +
                    "    \n" +
                    "    class Group {\n" +
                    "        Group addGroup(Group g) { return this; }\n" +
                    "        Group addGroup(int i, Group g) { return this; }\n" +
                    "        Group addGap(int i) { return this; }\n" +
                    "        Group addGap(long l) { return this; }\n" +
                    "        Group addGap(int i, int j) { return this; }\n" +
                    "        Group addComponent(Object c) { return this; }\n" +
                    "        Group addComponent(int i, Object c) { return this; }\n" +
                    "    }\n" +
                    "    class ParallelGroup extends Group {\n" +
                    "        Group addGroup(Group g) { return this; }\n" +
                    "        Group addGroup(int i, Group g) { return this; }\n" +
                    "        Group addGap(int i) { return this; }\n" +
                    "        Group addGap(int i, int j) { return this; }\n" +
                    "        Group addComponent(Object c) { return this; }\n" +
                    "        Group addComponent(int i, Object c) { return this; }\n" +
                    "    }\n");
    }

    code.append("}\n");

    JavaSource source = new JavaSource(code.toString());
    List<JavaSource> sourceList = Arrays.asList(source);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticListener<JavaFileObject> noErrors = (diagnostic) -> {
        throw new IllegalStateException("Should not produce errors: " + diagnostic);
    };
    JavacTask task = (JavacTask) compiler.getTask(null, null, withErrors ? null : noErrors,
            null, null, sourceList);

    task.analyze();
}
 
Example 18
Source File: TestClose2.java    From TencentKona-8 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 19
Source File: GeneratedClassLoader.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public GeneratedClassLoader() {
    javac = ToolProvider.getSystemJavaCompiler();
    nameBase = "TestSimpleClass";
}
 
Example 20
Source File: StringFoldingTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public StringFoldingTest() {
    tool = ToolProvider.getSystemJavaCompiler();
    source = new JavaSource();
}