/** * Compiles the input file and generates the output class file. * * @param fullFilePath input .java file path. * @return class file path. */ public static String compileFile(File fullFilePath) throws IOException { Preconditions.checkArgument(fullFilePath != null && fullFilePath.isFile()); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); Preconditions.checkNotNull(compiler); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(fullFilePath)); List<String> args = Arrays.asList("-Xlint:none"); boolean result = compiler.getTask(null, fileManager, diagnostics, args, null, compilationUnit).call(); String msg = ""; if (!result) { for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { msg += String.format( "Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getMessage(null)); } tracer.err(msg); } fileManager.close(); return msg; }
public static Map<Lang, Result> convertFromFiles( ClassLoader loader, List<Lang> lang, String file, String fqn, String method) throws Exception { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager manager = javac.getStandardFileManager(diagnostics, locale, charset); Iterable<? extends JavaFileObject> fileObjects = manager.getJavaFileObjects(file); StringWriter out = new StringWriter(); JavaCompiler.CompilationTask task = javac.getTask( out, manager, diagnostics, Collections.<String>emptyList(), Collections.<String>emptyList(), fileObjects); task.setLocale(locale); ConvertingProcessor processor = new ConvertingProcessor(lang, fqn, method); task.setProcessors(Collections.<Processor>singletonList(processor)); if (task.call()) { return processor.getResults(); } else { StringWriter message = new StringWriter(); PrintWriter writer = new PrintWriter(message); writer.append("Compilation of ").append(file).println(" failed:"); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { writer.append(diagnostic.getMessage(locale)); } writer.println("console:"); writer.append(out.getBuffer()); throw new Exception(message.toString()); } }
private void compile(final File f) throws IOException { // set up compiler final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f)); // compile generated source // (switch off annotation processing: no need to create Log4j2Plugins.dat) final List<String> options = Arrays.asList("-proc:none"); compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call(); // check we don't have any compilation errors final List<String> errors = new ArrayList<String>(); for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { errors.add( String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault()))); } } fileManager.close(); assertTrue(errors.toString(), errors.isEmpty()); }
/** * エミッターに追加された結果を元にコンパイルを実行する。 * * @return 結果をロードするためのローダー */ protected ClassLoader start() { List<Diagnostic<? extends JavaFileObject>> diagnostics = doCompile(); for (Diagnostic<?> d : diagnostics) { if (d.getKind() != Diagnostic.Kind.NOTE) { throw new AssertionError(diagnostics); } } return javaCompiler.getClassLoader(); }
public void report(Diagnostic<? extends S> diagnostic) { String out = String.format( "Kind: %1$-6s\r\nLine: %2$-6s\r\nColumn: %3$-6s\r\nMessage: %4$-6s\r\nCode:\r\n%5$-6s\r\n", diagnostic.getKind(), diagnostic.getLineNumber(), diagnostic.getColumnNumber(), diagnostic.getMessage(Locale.CHINA), ((JITCompiler.JavaSourceForString) diagnostic.getSource()).getCode()); System.out.println(out); }
public void report(Diagnostic<? extends S> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.WARNING) { warnings.add(diagnostic); count++; buffer.append(diagnostic.getMessage(Locale.getDefault())); buffer.append("\n"); } else if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { count++; buffer.append(diagnostic.getMessage(Locale.getDefault())); buffer.append("\n"); System.out.println(buffer.toString()); } }
private String getFailedCompilationMessage() { StringBuilder builder = new StringBuilder(); builder.append("Build failed unexpectedly"); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { builder.append( String.format( "\t%s line %d column %d: %s", diagnostic.getKind().toString(), diagnostic.getLineNumber(), diagnostic.getColumnNumber(), diagnostic.getMessage(Locale.ENGLISH))); } return builder.toString(); }
/** * Compiles the source code using the systems java compiler * * @param source * @return true -> compiling worked flawlessly */ private static String compile(JavaFileObject... source) { final ArrayList<String> options = new ArrayList<String>(); if (classpath != null) { options.add("-classpath"); options.add(System.getProperty("java.class.path") + classpath); } if (outputdir != null) { options.add("-d"); options.add(outputdir); } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); /** * Retrieving the standard file manager from compiler object, which is used to provide basic * building block for customizing how a compiler reads and writes to files. * * <p>The same file manager can be reopened for another compiler task. Thus we reduce the * overhead of scanning through file system and jar files each time */ StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null); final JavaCompiler.CompilationTask task = compiler.getTask(null, stdFileManager, diagnostics, options, null, Arrays.asList(source)); boolean result = task.call(); String error = null; if (!result) { error = "Compilation failed, see log for details"; for (@SuppressWarnings("rawtypes") Diagnostic diagnostic : diagnostics.getDiagnostics()) { Logger.getInstance() .log( "de.~.vm.Javac.compile(JavaFileObject...)", Logger.DEBUG, "Error on line %d in %s" + diagnostic.getLineNumber() + diagnostic); } } try { stdFileManager.close(); } catch (IOException e) { e.printStackTrace(); } return error; }
@Override public JsonElement getContent() { final JsonObject obj = new JsonObject(); obj.add(diagnostic.getKind().name(), new JsonPrimitive(getErrorToken())); return obj; }
/** * Test that the ijar tool preserves private nested classes as they may be exposed through public * API. This test relies on an interface jar provided through the build rule * :interface_ijar_testlib and the Java source file PrivateNestedClass.java. */ @Test public void testDeprecatedParts() throws IOException { if (!makeCompilationTask("third_party/ijar/test/UseDeprecatedParts.java").call()) { fail(getFailedCompilationMessage()); } int deprecatedWarningCount = 0; for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { if ((diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING) && // Java 6: (diagnostic.getMessage(Locale.ENGLISH).startsWith("[deprecation]") || // Java 7: diagnostic.getMessage(Locale.ENGLISH).contains("has been deprecated"))) { deprecatedWarningCount++; } } assertEquals(16, deprecatedWarningCount); }
public static Set<TestDiagnostic> fromJavaxDiagnosticList( List<Diagnostic<? extends JavaFileObject>> javaxDiagnostics, boolean noMsgText) { Set<TestDiagnostic> diagnostics = new LinkedHashSet<>(javaxDiagnostics.size()); for (Diagnostic<? extends JavaFileObject> diagnostic : javaxDiagnostics) { // See TestDiagnosticUtils as to why we use diagnostic.toString rather // than convert from the diagnostic itself final String diagnosticString = diagnostic.toString(); // suppress Xlint warnings if (diagnosticString.contains("uses unchecked or unsafe operations.") || diagnosticString.contains("Recompile with -Xlint:unchecked for details.") || diagnosticString.endsWith(" declares unsafe vararg methods.") || diagnosticString.contains("Recompile with -Xlint:varargs for details.")) continue; diagnostics.add(TestDiagnosticUtils.fromJavaxToolsDiagnostic(diagnosticString, noMsgText)); } return diagnostics; }
public void report(Diagnostic message) { if (!(message instanceof DiagnosticSourceUnwrapper)) { throw new AssertionError("Wrapped diagnostic expected!"); } String actual = message.toString(); JCDiagnostic jd = (JCDiagnostic) ((DiagnosticSourceUnwrapper) message).d; String expected = jd.toString(); if (!actual.equals(expected)) { throw new AssertionError("expected = " + expected + "\nfound = " + actual); } }
@Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { String msg = "[DIAGNOSTIC/" + className + "]: " + diagnostic.getMessage(null); Kind kind = diagnostic.getKind(); if ((firstMessage.length() == 0) || (kind == Kind.ERROR && firstMessageKind != Kind.ERROR)) { firstMessage = msg; firstMessageKind = kind; } switch (diagnostic.getKind()) { case ERROR: log.error(msg); break; case WARNING: case MANDATORY_WARNING: log.warn(msg); break; default: log.error(msg); break; } }
private void expectDiagnostic( Kind kind, String message, @Nullable String source, long start, long end, long col) throws IOException { expect(diagnostic.getKind()).andReturn(kind); expect(diagnostic.getMessage(EasyMock.<Locale>notNull())).andReturn(message); expect(diagnostic.getSource()).andReturn(file).anyTimes(); expect(diagnostic.getStartPosition()).andReturn(start).anyTimes(); expect(diagnostic.getEndPosition()).andReturn(end).anyTimes(); expect(diagnostic.getColumnNumber()).andReturn(col).anyTimes(); expect(file.getCharContent(anyBoolean())).andReturn(source).anyTimes(); }
public void report(Diagnostic<? extends JavaFileObject> diagnostic) { final CompilerMessage.Kind kind; switch (diagnostic.getKind()) { case ERROR: kind = BuildMessage.Kind.ERROR; myErrorCount++; break; case MANDATORY_WARNING: case WARNING: case NOTE: kind = BuildMessage.Kind.WARNING; myWarningCount++; break; default: kind = BuildMessage.Kind.INFO; } File sourceFile = null; try { // for eclipse compiler just an attempt to call getSource() may lead to an NPE, // so calling this method under try/catch to avoid induced compiler errors final JavaFileObject source = diagnostic.getSource(); sourceFile = source != null ? Utils.convertToFile(source.toUri()) : null; } catch (Exception e) { LOG.info(e); } final String srcPath = sourceFile != null ? FileUtil.toSystemIndependentName(sourceFile.getPath()) : null; String message = diagnostic.getMessage(Locale.US); if (Utils.IS_TEST_MODE) { LOG.info(message); } myContext.processMessage( new CompilerMessage( BUILDER_NAME, kind, message, srcPath, diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getPosition(), diagnostic.getLineNumber(), diagnostic.getColumnNumber())); }
@NotNull private static String errorsToString( @NotNull DiagnosticCollector<JavaFileObject> diagnosticCollector, boolean humanReadable) { StringBuilder builder = new StringBuilder(); for (javax.tools.Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) { if (diagnostic.getKind() != javax.tools.Diagnostic.Kind.ERROR) continue; if (humanReadable) { builder.append(diagnostic).append("\n"); } else { builder .append(diagnostic.getSource().getName()) .append(":") .append(diagnostic.getLineNumber()) .append(":") .append(diagnostic.getColumnNumber()) .append(":") .append(diagnostic.getCode()) .append("\n"); } } return builder.toString(); }
private void compile(JavaCompiler compiler, JarOutputStream jar) throws IOException { assert compiler != null; assert jar != null; DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); VolatileClassOutputManager fileManager = new VolatileClassOutputManager( compiler.getStandardFileManager(diagnostics, Locale.getDefault(), CHARSET)); try { List<String> arguments = new ArrayList<String>(); Collections.addAll(arguments, "-source", "1.6"); Collections.addAll(arguments, "-target", "1.6"); Collections.addAll(arguments, "-encoding", CHARSET.name()); StringWriter errors = new StringWriter(); PrintWriter pw = new PrintWriter(errors); CompilationTask task = compiler.getTask( pw, fileManager, diagnostics, arguments, Collections.<String>emptyList(), emitter.getEmitted()); Boolean successed = task.call(); pw.close(); for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) { switch (diagnostic.getKind()) { case ERROR: case MANDATORY_WARNING: getEnvironment().error(diagnostic.getMessage(null)); break; case WARNING: LOG.warn(diagnostic.getMessage(null)); break; default: LOG.info(diagnostic.getMessage(null)); break; } } if (successed != Boolean.TRUE) { throw new IOException( MessageFormat.format( "{0}のコンパイルに失敗しました: {1}", getEnvironment().getTargetId(), errors.toString())); } for (VolatileResourceFile file : fileManager.getResources()) { addEntry(jar, file); } for (VolatileClassFile file : fileManager.getCompiled()) { addEntry(jar, file); } for (Map.Entry<String, byte[]> entry : contents.entrySet()) { addEntry(jar, entry.getKey(), entry.getValue()); } } finally { fileManager.close(); } }
public static void main(String... args) throws IOException, URISyntaxException { if (args.length != 1) throw new IllegalStateException("Must provide class name!"); String testContent = null; List<File> sourcePath = new ArrayList<>(); for (String sourcePaths : System.getProperty("test.src.path").split(":")) { sourcePath.add(new File(sourcePaths)); } JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null); for (File sp : sourcePath) { File inp = new File(sp, args[0]); if (inp.canRead()) { testContent = fm.getRegularFile(inp.toPath()).getCharContent(true).toString(); } } if (testContent == null) throw new IllegalStateException(); final List<Diagnostic<?>> diagnostics = new ArrayList<>(); DiagnosticListener<JavaFileObject> collectDiagnostics = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { diagnostics.add(diagnostic); } }; JavaFileObject testFile = new TestFO(new URI("mem://" + args[0]), testContent); JavacTask task = JavacTool.create() .getTask( null, new TestFM(fm), collectDiagnostics, STANDARD_PARAMS, null, Arrays.asList(testFile)); final Trees trees = Trees.instance(task); final CompilationUnitTree cut = task.parse().iterator().next(); task.analyze(); final List<int[]> declarationSpans = new ArrayList<>(); new TreeScanner<Void, Void>() { @Override public Void visitClass(ClassTree node, Void p) { handleDeclaration(node); return super.visitClass(node, p); } @Override public Void visitMethod(MethodTree node, Void p) { handleDeclaration(node); return super.visitMethod(node, p); } @Override public Void visitVariable(VariableTree node, Void p) { handleDeclaration(node); return super.visitVariable(node, p); } @Override public Void visitNewClass(NewClassTree node, Void p) { if (node.getClassBody() != null) { scan(node.getClassBody().getMembers(), null); } return null; } private void handleDeclaration(Tree node) { int endPos = (int) trees.getSourcePositions().getEndPosition(cut, node); if (endPos == (-1)) { if (node.getKind() == Tree.Kind.METHOD && (((JCMethodDecl) node).getModifiers().flags & Flags.GENERATEDCONSTR) != 0) { return; } throw new IllegalStateException(); } declarationSpans.add( new int[] {(int) trees.getSourcePositions().getStartPosition(cut, node), endPos}); } }.scan(cut, null); for (final int[] declarationSpan : declarationSpans) { final String suppressWarnings = "@SuppressWarnings({\"deprecation\", \"unchecked\", \"serial\", \"divzero\"})"; final String updatedContent = testContent.substring(0, declarationSpan[0]) + suppressWarnings + testContent.substring(declarationSpan[0]); final List<Diagnostic<?>> foundErrors = new ArrayList<>(diagnostics); DiagnosticListener<JavaFileObject> verifyDiagnostics = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { long adjustedPos = diagnostic.getPosition(); if (adjustedPos >= declarationSpan[0]) adjustedPos -= suppressWarnings.length(); if (declarationSpan[0] <= adjustedPos && adjustedPos <= declarationSpan[1]) { throw new IllegalStateException("unsuppressed: " + diagnostic.getMessage(null)); } boolean found = false; for (Iterator<Diagnostic<?>> it = foundErrors.iterator(); it.hasNext(); ) { Diagnostic<?> d = it.next(); if (d.getPosition() == adjustedPos && d.getCode().equals(diagnostic.getCode())) { it.remove(); found = true; break; } } if (!found) { throw new IllegalStateException( "diagnostic not originally reported: " + diagnostic.getMessage(null)); } } }; JavaFileObject updatedFile = new TestFO(new URI("mem://" + args[0]), updatedContent); JavacTask testTask = JavacTool.create() .getTask( null, new TestFM(fm), verifyDiagnostics, STANDARD_PARAMS, null, Arrays.asList(updatedFile)); testTask.analyze(); for (Diagnostic<?> d : foundErrors) { if (d.getPosition() < declarationSpan[0] || declarationSpan[1] < d.getPosition()) { throw new IllegalStateException("missing: " + d.getMessage(null)); } } } }
public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { errorFound = true; } }
public static void main(String[] args) throws Throwable { StringBuilder sb = new StringBuilder(64); sb.append("package tools.test.compile;\n"); sb.append("public class HelloWorld implements tools.test.InlineCompiler.DoStuff {\n"); sb.append(" public void doStuff() {\n"); sb.append( " System.out.println(\"print:\" + tools.Convert.toString(\"Hello world\"));\n"); sb.append(" }\n"); sb.append("}\n"); File helloWorldJava = new File("./tools/test/compile/HelloWorld.java"); // 注意这里的路径,和包名对应 2014-11-21 by 六三 if (helloWorldJava.getParentFile().exists() || helloWorldJava.getParentFile().mkdirs()) { // 写文件 Writer writer = null; try { writer = new FileWriter(helloWorldJava); writer.write(sb.toString()); writer.flush(); } finally { try { writer.close(); } catch (Exception e) {; } } } /** * Compilation Requirements * ******************************************************************************************** */ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); // This sets up the class path that the compiler will use. // I've added the .jar file that contains the DoStuff interface within in it... List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(System.getProperty("java.class.path") + ";"); Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /** Compilation Requirements * */ if (task.call()) { /** Load and execute * */ System.out.println("Yipe"); // Create a new custom class loader, pointing to the directory that contains the compiled // classes, this should point to the top of the package structure! URLClassLoader classLoader = new URLClassLoader(new URL[] {new File("./").toURI().toURL()}); // Load the class from the classloader by name.... Class<?> loadedClass = classLoader.loadClass("tools.test.compile.HelloWorld"); // Create a new instance... Object obj = loadedClass.newInstance(); // Santity check if (obj instanceof DoStuff) { // Cast to the DoStuff interface DoStuff stuffToDo = (DoStuff) obj; // Run it baby stuffToDo.doStuff(); } /** Load and execute * */ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format( "Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri()); } } fileManager.close(); }
public DiagnosticException(Diagnostic<? extends JavaFileObject> diagnostic) { super(diagnostic.toString()); }
private void markError( DiagnosticCollector<JavaFileObject> diagnosticsCollector, boolean markerCreation) { for (Diagnostic diagnostic : diagnosticsCollector.getDiagnostics()) { System.out.format("Error on line %d" + " -> ", diagnostic.getLineNumber(), diagnostic); System.out.println(diagnostic.getMessage(null) + "\n"); System.err.println("*** " + diagnostic.toString() + " *** " + diagnostic.getCode()); JavaFileObject source = (JavaFileObject) diagnostic.getSource(); String longFileName = source == null ? null : source.toUri().getPath(); // String shortFileName = source == null ? null : source.getName(); // System.out.println("Error in: " + longFileName); // Path path = new Path(longFileName); // IFile ifile = // ResourcesPlugin.getWorkspace().getRoot().getFile(path); if (diagnostic.getLineNumber() > -1) { File fileToOpen = new File(longFileName); if (fileToOpen.exists() && fileToOpen.isFile()) { final IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI()); Display display = PlatformUI.getWorkbench().getDisplay(); display.syncExec( new Runnable() { public void run() { try { IEditorPart part = IDE.openEditorOnFileStore(pag, fileStore); if (part != null) { IEditorInput input = part.getEditorInput(); ifile = ((IFileEditorInput) input).getFile(); // ... use activeProjectName } } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } else { // Do something if the file does not exist } } // System.out.format("Error on line %d in %s"+"\n", // diagnostic.getLineNumber(), diagnostic); if (markerCreation == true) { int lnr = (int) diagnostic.getLineNumber(); int startPos = (int) diagnostic.getStartPosition(); int stopPos = (int) diagnostic.getEndPosition(); if (ifile != null) { IMarker marker; try { marker = ifile.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.MESSAGE, diagnostic.getMessage(null)); marker.setAttribute(IMarker.LINE_NUMBER, lnr); // if (pos.offset != 0) { // System.out.println(startPos); // System.out.println(stopPos); marker.setAttribute(IMarker.CHAR_START, startPos); marker.setAttribute(IMarker.CHAR_END, stopPos - 1); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
/** * Compile the given files. * * @param files Source files to compile. * @param classPath Support jars or directories that should be on the classpath. If @code{null}, * the default is used. * @param sourcePath Location of additional sources to be compiled on-demand. If @code{null}, the * default is used. * @param destination Location (directory) for compiled classes. If @code{null}, the default * in-place location is used. * @param bootClassPath The bootclasspath (contains Java API jars or directories); should be * consistent with @code{sourceVersion} If @code{null}, the default is used. * @param sourceVersion The language version of the sources. Should be consistent * with @code{bootClassPath}. If @code{null}, the default is used. * @param showWarnings Whether compiler warnings should be shown or ignored. * @return Errors that occurred. If no errors, should be zero length (not null). */ public List<? extends DJError> compile( List<? extends File> files, List<? extends File> classPath, List<? extends File> sourcePath, File destination, List<? extends File> bootClassPath, String sourceVersion, boolean showWarnings) { debug.logStart("compile()"); debug.logValues( new String[] { "this", "files", "classPath", "sourcePath", "destination", "bootClassPath", "sourceVersion", "showWarnings" }, this, files, classPath, sourcePath, destination, bootClassPath, sourceVersion, showWarnings); Iterable<String> options = _createOptions( classPath, sourcePath, destination, bootClassPath, sourceVersion, showWarnings); LinkedList<DJError> errors = new LinkedList<DJError>(); // This is the class that javax.tools.ToolProvider.getSystemJavaCompiler() uses. // We create an instance of that class directly, bypassing ToolProvider, because ToolProvider // returns null // if DrJava is started with just the JRE, instead of with the JDK, even if tools.jar is later // made available // to the class loader. JavaCompiler compiler = null; try { compiler = (JavaCompiler) (Class.forName("com.sun.tools.javac.api.JavacTool").newInstance()); } catch (ClassNotFoundException e) { errors.addFirst(new DJError("Compile exception: " + e, false)); error.log(e); return errors; } catch (InstantiationException e) { errors.addFirst(new DJError("Compile exception: " + e, false)); error.log(e); return errors; } catch (IllegalAccessException e) { errors.addFirst(new DJError("Compile exception: " + e, false)); error.log(e); return errors; } /** Default FileManager provided by Context class */ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(files); try { System.err.println("Calling '" + compiler + "' with options " + options); compiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call(); for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) { Diagnostic.Kind dt = d.getKind(); boolean isWarning = false; // init required by javac switch (dt) { case OTHER: continue; // skip, do not record case NOTE: continue; // skip, do not record case MANDATORY_WARNING: isWarning = true; break; case WARNING: isWarning = true; break; case ERROR: isWarning = false; break; } /* The new Java 6.0 Diagnostic interface appears to be broken. The expression d.getSource().getName() returns a * non-existent path--the name of the test file (allocated as a TEMP file) appended to the source root for * DrJava--in GlobalModelCompileErrorsTest.testCompileFailsCorrectLineNumbers(). The expression * d.getSource().toUri().getPath() returns the correct result as does ((JCDiagnostic) d).getSourceName(). */ if (d.getSource() != null) { errors.add( new DJError( new File(d.getSource().toUri().getPath()), // d.getSource().getName() fails! ((int) d.getLineNumber()) - 1, // javac starts counting at 1 ((int) d.getColumnNumber()) - 1, d.getMessage(null), // null is the locale isWarning)); } else { errors.add(new DJError(d.getMessage(null), isWarning)); } } fileManager.close(); } catch (Throwable t) { // compiler threw an exception/error (typically out of memory error) errors.addFirst(new DJError("Compile exception: " + t, false)); error.log(t); } debug.logEnd("compile()"); return errors; }
public static void compile( String fileLocation, String code, String outputLocation, final PrintStream stream, ArrayList<CompilerListener> compilerListeners) { if (!CONFIG_DATA.containsKey("jdk.location") || !(new File(CONFIG_DATA.get("jdk.location")).isDirectory())) { FileBrowseDialog jdkSearch = new FileBrowseDialog( "Specify your JDK location.", "Location:", FileBrowseDialog.DIRECTORY); String jdkLoc = jdkSearch.open(); if (jdkLoc != null) { String location = FileUtils.removeEndingSlashes(jdkLoc.replace('\\', '/')); ArrowIDE.setConfigDataValue("jdk.location", location); } else { stream.println("You must specify a valid jdk to compile this program."); return; } } String fileName = FileUtils.getFileNameWithoutExtension(fileLocation); fileLocation = FileUtils.removeExtension(fileLocation); String projectLocation = FileUtils.getPrecedingPath(fileLocation, "/src/"); outputLocation = projectLocation + "/bin/"; try { outputLocation = FileUtils.getAbsolutePath(outputLocation) + "/"; } catch (IOException e2) { e2.printStackTrace(); } new File(outputLocation).mkdirs(); // fileName = fileName == null ? "" : fileName; // // JavacJavaCompilerSettings settings = new JavacJavaCompilerSettings(); // // org.apache.commons.jci.compilers.JavaCompiler compiler = new // JavacJavaCompiler(settings);//new JavaCompilerFactory().createCompiler("javac");//new // JavacJavaCompiler(settings); // //// org.apache.commons.jci.compilers.JavaCompiler compiler = new // JavaCompilerFactory().createCompiler("eclipse"); // // MemoryResourceReader mrr = new MemoryResourceReader(); // mrr.add("Test", code.getBytes()); // // MemoryResourceStore mrs = new MemoryResourceStore(); // // // CompilationResult result = compiler.compile(new String[] { fileName }, mrr, mrs); // // return result.getErrors().length + " "; /*Creating dynamic java source code file object*/ SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(fileName, code); JavaFileObject javaFileObjects[] = new JavaFileObject[] {fileObject}; /*Instantiating the java compiler*/ JavaCompiler compiler = getCompiler(); /** * Retrieving the standard file manager from compiler object, which is used to provide basic * building block for customizing how a compiler reads and writes to files. * * <p>The same file manager can be reopened for another compiler task. Thus we reduce the * overhead of scanning through file system and jar files each time */ StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null); /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/ Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects); String classpath = getClasspath(projectLocation); /*Prepare any compilation options to be used during compilation*/ // In this example, we are asking the compiler to place the output files under bin folder. String[] compileOptions = new String[] { // "-cp", classpath, "-cp", classpath, "-d", outputLocation }; Iterable<String> compilationOptions = Arrays.asList(compileOptions); // if (true)return; /*Create a diagnostic controller, which holds the compilation problems*/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); /*Create a compilation task from compiler by passing in the required input objects prepared above*/ CompilationTask compilerTask = compiler.getTask( null, stdFileManager, diagnostics, compilationOptions, null, compilationUnits); // Perform the compilation by calling the call method on compilerTask object. boolean status = compilerTask.call(); final StringBuilder error = new StringBuilder(); String outputFile = outputLocation + fileName + ".class"; final String outputFiles[] = new String[] {outputFile}; ArrayList<Diagnostic> ds = new ArrayList<Diagnostic>(); ArrayList<String> errors = new ArrayList<String>(); // If compilation error occurs if (!status) { /*Iterate through each compilation problem and print it*/ for (Diagnostic d : diagnostics.getDiagnostics()) { String err = d.getMessage(Locale.getDefault()); errors.add(String.format("Error on line %d: %s", d.getLineNumber(), err)); ds.add(d); } String strs[] = errors.toArray(new String[0]); for (String str : strs) { error.append(str); } Display.getDefault() .syncExec( new Runnable() { public void run() { if (stream != null) { stream.println(error.toString()); } } }); } CompileOutput output = null; CompileOutput outputs[] = new CompileOutput[ds.size() > 0 ? ds.size() : 1]; if (ds.size() > 0) { for (int i = 0; i < ds.size(); i++) { outputs[i] = new CompileOutput( (int) ds.get(i).getStartPosition(), (int) ds.get(i).getEndPosition(), (int) ds.get(i).getLineNumber(), status ? 0 : 1, errors.get(i)); } } else { outputs[0] = new CompileOutput(0, 0, 0, status ? 0 : 1, ""); } for (int i = compilerListeners.size() - 1; i >= 0; i--) { CompilerEvent event = new CompilerEvent(outputFiles, outputs, stream, fileLocation); compilerListeners.get(i).compiled(event); } try { stdFileManager.close(); } catch (IOException e) { e.printStackTrace(); } }
public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { errDiags = errDiags.append(diagnostic.getMessage(Locale.getDefault())); errorFound = true; } }
@Override public String getErrorToken() { return diagnostic.getMessage(Locale.ENGLISH); }
/** Compiles a single Java project. */ private static void performCompilation( final ResourceHandle sourceFolder, final ResourceHandle binaryFolder) { // delete binary files from previous builds binaryFolder.delete(); // obtain the standard file manager so we can include the boot classpath final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>(); final Locale locale = null; final StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticListener, locale, Charset.forName("utf-8")); final PlatformClasspathShieldFileManager wrappedStandardFileManager = new PlatformClasspathShieldFileManager(standardFileManager); // create library file managers JavaFileManager fileManager = wrappedStandardFileManager; try { if (Configuration.isDeployedFolderLayout()) { fileManager = new JarFileManager(new JarFile("jars/wicket-util-6.4.0.jar"), fileManager); fileManager = new JarFileManager(new JarFile("jars/wicket-core-6.4.0.jar"), fileManager); fileManager = new JarFileManager(new JarFile("jars/wicket-request-6.4.0.jar"), fileManager); fileManager = new JarFileManager(new JarFile("jars/wicket-extensions-6.4.0.jar"), fileManager); fileManager = new ClassFolderLibraryFileManager(new File("."), fileManager); } else { fileManager = new JarFileManager( new JarFile("../webapp.wicket/lib/java/wicket-util-6.4.0.jar"), fileManager); fileManager = new JarFileManager( new JarFile("../webapp.wicket/lib/java/wicket-core-6.4.0.jar"), fileManager); fileManager = new JarFileManager( new JarFile("../webapp.wicket/lib/java/wicket-request-6.4.0.jar"), fileManager); fileManager = new JarFileManager( new JarFile("../webapp.wicket/lib/java/wicket-extensions-6.4.0.jar"), fileManager); fileManager = new ClassFolderLibraryFileManager(new File("bin"), fileManager); fileManager = new ClassFolderLibraryFileManager(new File("../webapp.wicket/bin"), fileManager); fileManager = new ClassFolderLibraryFileManager(new File("../webapp.common/bin"), fileManager); } } catch (final IOException e) { throw new RuntimeException(e); } // fetch and wrap source code files as JavaFileObjects final MemoryFileManager memoryFileManager = new MemoryFileManager(fileManager); final List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>(); try { new RecursiveResourceOperation() { @Override protected void handleFile(ResourceHandle resourceHandle) { if ("java".equals(resourceHandle.getExtension())) { ResourcePath path = resourceHandle.getPath(); final String key = path.removeFirstSegments(sourceFolder.getPath().getSegmentCount(), true).toString(); final IMemoryJavaFileObject fileObject = new MemoryJavaFileObject(key, resourceHandle.readBinaryFile(true)); javaFiles.add(fileObject); memoryFileManager.getInputFiles().put(key, fileObject); } } }.handle(sourceFolder); } catch (final WorkspaceResourceNotFoundException e) { // src folder doesn't exist try { memoryFileManager.close(); } catch (final IOException e2) { } return; } // run the java compiler final CompilationTask task = compiler.getTask(null, memoryFileManager, diagnosticListener, null, null, javaFiles); /* final boolean success = */ task.call(); // save the class files for (final IMemoryFileObject fileObject : memoryFileManager.getOutputFiles().values()) { final ResourcePath path = new ResourcePath(binaryFolder.getPath().toString() + fileObject.getName()); final ResourceHandle handle = new ResourceHandle(binaryFolder.getWorkspaceId(), path); handle.writeFile(fileObject.getBinaryContent(), true, true); } // dispose of the file manager try { memoryFileManager.close(); } catch (final IOException e) { } // collect diagnostic messages per source file final List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticListener.getDiagnostics(); final Map<JavaFileObject, List<Diagnostic<? extends JavaFileObject>>> sourceFileToDiagnostics = new HashMap<JavaFileObject, List<Diagnostic<? extends JavaFileObject>>>(); for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) { final JavaFileObject currentFile = diagnostic.getSource(); List<Diagnostic<? extends JavaFileObject>> currentFileDiagnostics = sourceFileToDiagnostics.get(currentFile); if (currentFileDiagnostics == null) { currentFileDiagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>(); sourceFileToDiagnostics.put(currentFile, currentFileDiagnostics); } currentFileDiagnostics.add(diagnostic); } // these warnings will be ignored because they're nonsense final Set<String> ignoredWarnings = new HashSet<String>(); ignoredWarnings.add( "warning: [package-info] a package-info.java file has already been seen for package unnamed package"); ignoredWarnings.add( "[package-info] a package-info.java file has already been seen for package unnamed package"); // generate markers for the diagnostic messages sourceFolder.deleteMarkersRecursively(MarkerOrigin.JAVAC); for (final Map.Entry<JavaFileObject, List<Diagnostic<? extends JavaFileObject>>> fileEntry : sourceFileToDiagnostics.entrySet()) { ResourcePath filePath = new ResourcePath(fileEntry.getKey().getName()); ResourceHandle fileHandle = sourceFolder.get(filePath.withLeadingSeparator(false)); for (final Diagnostic<? extends JavaFileObject> diagnostic : fileEntry.getValue()) { // convert the diagnostic kind to a marker meaning (skip this diagnostic if the kind is // unknown) final Kind diagnosticKind = diagnostic.getKind(); MarkerMeaning meaning; if (diagnosticKind == Kind.ERROR) { meaning = MarkerMeaning.ERROR; } else if (diagnosticKind == Kind.WARNING || diagnosticKind == Kind.MANDATORY_WARNING) { meaning = MarkerMeaning.WARNING; } else { continue; } // skip erroneous markers final String messageText = diagnostic.getMessage(null); if (meaning == MarkerMeaning.WARNING && ignoredWarnings.contains(messageText)) { continue; } // create the marker final long line = diagnostic.getLineNumber(); final long column = diagnostic.getColumnNumber(); fileHandle.createMarker(MarkerOrigin.JAVAC, meaning, line, column, messageText); } } // copy non-Java files over to the output folder new RecursiveResourceOperation() { @Override protected void handleFile(ResourceHandle sourceFile) { if (!"java".equals(sourceFile.getExtension())) { ResourcePath relativePath = sourceFile .getPath() .removeFirstSegments(sourceFolder.getPath().getSegmentCount(), false); sourceFile.copyFileTo(binaryFolder.get(relativePath), true); } } }.handle(sourceFolder); }
private void assertCompilationResultIs( Multimap<Diagnostic.Kind, Pattern> expectedDiagnostics, List<String> testSourceCode) throws IOException { assertFalse(testSourceCode.isEmpty()); StringWriter compilerOut = new StringWriter(); List<String> options = ImmutableList.of( "-sourcepath", tmpDir.getPath(), "-d", tmpDir.getPath(), "-processor", AutoValueProcessor.class.getName(), "-Xlint"); javac.getTask(compilerOut, fileManager, diagnosticCollector, options, null, null); // This doesn't compile anything but communicates the paths to the JavaFileManager. // Convert the strings containing the source code of the test classes into files that we // can feed to the compiler. List<String> classNames = Lists.newArrayList(); List<JavaFileObject> sourceFiles = Lists.newArrayList(); for (String source : testSourceCode) { ClassName className = ClassName.extractFromSource(source); File dir = new File(tmpDir, className.sourceDirectoryName()); dir.mkdirs(); assertTrue(dir.isDirectory()); // True if we just made it, or it was already there. String sourceName = className.simpleName + ".java"; Files.write(source, new File(dir, sourceName), Charset.forName("UTF-8")); classNames.add(className.fullName()); JavaFileObject sourceFile = fileManager.getJavaFileForInput( StandardLocation.SOURCE_PATH, className.fullName(), Kind.SOURCE); sourceFiles.add(sourceFile); } assertEquals(classNames.size(), sourceFiles.size()); // Compile the classes. JavaCompiler.CompilationTask javacTask = javac.getTask( compilerOut, fileManager, diagnosticCollector, options, classNames, sourceFiles); boolean compiledOk = javacTask.call(); // Check that there were no compilation errors unless we were expecting there to be. // We ignore "notes", typically debugging output from the annotation processor // when that is enabled. Multimap<Diagnostic.Kind, String> diagnostics = ArrayListMultimap.create(); for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) { boolean ignore = (diagnostic.getKind() == Diagnostic.Kind.NOTE || (diagnostic.getKind() == Diagnostic.Kind.WARNING && diagnostic .getMessage(null) .contains("No processor claimed any of these annotations"))); if (!ignore) { diagnostics.put(diagnostic.getKind(), diagnostic.getMessage(null)); } } assertEquals(diagnostics.containsKey(Diagnostic.Kind.ERROR), !compiledOk); assertEquals( "Diagnostic kinds should match: " + diagnostics, expectedDiagnostics.keySet(), diagnostics.keySet()); for (Map.Entry<Diagnostic.Kind, Pattern> expectedDiagnostic : expectedDiagnostics.entries()) { Collection<String> actualDiagnostics = diagnostics.get(expectedDiagnostic.getKey()); assertTrue( "Diagnostics should contain " + expectedDiagnostic + ": " + diagnostics, Iterables.any(actualDiagnostics, Predicates.contains(expectedDiagnostic.getValue()))); } }