Java Code Examples for javax.tools.DiagnosticCollector#getDiagnostics()
The following examples show how to use
javax.tools.DiagnosticCollector#getDiagnostics() .
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: ClassBodyWrapper.java From Quicksql with MIT License | 6 votes |
String buildCompilationReport(DiagnosticCollector<JavaFileObject> collector, List<String> options) { int count = 0; StringBuilder resultBuilder = new StringBuilder(); for (Object o : collector.getDiagnostics()) { Diagnostic<?> diagnostic = (Diagnostic) o; ++ count; JavaSourceFromString javaSource = (JavaSourceFromString) diagnostic.getSource(); resultBuilder.append(javaSource.getCharContent(false)).append("\n"); resultBuilder.append("Compiler options: ").append(options).append("\n\n"); resultBuilder.append(diagnostic.getKind()).append("|").append(diagnostic.getCode()) .append("\n"); resultBuilder.append("LINE:COLUMN ").append(diagnostic.getLineNumber()).append(":") .append(diagnostic.getColumnNumber()).append("\n") .append(diagnostic.getMessage(null)).append("\n\n"); } String diagnosticString = resultBuilder.toString(); String compilationErrorsOverview = count + " class(es) failed to compile"; return "Compilation error\n" + compilationErrorsOverview + "\n" + diagnosticString; }
Example 2
Source File: RetentionAnnoCombo.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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 3
Source File: JavacParserTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@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 4
Source File: EndPositions.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
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 5
Source File: TestGetElementReference.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
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 6
Source File: EndPositions.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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: Example.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@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 8
Source File: GetTask_DiagListenerTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * 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 9
Source File: GetTask_DiagListenerTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * 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 10
Source File: TreeEndPosTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
static void compile(JavaSource src) throws IOException { ByteArrayOutputStream ba = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(ba); File tempDir = new File("."); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector dc = new DiagnosticCollector(); JavaFileManager javaFileManager = getJavaFileManager(compiler, dc); List<String> options = new ArrayList<>(); options.add("-cp"); options.add(tempDir.getPath()); options.add("-d"); options.add(tempDir.getPath()); options.add("-XDshouldStopPolicy=GENERATE"); List<JavaFileObject> sources = new ArrayList<>(); sources.add(src); JavaCompiler.CompilationTask task = compiler.getTask(writer, javaFileManager, dc, options, null, sources); task.call(); for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) { long actualStart = diagnostic.getStartPosition(); long actualEnd = diagnostic.getEndPosition(); System.out.println("Source: " + src.source); System.out.println("Diagnostic: " + diagnostic); System.out.print("Start position: Expected: " + src.startPos); System.out.println(", Actual: " + actualStart); System.out.print("End position: Expected: " + src.endPos); System.out.println(", Actual: " + actualEnd); if (src.startPos != actualStart || src.endPos != actualEnd) { throw new RuntimeException("error: trees don't match"); } } }
Example 11
Source File: SchemaGenerator.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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 12
Source File: T6458823.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new RuntimeException("can't get javax.tools.JavaCompiler!"); } DiagnosticCollector<JavaFileObject> diagColl = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null); List<String> options = new ArrayList<String>(); options.add("-processor"); options.add("MyProcessor"); options.add("-proc:only"); List<File> files = new ArrayList<File>(); files.add(new File(T6458823.class.getResource("TestClass.java").toURI())); final CompilationTask task = compiler.getTask(null, fm, diagColl, options, null, fm.getJavaFileObjectsFromFiles(files)); task.call(); int diagCount = 0; for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) { if (diag.getKind() != Diagnostic.Kind.WARNING) { throw new AssertionError("Only warnings expected"); } System.out.println(diag); if (diag.getPosition() == Diagnostic.NOPOS) { throw new AssertionError("No position info in message"); } if (diag.getSource() == null) { throw new AssertionError("No source info in message"); } diagCount++; } if (diagCount != 2) { throw new AssertionError("unexpected number of warnings: " + diagCount + ", expected: 2"); } }
Example 13
Source File: T6458823.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new RuntimeException("can't get javax.tools.JavaCompiler!"); } DiagnosticCollector<JavaFileObject> diagColl = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null); List<String> options = new ArrayList<String>(); options.add("-processor"); options.add("MyProcessor"); options.add("-proc:only"); List<File> files = new ArrayList<File>(); files.add(new File(T6458823.class.getResource("TestClass.java").toURI())); final CompilationTask task = compiler.getTask(null, fm, diagColl, options, null, fm.getJavaFileObjectsFromFiles(files)); task.call(); int diagCount = 0; for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) { if (diag.getKind() != Diagnostic.Kind.WARNING) { throw new AssertionError("Only warnings expected"); } System.out.println(diag); if (diag.getPosition() == Diagnostic.NOPOS) { throw new AssertionError("No position info in message"); } if (diag.getSource() == null) { throw new AssertionError("No source info in message"); } diagCount++; } if (diagCount != 2) { throw new AssertionError("unexpected number of warnings: " + diagCount + ", expected: 2"); } }
Example 14
Source File: TestGetElementReference.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
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 15
Source File: DynamicCompiler.java From arthas with Apache License 2.0 | 4 votes |
public Map<String, Class<?>> build() { errors.clear(); warnings.clear(); JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader); DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null, compilationUnits); try { if (!compilationUnits.isEmpty()) { boolean result = task.call(); if (!result || collector.getDiagnostics().size() > 0) { for (Diagnostic<? extends JavaFileObject> diagnostic : collector.getDiagnostics()) { switch (diagnostic.getKind()) { case NOTE: case MANDATORY_WARNING: case WARNING: warnings.add(diagnostic); break; case OTHER: case ERROR: default: errors.add(diagnostic); break; } } if (!errors.isEmpty()) { throw new DynamicCompilerException("Compilation Error", errors); } } } return dynamicClassLoader.getClasses(); } catch (Throwable e) { throw new DynamicCompilerException(e, errors); } finally { compilationUnits.clear(); } }
Example 16
Source File: CodegenUtils.java From systemds with Apache License 2.0 | 4 votes |
private static Class<?> compileClassJavac(String name, String src) { try { //create working dir on demand if( _workingDir == null ) createWorkingDir(); //write input file (for debugging / classpath handling) File ftmp = new File(_workingDir+"/"+name.replace(".", "/")+".java"); if( !ftmp.getParentFile().exists() ) ftmp.getParentFile().mkdirs(); LocalFileUtils.writeTextFile(ftmp, src); //get system java compiler JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if( compiler == null ) throw new RuntimeException("Unable to obtain system java compiler."); //prepare file manager DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) { //prepare input source code Iterable<? extends JavaFileObject> sources = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(ftmp)); //prepare class path URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation(); String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath(); List<String> options = Arrays.asList("-classpath",classpath); //compile source code CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources); Boolean success = task.call(); //output diagnostics and error handling for(Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if( tmp.getKind()==Kind.ERROR ) System.err.println("ERROR: "+tmp.toString()); if( success == null || !success ) throw new RuntimeException("Failed to compile class "+name); //dynamically load compiled class try (URLClassLoader classLoader = new URLClassLoader( new URL[]{new File(_workingDir).toURI().toURL(), runDir}, CodegenUtils.class.getClassLoader())) { return classLoader.loadClass(name); } } } catch(Exception ex) { LOG.error("Failed to compile class "+name+": \n"+src); throw new DMLRuntimeException("Failed to compile class "+name+".", ex); } }
Example 17
Source File: CheckErrorsForSource7.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
private void run(String... args) throws IOException, URISyntaxException { //the first and only parameter must be the name of the file to be analyzed: if (args.length != 1) throw new IllegalStateException("Must provide source file!"); File testSrc = new File(System.getProperty("test.src")); File testFile = new File(testSrc, args[0]); if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source"); JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null); //gather spans of the @TA annotations into typeAnnotationSpans: JavacTask task = JavacTool.create().getTask(null, fm, null, Collections.<String>emptyList(), null, fm.getJavaFileObjects(testFile)); final Trees trees = Trees.instance(task); final CompilationUnitTree cut = task.parse().iterator().next(); final List<int[]> typeAnnotationSpans = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void visitAnnotation(AnnotationTree node, Void p) { if (node.getAnnotationType().getKind() == Kind.IDENTIFIER && ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) { int start = (int) trees.getSourcePositions().getStartPosition(cut, node); int end = (int) trees.getSourcePositions().getEndPosition(cut, node); typeAnnotationSpans.add(new int[] {start, end}); } return null; } }.scan(cut, null); //sort the spans in the reverse order, to simplify removing them from the source: Collections.sort(typeAnnotationSpans, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o2[0] - o1[0]; } }); //verify the errors are produce correctly: String originalSource = cut.getSourceFile().getCharContent(false).toString(); for (int[] toKeep : typeAnnotationSpans) { //prepare updated source code by removing all the annotations except the toKeep one: String updated = originalSource; for (int[] span : typeAnnotationSpans) { if (span == toKeep) continue; updated = updated.substring(0, span[0]) + updated.substring(span[1]); } //parse and verify: JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated); DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>(); JavacTask task2 = JavacTool.create().getTask(null, fm, errors, Arrays.asList("-source", "7"), null, Arrays.asList(updatedFile)); task2.parse(); boolean found = false; for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) { if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) { if (found) { throw new IllegalStateException("More than one expected error found."); } found = true; } } if (!found) throw new IllegalStateException("Did not produce proper errors for: " + updated); } }
Example 18
Source File: SortMethodsTest.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<JavaFileObject>(); final String cName = new String("ManyMethodsClass"); Vector<Long> results = new Vector<Long>(); for (int i = 6; i < 600000; i*=10) { String klass = createClass(cName, i); JavaMemoryFileObject file = new JavaMemoryFileObject(cName, klass); MemoryFileManager mfm = new MemoryFileManager(comp.getStandardFileManager(diags, null, null), file); CompilationTask task = comp.getTask(null, mfm, diags, null, null, Arrays.asList(file)); if (task.call()) { try { MemoryClassLoader mcl = new MemoryClassLoader(file); long start = System.nanoTime(); Class<? extends Object> c = Class.forName(cName, true, mcl); long end = System.nanoTime(); results.add(end - start); Method m = c.getDeclaredMethod("sayHello", new Class[0]); String ret = (String)m.invoke(null, new Object[0]); System.out.println(ret + " (loaded and resloved in " + (end - start) + "ns)"); } catch (Exception e) { System.err.println(e); } } else { System.out.println(klass); System.out.println(); for (Diagnostic diag : diags.getDiagnostics()) { System.out.println(diag.getCode() + "\n" + diag.getKind() + "\n" + diag.getPosition()); System.out.println(diag.getSource() + "\n" + diag.getMessage(null)); } } } long lastRatio = 0; for (int i = 2; i < results.size(); i++) { long normalized1 = Math.max(results.get(i-1) - results.get(0), 1); long normalized2 = Math.max(results.get(i) - results.get(0), 1); long ratio = normalized2/normalized1; lastRatio = ratio; System.out.println("10 x more methods requires " + ratio + " x more time"); } // The following is just vague estimation but seems to work on current x86_64 and sparcv9 machines if (lastRatio > 80) { throw new RuntimeException("ATTENTION: it seems that class loading needs quadratic time with regard to the number of class methods!!!"); } }
Example 19
Source File: CheckErrorsForSource7.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
private void run(String... args) throws IOException, URISyntaxException { //the first and only parameter must be the name of the file to be analyzed: if (args.length != 1) throw new IllegalStateException("Must provide source file!"); File testSrc = new File(System.getProperty("test.src")); File testFile = new File(testSrc, args[0]); if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source"); JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null); //gather spans of the @TA annotations into typeAnnotationSpans: JavacTask task = JavacTool.create().getTask(null, fm, null, Collections.<String>emptyList(), null, fm.getJavaFileObjects(testFile)); final Trees trees = Trees.instance(task); final CompilationUnitTree cut = task.parse().iterator().next(); final List<int[]> typeAnnotationSpans = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void visitAnnotation(AnnotationTree node, Void p) { if (node.getAnnotationType().getKind() == Kind.IDENTIFIER && ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) { int start = (int) trees.getSourcePositions().getStartPosition(cut, node); int end = (int) trees.getSourcePositions().getEndPosition(cut, node); typeAnnotationSpans.add(new int[] {start, end}); } return null; } }.scan(cut, null); //sort the spans in the reverse order, to simplify removing them from the source: Collections.sort(typeAnnotationSpans, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o2[0] - o1[0]; } }); //verify the errors are produce correctly: String originalSource = cut.getSourceFile().getCharContent(false).toString(); for (int[] toKeep : typeAnnotationSpans) { //prepare updated source code by removing all the annotations except the toKeep one: String updated = originalSource; for (int[] span : typeAnnotationSpans) { if (span == toKeep) continue; updated = updated.substring(0, span[0]) + updated.substring(span[1]); } //parse and verify: JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated); DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>(); JavacTask task2 = JavacTool.create().getTask(null, fm, errors, Arrays.asList("-source", "7"), null, Arrays.asList(updatedFile)); task2.parse(); boolean found = false; for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) { if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) { if (found) { throw new IllegalStateException("More than one expected error found."); } found = true; } } if (!found) throw new IllegalStateException("Did not produce proper errors for: " + updated); } }
Example 20
Source File: DynamicCompiler.java From arthas with Apache License 2.0 | 4 votes |
public Map<String, byte[]> buildByteCodes() { errors.clear(); warnings.clear(); JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader); DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null, compilationUnits); try { if (!compilationUnits.isEmpty()) { boolean result = task.call(); if (!result || collector.getDiagnostics().size() > 0) { for (Diagnostic<? extends JavaFileObject> diagnostic : collector.getDiagnostics()) { switch (diagnostic.getKind()) { case NOTE: case MANDATORY_WARNING: case WARNING: warnings.add(diagnostic); break; case OTHER: case ERROR: default: errors.add(diagnostic); break; } } if (!errors.isEmpty()) { throw new DynamicCompilerException("Compilation Error", errors); } } } return dynamicClassLoader.getByteCodes(); } catch (ClassFormatError e) { throw new DynamicCompilerException(e, errors); } finally { compilationUnits.clear(); } }