import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * javax by Stefan Reich (www.superinformatiker.de, info@superinformatiker.de) * * jaxax compiles and runs a bunch of Java sources in one step. * * Syntax: * javax (searches for sources in current dir) * javax srcdir (searches in given directory) * * Main class must be called "main" in default package. * * Requirements: * Java 6 or higher - JDK (javac) must be in path * * Limitations: * Linux only, right now (invokes bash to call javac) * Can't pass arguments to invoked program yet (would be easy to add) * * TODO: delete .class files at program end */ public class x1 { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { File srcDir = new File(args.length == 0 ? "." : args[0]); List sources = new ArrayList(); System.out.println("Scanning for sources in " + srcDir.getPath()); scanForSources(srcDir, sources); if (sources.isEmpty()) { System.out.println("No sources found"); return; } File optionsFile = File.createTempFile("javax", ""); File classesDir = new File(System.getProperty("user.home"), ".javax/" + System.currentTimeMillis()); System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); String options = "-d " + bashQuote(classesDir.getPath()); writeOptions(sources, optionsFile, options); classesDir.mkdirs(); invokeJavac(optionsFile); System.out.println("Running program (class main.java)\n"); runProgram(classesDir); } private static void runProgram(File classesDir) throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { URLClassLoader classLoader = new URLClassLoader(new URL[]{classesDir.toURI().toURL()}); Class mainClass = classLoader.loadClass("main"); Method main = mainClass.getMethod("main", String[].class); main.invoke(null, (Object) new String[0]); } private static void invokeJavac(File optionsFile) throws IOException { String javacOutput = backtick("javac " + bashQuote("@" + optionsFile.getPath())); System.out.println(javacOutput); } private static void writeOptions(List sources, File sourcesFile, String moreOptions) throws IOException { FileWriter writer = new FileWriter(sourcesFile); for (File source : sources) writer.write(bashQuote(source.getPath()) + " "); writer.write(moreOptions); writer.close(); } private static void scanForSources(File source, List sources) { if (source.isFile() && source.getName().endsWith(".java")) sources.add(source); else if (source.isDirectory()) { File[] files = source.listFiles(); for (File file : files) scanForSources(file, sources); } } public static String backtick(String cmd) throws IOException { File outFile = File.createTempFile("_backtick", ""); File scriptFile = File.createTempFile("_backtick", ""); String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; //Log.info("[Backtick] " + command); try { saveTextFile(scriptFile.getPath(), command); String[] command2 = {"/bin/bash", scriptFile.getPath() }; Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } int value = process.exitValue(); //Log.info("exit value: " + value); return loadTextFile(outFile.getPath(), ""); } finally { scriptFile.delete(); } } /** possoibly improvable */ public static String bashQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } public final static String charsetForTextFiles = "UTF8"; /** writes safely (to temp file, then rename) */ public static void saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } public static String loadTextFile(String fileName, String defaultContents) throws IOException { if (!new File(fileName).exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); return loadTextFile(inputStreamReader); } public static String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) builder.append(line).append('\n'); } finally { reader.close(); } return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1); } }