Java Code Examples for javax.tools.DiagnosticCollector

The following examples show how to use javax.tools.DiagnosticCollector. 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
Source Project: chaosblade-exec-jvm   Source File: JavaCodeScriptEngine.java    License: Apache License 2.0 6 votes vote down vote up
private static void generateDiagnosticReport(
    DiagnosticCollector<JavaFileObject> collector, StringBuilder reporter) throws IOException {
    List<Diagnostic<? extends JavaFileObject>> diagnostics = collector.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        JavaFileObject source = diagnostic.getSource();
        if (source != null) {
            reporter.append("Source: ").append(source.getName()).append('\n');
            reporter.append("Line ").append(diagnostic.getLineNumber()).append(": ")
                .append(diagnostic.getMessage(Locale.ENGLISH)).append('\n');
            CharSequence content = source.getCharContent(true);
            BufferedReader reader = new BufferedReader(new StringReader(content.toString()));
            int i = 1;
            String line;
            while ((line = reader.readLine()) != null) {
                reporter.append(i).append('\t').append(line).append('\n');
                ++i;
            }
        } else {
            reporter.append("Source: (null)\n");
            reporter.append("Line ").append(diagnostic.getLineNumber()).append(": ")
                .append(diagnostic.getMessage(Locale.ENGLISH)).append('\n');
        }
        reporter.append('\n');
    }
}
 
Example 2
Source Project: talos   Source File: ScriptCompiler.java    License: Apache License 2.0 6 votes vote down vote up
public SimpleReturnScript compile (String javaString) {
	JavaSourceFromString file = new JavaSourceFromString("SimpleRunIm", javaString);
	DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
	DynamicClassesFileManager manager = new DynamicClassesFileManager(compiler.getStandardFileManager(null, null, null));

	Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
	JavaCompiler.CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, compilationUnits);

	boolean success = task.call();
	for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
		System.err.print(String.format("Script compilation error: Line: %d - %s%n", diagnostic.getLineNumber(), diagnostic.getMessage(null)));
	}
	if (success) {
		try {

			System.out.println("Compiled");
			Class clazz = manager.loader.findClass("SimpleRunIm");

			return (SimpleReturnScript)ClassReflection.newInstance(clazz);
		} catch (ReflectionException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	return null;
}
 
Example 3
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 4
Source Project: TencentKona-8   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 5
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 6
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example 7
@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 8
private boolean getCompileResult(String contents, String className,
        boolean shouldCompile) throws Exception{

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok = compileCode(className, contents, diagnostics);

    String expectedErrKey = "compiler.err.invalid.repeatable" +
                                    ".annotation.retention";
    if (!shouldCompile && !ok) {
        for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
            if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
                d.getCode().contains(expectedErrKey))) {
                error("FAIL: Incorrect error given, expected = "
                        + expectedErrKey + ", Actual = " + d.getCode()
                        + " for className = " + className, contents);
            }
        }
    }

    return (shouldCompile  == ok);
}
 
Example 9
public void runTest() throws Exception {
    boolean ok = false;
    int testCtr = 0;

    // Create test source content
    for (TestCases className : TestCases.values()) {
        testCtr++;
        String contents = getContent(className.toString());

        // Compile the generated source file
        DiagnosticCollector<JavaFileObject> diagnostics =
                new DiagnosticCollector<JavaFileObject>();
        ok = compileCode(className.toString(), contents, diagnostics);
        if (!ok) {
            error("Class="+ className +" did not compile as expected", contents);
        } else {
            System.out.println("Test passed for className: " + className);
        }
    }

    System.out.println("Total number of tests run: " + testCtr);
    System.out.println("Total number of errors: " + errors);

    if (errors > 0)
        throw new Exception(errors + " errors found");
}
 
Example 10
private void verifyGeneratedCode(String sourceFile) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(Arrays.asList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(
                null, fileManager, diagnostics, null, null, compilationUnits);
        boolean result = task.call();

        System.out.println(diagnostics.getDiagnostics());
        assertTrue("Generated contract contains compile time error", result);
    }
}
 
