javax.tools.DiagnosticCollector Java Examples

The following examples show how to use javax.tools.DiagnosticCollector. 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: SolidityFunctionWrapperGeneratorTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: T7190862.java    From TencentKona-8 with 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 #3
Source File: JavapTaskCtorFailWithNPE.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 File: SchemaGenerator.java    From jdk8u60 with 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 #5
Source File: ScriptCompiler.java    From talos with 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 #6
Source File: T7190862.java    From openjdk-jdk8u with 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 #7
Source File: CustomJavaFileObjectAndFileManeger.java    From learnjavabug with 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 #8
Source File: RetentionAnnoCombo.java    From jdk8u60 with 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 #9
Source File: TestCompileJARInClassPath.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source File: ProfileOptionTest.java    From jdk8u60 with 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 #12
Source File: ProfileOptionTest.java    From TencentKona-8 with 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 #13
Source File: TestCompileJARInClassPath.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 #14
Source File: JavaCodeScriptEngine.java    From chaosblade-exec-jvm with 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 #15
Source File: JavapTaskCtorFailWithNPE.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 #16
Source File: T7190862.java    From jdk8u60 with 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 #17
Source File: DocumentedAnnoCombo.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 #18
Source File: RetentionAnnoCombo.java    From TencentKona-8 with 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 #19
Source File: JavacParserTest.java    From jdk8u60 with 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 #20
Source File: JavacParserTest.java    From jdk8u60 with 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 #21
Source File: JavacParserTest.java    From jdk8u60 with 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 #22
Source File: JavacParserTest.java    From jdk8u60 with 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 #23
Source File: JavacParserTest.java    From openjdk-jdk8u with 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 #24
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 #25
Source File: SolidityFunctionWrapperGeneratorTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
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);
        assertTrue("Generated contract contains compile time error", task.call());
    }
}
 
Example #26
Source File: DynamicEngine.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public Object execute(String fullClassName, String javaCode, String method, Class<?>[] paramsCls,Object[] params) throws Exception {
      Object result = null;
      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
      ClassFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(diagnostics, null, null));
 
      List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>();
      jfiles.add(new CharSequenceJavaFileObject(fullClassName, javaCode));
 
      List<String> options = new ArrayList<String>();
      options.add("-encoding");
      options.add(Constants.CHARSET.toString());
      options.add("-classpath");
      options.add(this.classpath);
 
      JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, jfiles);
      boolean success = task.call();
 
      if (success) {
          JavaClassObject jco = fileManager.getJavaClassObject();
          DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(this.parentClassLoader);
          Class<?> clazz = dynamicClassLoader.loadClass(fullClassName,jco);
          result = invoke(clazz, method, paramsCls, params);
          
//        instance = clazz.newInstance();
	dynamicClassLoader.close();
      } else {
          StringBuilder error = new StringBuilder();
          for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
          	error.append(compilePrint(diagnostic));
          }
          throw new Exception(error.toString());
      }

      return result;
  }
 
Example #27
Source File: GetTask_DiagListenerTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example #28
Source File: InheritedAnnoCombo.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void runTest() throws Exception {
    int testCtr = 0;
    boolean ok = false;

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

        // Compile the generated code
        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 #29
Source File: TestGetElementReference.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 #30
Source File: InheritedAnnoCombo.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void runTest() throws Exception {
    int testCtr = 0;
    boolean ok = false;

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

        // Compile the generated code
        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");
}