public void save(@NotNull final OutputFileObject fileObject) { if (JavaFileObject.Kind.CLASS != fileObject.getKind()) { // generated sources or resources must be saved synchronously, because some compilers (e.g. // eclipse) // may want to read generated text for further compilation try { final BinaryContent content = fileObject.getContent(); if (content != null) { content.saveToFile(fileObject.getFile()); } } catch (IOException e) { myContext.processMessage( new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, e.getMessage())); } } submitAsyncTask( myContext, new Runnable() { public void run() { try { for (ClassPostProcessor processor : ourClassProcessors) { processor.process(myContext, fileObject); } } finally { myDelegateOutputFileSink.save(fileObject); } } }); }
private File compileOne(Type type) { if (this.flags.contains(Flags.USECACHE)) { File dir = cache.get(type.getName()); if (dir != null) { return dir; } } List<JavaFileObject> files = new ArrayList<>(); SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src)); for (Type dep : type.typeDependencies()) { dep.generateAsDependency(accum, type.methodDependencies()); } type.generate(accum); JavacTask ct = (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files); File destDir = null; do { int value = counter.incrementAndGet(); destDir = new File(root, Integer.toString(value)); } while (destDir.exists()); if (this.flags.contains(Flags.VERBOSE)) { System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir); for (JavaFileObject jfo : files) { System.out.println(jfo.toString()); } } try { destDir.mkdirs(); this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir)); } catch (IOException e) { throw new RuntimeException( "IOException encountered during compilation: " + e.getMessage(), e); } Boolean result = ct.call(); if (result == Boolean.FALSE) { throw new RuntimeException("Compilation failure in " + type.getName() + " unit"); } if (this.flags.contains(Flags.USECACHE)) { File existing = cache.putIfAbsent(type.getName(), destDir); if (existing != null) { deleteDir(destDir); return existing; } } else { this.tempDirs.add(destDir); } return destDir; }
public static void writeFile(String dir, String fileName, String content) { try { File f = new File(dir, fileName); FileWriter w = new FileWriter(f); BufferedWriter bw = new BufferedWriter(w); bw.write(content); bw.close(); w.close(); } catch (IOException ioe) { System.err.println("can't write file"); ioe.printStackTrace(System.err); } }
public Class<?> findClass(String s) { try { byte[] bytes = loadClassData(s); return defineClass(s, bytes, 0, bytes.length); } catch (IOException ioe) { try { return super.loadClass(s); } catch (ClassNotFoundException ignore) { } ioe.printStackTrace(System.out); return null; } }
// Writes the program to a source file, compiles it, and runs it. private void compileAndRun(String fileName, String code) { // Exceptions here can pick and choose what font to use, as needed. // Exceptions thrown by the program, that cause the Playground to be unstable, should be in // blue. println("Deleting old temp files...", progErr); new File(fileName + ".java").delete(); new File(fileName + ".class").delete(); println("Creating source file...", progErr); file = new File(fileName + ".java"); println("Writing code to source file...", progErr); try { new FileWriter(file).append(code).close(); } catch (IOException i) { println("Had an IO Exception when trying to write the code. Stack trace:", error); i.printStackTrace(); return; // Exit on error } println("Compiling code...", progErr); // This should only ever be called if the JDK isn't installed. How you'd get here, I don't // know. if (compiler == null) { println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error); return; } // Tries to compile. Success code is 0, so if something goes wrong, do stuff. int result = compiler.run( null, null, null, file .getAbsolutePath()); // Possibly add a new outputstream to parse through the // compiler errors if (result != 0) { displayLog(); println("Failed to compile.", error); return; // Return on error } println("Code compiled with 0 errors.", progErr); println("Attempting to run code...", progErr); run(fileName); }
private static int findFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); try { return serverSocket.getLocalPort(); } finally { // workaround for linux : calling close() immediately after opening socket // may result that socket is not closed synchronized (serverSocket) { try { serverSocket.wait(1); } catch (Throwable ignored) { } } serverSocket.close(); } } catch (IOException e) { e.printStackTrace(System.err); return JavacServer.DEFAULT_SERVER_PORT; } }
// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (IOException e) { // JVM = builder.start() can throw this. println("IOException when running the JVM.", progErr); e.printStackTrace(); displayLog(); return; } }
/** * Wow! much faster than compiling outside of VM. Finicky though. Had rules called r and modulo. * Wouldn't compile til I changed to 'a'. */ protected boolean compile(String fileName) { String classpathOption = "-classpath"; String[] args = new String[] { "javac", "-d", tmpdir, classpathOption, tmpdir + pathSep + CLASSPATH, tmpdir + "/" + fileName }; String cmdLine = "javac" + " -d " + tmpdir + " " + classpathOption + " " + tmpdir + pathSep + CLASSPATH + " " + fileName; // System.out.println("compile: "+cmdLine); File f = new File(tmpdir, fileName); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // DiagnosticCollector<JavaFileObject> diagnostics = // new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f)); Iterable<String> compileOptions = Arrays.asList(new String[] {"-d", tmpdir, "-cp", tmpdir + pathSep + CLASSPATH}); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, compileOptions, null, compilationUnits); boolean ok = task.call(); try { fileManager.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } // List<String> errors = new ArrayList<String>(); // for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { // errors.add( // String.valueOf(diagnostic.getLineNumber())+ // ": " + diagnostic.getMessage(null)); // } // if ( errors.size()>0 ) { // System.err.println("compile stderr from: "+cmdLine); // System.err.println(errors); // return false; // } return ok; /* File outputDir = new File(tmpdir); try { Process process = Runtime.getRuntime().exec(args, null, outputDir); StreamVacuum stdout = new StreamVacuum(process.getInputStream()); StreamVacuum stderr = new StreamVacuum(process.getErrorStream()); stdout.start(); stderr.start(); process.waitFor(); stdout.join(); stderr.join(); if ( stdout.toString().length()>0 ) { System.err.println("compile stdout from: "+cmdLine); System.err.println(stdout); } if ( stderr.toString().length()>0 ) { System.err.println("compile stderr from: "+cmdLine); System.err.println(stderr); } int ret = process.exitValue(); return ret==0; } catch (Exception e) { System.err.println("can't exec compilation"); e.printStackTrace(System.err); return false; } */ }