Example 11
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 12
Source Project: jdk8u60   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 13
Source Project: jdk8u60   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 14
Source Project: jdk8u60   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example 15
Source Project: jdk8u60   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example 16
Source Project: jdk8u60   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
 
Example 17
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 18
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 19
Source Project: jdk8u60   Source File: ProfileOptionTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 20
Source Project: jdk8u60   Source File: RetentionAnnoCombo.java    License: GNU General Public License v2.0 6 votes vote down vote up
private boolean getCompileResult(String contents, String className,
        boolean shouldCompile) throws Exception{

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok = compileCode(className, contents, diagnostics);

    String expectedErrKey = "compiler.err.invalid.repeatable" +
                                    ".annotation.retention";
    if (!shouldCompile && !ok) {
        for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
            if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
                d.getCode().contains(expectedErrKey))) {
                error("FAIL: Incorrect error given, expected = "
                        + expectedErrKey + ", Actual = " + d.getCode()
                        + " for className = " + className, contents);
            }
        }
    }

    return (shouldCompile  == ok);
}
 
Example 21
Source Project: jdk8u60   Source File: SchemaGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            return task.call();
        }
 
Example 22
Source Project: openjdk-jdk8u   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 23
Source Project: learnjavabug   Source File: CustomJavaFileObjectAndFileManeger.java    License: MIT License 6 votes vote down vote up
public static void e() throws URISyntaxException {
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        ClassLoader classLoader = CustomJavaFileObjectAndFileManeger.class.getClassLoader();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
        StandardJavaFileManager standardJavaFileManager = javaCompiler
            .getStandardFileManager(diagnostics, Locale.CHINA, Charset.forName("utf-8"));
//        FileManagerImpl fileManager = new FileManagerImpl(standardJavaFileManager);
        StringBuilder stringBuilder = new StringBuilder()
            .append("class Main {")
            .append("   public static void main(String[] args) {")
            .append("       System.out.println(\"hello FFF!\");")
            .append("   }")
            .append("}");
        Iterable<? extends JavaFileObject> javaFileObjects = Arrays
            .asList(new JavaObjectFromString("Main", stringBuilder.toString()));

        // 编译任务
        CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, diagnostics, null, null, javaFileObjects);
        Boolean result = task.call();
        System.out.println(result);
        List list = diagnostics.getDiagnostics();
        for (Object object : list) {
            Diagnostic d = (Diagnostic) object;
            System.out.println(d.getMessage(Locale.ENGLISH));
        }
    }
 
Example 24
public static void main(String... args) throws IOException {
    File source = new File(System.getProperty("test.src", "."), "TestGetElementReferenceData.java").getAbsoluteFile();
    StandardJavaFileManager fm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    JavacTask ct = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, diagnostics, Arrays.asList("-Xjcov", "-source", "1.8"), null, fm.getJavaFileObjects(source));
    Trees trees = Trees.instance(ct);
    CompilationUnitTree cut = ct.parse().iterator().next();

    ct.analyze();

    for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
        if (d.getKind() == Diagnostic.Kind.ERROR) {
            throw new IllegalStateException("Should have been attributed without errors: " + diagnostics.getDiagnostics());
        }
    }

    Pattern p = Pattern.compile("/\\*getElement:(.*?)\\*/");
    Matcher m = p.matcher(cut.getSourceFile().getCharContent(false));

    while (m.find()) {
        TreePath tp = pathFor(trees, cut, m.start() - 1);
        Element found = trees.getElement(tp);
        String expected = m.group(1);
        String actual = found != null ? found.getKind() + ":" + symbolToString(found) : "<null>";

        if (!expected.equals(actual)) {
            throw new IllegalStateException("expected=" + expected + "; actual=" + actual);
        }
    }
}
 
Example 25
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            boolean res = task.call();
            //Print messages generated by compiler
            for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
                 System.err.println(d.toString());
            }
            return res;
        }
 
Example 26
Source Project: Quicksql   Source File: ClassBodyWrapper.java    License: MIT License 5 votes vote down vote up
public CompilationPackage compile(Map<String, String> classesToCompile, String extraJars)
    throws CompilerException {
    //modified classpath acquirement mode
    String belongingJarPath = ClassBodyWrapper.class.getProtectionDomain().getCodeSource()
        .getLocation()
        .getPath();

    List<String> options = Arrays
        .asList("-classpath", extraJars
            + System.getProperty("path.separator")
            + System.getProperty("java.class.path")
            + System.getProperty("path.separator")
            + belongingJarPath
        );

    List<JavaSourceFromString> strFiles = Lists.newArrayList();
    Iterator it = classesToCompile.keySet().iterator();

    String compilationReport;
    while (it.hasNext()) {
        String className = (String) it.next();
        compilationReport = classesToCompile.get(className);
        strFiles.add(new JavaSourceFromString(className, compilationReport));
    }

    JavaCompiler compiler = this.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> collector = this.getDiagnosticCollector();
    InMemoryClassManager manager = this.getClassManager(compiler);
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager,
        collector, options, null, strFiles);
    boolean status = task.call();
    if (status) {
        List<CompilationUnit> compilationUnits = manager.getAllClasses();
        return new CompilationPackage(compilationUnits);
    } else {
        compilationReport = this.buildCompilationReport(collector, options);
        throw new CompilerException(compilationReport);
    }
}
 
Example 27
private boolean getCompileResult(String className, boolean shouldCompile,
        Iterable<? extends JavaFileObject> files) throws Exception {

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok =  Helper.compileCode(diagnostics,files);
    if (!shouldCompile && !ok) {
        checkErrorKeys(className, diagnostics);
    }
    return (shouldCompile == ok);
}
 
Example 28
Source Project: yGuard   Source File: SimpleCompiler.java    License: MIT License 5 votes vote down vote up
private boolean compileCore( final Iterable sources, final JarOutputStream jos ) {
  final StringWriter compilerOut = new StringWriter();
  final DiagnosticCollector dc = new DiagnosticCollector();

  final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  final JavaCompiler.CompilationTask task = compiler.getTask(
          compilerOut,
          new InMemoryFileManager(jos, compiler, dc),
          dc,
          options,
          null,
          sources);
  final Boolean result = task.call();
  return result.booleanValue();
}
 
Example 29
Source Project: yGuard   Source File: SimpleCompiler.java    License: MIT License 5 votes vote down vote up
InMemoryFileManager(
        final JarOutputStream jos,
        final JavaCompiler compiler,
        final DiagnosticCollector dc
) {
  super(compiler.getStandardFileManager(dc, Locale.US, Charset.forName("UTF-8")));
  this.jos = jos;
}
 
Example 30
/**
 * Verify that a diagnostic listener can be specified.
 * Note that messages from the tool and doclet are imperfectly modeled
 * because the DocErrorReporter API works in terms of localized strings
 * and file:line positions. Therefore, messages reported via DocErrorReporter
 * and simply wrapped and passed through.
 */
@Test
public void testDiagListener() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", "package pkg; public error { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    DocumentationTask t = tool.getTask(null, fm, dc, null, null, files);
    if (t.call()) {
        throw new Exception("task succeeded unexpectedly");
    } else {
        List<String> diagCodes = new ArrayList<String>();
        for (Diagnostic d: dc.getDiagnostics()) {
            System.err.println(d);
            diagCodes.add(d.getCode());
        }
        List<String> expect = Arrays.asList(
                "javadoc.note.msg",         // Loading source file
                "compiler.err.expected3",   // class, interface, or enum expected
                "javadoc.note.msg");        // 1 error
        if (!diagCodes.equals(expect))
            throw new Exception("unexpected diagnostics occurred");
        System.err.println("diagnostics received as expected");
    }
}