Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

696
LINES

< > BotCompany Repo | #616 // x10.java (under development)

Java source code

1  
import java.io.*;
2  
import java.lang.reflect.Method;
3  
import java.net.URL;
4  
import java.net.URLClassLoader;
5  
import java.net.URLConnection;
6  
import java.security.MessageDigest;
7  
import java.security.NoSuchAlgorithmException;
8  
import java.util.*;
9  
import java.util.regex.Matcher;
10  
import java.util.regex.Pattern;
11  
12  
/**
13  
 Changes to v9:
14  
 -FASTER: Uses Eclipse compiler instead of javac if ecj-4.3.2.jar is in classpath
15  
 -FASTER: virtualized I/O for translators - no extra VM necessary.
16  
  should definitely work if you write your translators in normal ways.
17  
 -"run" command ("x10 run 606" is the same as just "x10 605".)
18  
 -"Loading http://..." messages moved to System.err
19  
  (so you can pipe the result of "list" into a file)
20  
 -Added a TODO
21  
22  
 Still Linux only. (Where are the Windows porters?)
23  
 */
24  
25  
public class x10 {
26  
  static final String version = "JavaX 10";
27  
28  
  static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
29  
  static boolean preferCached = false;
30  
  static List<String> mainTranslators = new ArrayList<String>();
31  
  private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
32  
  private static int processesStarted;
33  
34  
  public static void main(String[] args) throws Exception {
35  
    File ioBaseDir = new File("."), inputDir = null, outputDir = null;
36  
    String src = ".";
37  
    for (int i = 0; i < args.length; i++) {
38  
      String arg = args[i];
39  
      if (arg.equals("-v") || arg.equals("-verbose"))
40  
        verbose = true;
41  
      else if (arg.equals("-finderror"))
42  
        verbose = true;
43  
      else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
44  
        preferCached = true;
45  
      else if (arg.equals("-novirt"))
46  
        virtualizeTranslators = false;
47  
      else if (arg.equals("translate"))
48  
        translate = true;
49  
      else if (arg.equals("list"))
50  
        list = true;
51  
      else if (arg.equals("run")) {
52  
        // it's the default command anyway
53  
      } else if (arg.startsWith("input="))
54  
        inputDir = new File(arg.substring(6));
55  
      else if (arg.startsWith("output="))
56  
        outputDir = new File(arg.substring(7));
57  
      else if (arg.equals("with"))
58  
        mainTranslators.add(args[++i]);
59  
      else
60  
        src = arg;
61  
    }
62  
63  
    if (virtualizeTranslators && !preferCached)
64  
      initDiskSnippetCache(TempDirMaker_make());
65  
66  
    if (inputDir != null) {
67  
      ioBaseDir = TempDirMaker_make();
68  
      System.out.println("Taking input from: " + inputDir.getAbsolutePath());
69  
      System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
70  
      copyInput(inputDir, new File(ioBaseDir, "input"));
71  
    }
72  
73  
    javax4(src, ioBaseDir, translate, list);
74  
75  
    if (outputDir != null) {
76  
      copyInput(new File(ioBaseDir, "output"), outputDir);
77  
      System.out.println("Output copied to: " + outputDir.getAbsolutePath());
78  
    }
79  
80  
    if (verbose)
81  
      System.out.println("Processes started: " + processesStarted);
82  
  }
83  
84  
  public static void javax4(String src, File ioDir, boolean translate, boolean list) throws Exception {
85  
    File srcDir;
86  
    if (isSnippetID(src))
87  
      srcDir = loadSnippetAsMainJava(src);
88  
    else {
89  
      srcDir = new File(src);
90  
      if (!new File(srcDir, "main.java").exists()) {
91  
        System.out.println("This is " + version  + ".\n" +
92  
          "No main.java found, exiting");
93  
        return;
94  
      }
95  
    }
96  
97  
    // translate
98  
99  
    File X = srcDir;
100  
    X = applyTranslators(X, mainTranslators);
101  
    X = defaultTranslate(X);
102  
103  
    // list or run
104  
105  
    if (translate)
106  
      System.out.println("Program translated to: " + X.getAbsolutePath());
107  
    else if (list)
108  
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
109  
    else
110  
      javax2(X, ioDir, false, false);
111  
  }
112  
113  
  private static File defaultTranslate(File x) throws Exception {
114  
    x = luaPrintToJavaPrint(x);
115  
    x = autoTranslate(x);
116  
    return x;
117  
  }
118  
119  
  private static File autoTranslate(File x) throws Exception {
120  
    String main = loadTextFile(new File(x, "main.java").getPath(), null);
121  
    List<String> lines = toLines(main);
122  
    List<String> translators = findTranslators(lines);
123  
    if (translators.isEmpty())
124  
      return x;
125  
126  
    main = fromLines(lines);
127  
    File newDir = TempDirMaker_make();
128  
    saveTextFile(new File(newDir, "main.java").getPath(), main);
129  
    return applyTranslators(newDir, translators);
130  
  }
131  
132  
  private static List<String> findTranslators(List<String> lines) {
133  
    List<String> translators = new ArrayList<String>();
134  
    Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
135  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
136  
      String line = iterator.next();
137  
      line = line.trim();
138  
      Matcher matcher = pattern.matcher(line);
139  
      if (matcher.find()) {
140  
        translators.addAll(Arrays.asList(matcher.group(1).split("[ \t]+")));
141  
        iterator.remove();
142  
      }
143  
    }
144  
    return translators;
145  
  }
146  
147  
  public static List<String> toLines(String s) {
148  
    List<String> lines = new ArrayList<String>();
149  
    int start = 0;
150  
    while (true) {
151  
      int i = toLines_nextLineBreak(s, start);
152  
      if (i < 0) {
153  
        if (s.length() > start) lines.add(s.substring(start));
154  
        break;
155  
      }
156  
157  
      lines.add(s.substring(start, i));
158  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
159  
        i += 2;
160  
      else
161  
        ++i;
162  
163  
      start = i;
164  
    }
165  
    return lines;
166  
  }
167  
168  
  private static int toLines_nextLineBreak(String s, int start) {
169  
    for (int i = start; i < s.length(); i++) {
170  
      char c = s.charAt(i);
171  
      if (c == '\r' || c == '\n')
172  
        return i;
173  
    }
174  
    return -1;
175  
  }
176  
177  
  public static String fromLines(List<String> lines) {
178  
    StringBuilder buf = new StringBuilder();
179  
    for (String line : lines) {
180  
      buf.append(line).append('\n');
181  
    }
182  
    return buf.toString();
183  
  }
184  
185  
  private static File applyTranslators(File x, List<String> translators) throws Exception {
186  
    for (String translator : translators)
187  
      x = applyTranslator(x, translator);
188  
    return x;
189  
  }
190  
191  
  private static File applyTranslator(File x, String translator) throws Exception {
192  
    if (verbose)
193  
      System.out.println("Using translator " + translator + " on sources in " + x.getPath());
194  
195  
    File newDir = runTranslatorOnInput(translator, null, x, !verbose);
196  
197  
    if (!new File(newDir, "main.java").exists()) {
198  
      throw new Exception("Translator " + translator + " did not generate main.java");
199  
      // TODO: show translator output
200  
    }
201  
    if (verbose)
202  
      System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
203  
    x = newDir;
204  
    return x;
205  
  }
206  
207  
  private static File luaPrintToJavaPrint(File x) throws IOException {
208  
    File newDir = TempDirMaker_make();
209  
    String code = loadTextFile(new File(x, "main.java").getPath(), null);
210  
    code = luaPrintToJavaPrint(code);
211  
    if (verbose)
212  
      System.out.println(code);
213  
    saveTextFile(new File(newDir, "main.java").getPath(), code);
214  
    return newDir;
215  
  }
216  
217  
  public static String luaPrintToJavaPrint(String code) {
218  
    return ("\n" + code).replaceAll(
219  
      "(\n\\s*)print (\".*\")",
220  
      "$1System.out.println($2);").substring(1);
221  
  }
222  
223  
  public static File loadSnippetAsMainJava(String snippetID) throws IOException {
224  
    File srcDir = TempDirMaker_make();
225  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
226  
    return srcDir;
227  
  }
228  
229  
  public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
230  
    File srcDir = TempDirMaker_make();
231  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
232  
    return srcDir;
233  
  }
234  
235  
  /** returns output dir */
236  
  private static File runTranslatorOnInput(String snippetID, String hash, File input, boolean silent) throws Exception {
237  
    File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
238  
      : loadSnippetAsMainJavaVerified(snippetID, hash);
239  
    srcDir = defaultTranslate(srcDir);
240  
    boolean runInProcess = false;
241  
    File ioBaseDir = TempDirMaker_make();
242  
    if (virtualizeTranslators) {
243  
      if (verbose) System.out.println("Virtualizing translator");
244  
245  
      //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
246  
      // that doesn't work because it recurses infinitely...
247  
248  
      // So we do it right here:
249  
      String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
250  
      s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
251  
      s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
252  
      s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
253  
      s += "\n\n" + loadSnippet("#2000355"); // load class virtual
254  
255  
      // change baseDir
256  
      s = s.replace("virtual_baseDir = \"\";",
257  
        "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";");
258  
259  
      // forward snippet cache
260  
      s = s.replace("static File DiskSnippetCache_dir;",
261  
        "static File DiskSnippetCache_dir = new File(" + javaQuote(DiskSnippetCache_dir.getAbsolutePath()) + ");");
262  
      s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");
263  
264  
      if (verbose) {
265  
        System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
266  
        System.out.println(s);
267  
        System.out.println("==END VIRTUALIZED TRANSLATOR==");
268  
      }
269  
      saveTextFile(new File(srcDir, "main.java").getPath(), s);
270  
271  
      // TODO: silence translator also
272  
      runInProcess = true;
273  
    }
274  
    return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess);
275  
  }
276  
277  
  /** returns output dir */
278  
  private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput, boolean silent, boolean runInProcess) throws Exception {
279  
    File srcDir = new File(ioBaseDir, "src");
280  
    File inputDir = new File(ioBaseDir, "input");
281  
    File outputDir = new File(ioBaseDir, "output");
282  
    copyInput(originalSrcDir, srcDir);
283  
    copyInput(originalInput, inputDir);
284  
    javax2(srcDir, ioBaseDir, silent, runInProcess);
285  
    return outputDir;
286  
  }
287  
288  
  private static void copyInput(File src, File dst) throws IOException {
289  
    copyDirectory(src, dst);
290  
  }
291  
292  
  public static boolean hasFile(File inputDir, String name) {
293  
    return new File(inputDir, name).exists();
294  
  }
295  
296  
  public static void copyDirectory(File src, File dst) throws IOException {
297  
    if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
298  
    dst.mkdirs();
299  
    File[] files = src.listFiles();
300  
    if (files == null) return;
301  
    for (File file : files) {
302  
      File dst1 = new File(dst, file.getName());
303  
      if (file.isDirectory())
304  
        copyDirectory(file, dst1);
305  
      else {
306  
        if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
307  
        copy(file, dst1);
308  
      }
309  
    }
310  
  }
311  
312  
  /** Quickly copy a file without a progress bar or any other fancy GUI... :) */
313  
  public static void copy(File src, File dest) throws IOException {
314  
    FileInputStream inputStream = new FileInputStream(src);
315  
    FileOutputStream outputStream = new FileOutputStream(dest);
316  
    try {
317  
      copy(inputStream, outputStream);
318  
      inputStream.close();
319  
    } finally {
320  
      outputStream.close();
321  
    }
322  
  }
323  
324  
  public static void copy(InputStream in, OutputStream out) throws IOException {
325  
    byte[] buf = new byte[65536];
326  
    while (true) {
327  
      int n = in.read(buf);
328  
      if (n <= 0) return;
329  
      out.write(buf, 0, n);
330  
    }
331  
  }
332  
333  
  /** writes safely (to temp file, then rename) */
334  
  public static void saveTextFile(String fileName, String contents) throws IOException {
335  
    File file = new File(fileName);
336  
    File parentFile = file.getParentFile();
337  
    if (parentFile != null)
338  
      parentFile.mkdirs();
339  
    String tempFileName = fileName + "_temp";
340  
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
341  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
342  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
343  
    printWriter.print(contents);
344  
    printWriter.close();
345  
    if (file.exists() && !file.delete())
346  
      throw new IOException("Can't delete " + fileName);
347  
348  
    if (!new File(tempFileName).renameTo(file))
349  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
350  
  }
351  
352  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
353  
    if (!new File(fileName).exists())
354  
      return defaultContents;
355  
356  
    FileInputStream fileInputStream = new FileInputStream(fileName);
357  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
358  
    return loadTextFile(inputStreamReader);
359  
  }
360  
361  
  public static String loadTextFile(Reader reader) throws IOException {
362  
    StringBuilder builder = new StringBuilder();
363  
    try {
364  
      BufferedReader bufferedReader = new BufferedReader(reader);
365  
      String line;
366  
      while ((line = bufferedReader.readLine()) != null)
367  
        builder.append(line).append('\n');
368  
    } finally {
369  
      reader.close();
370  
    }
371  
    return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1);
372  
  }
373  
374  
  static File DiskSnippetCache_dir;
375  
376  
  public static void initDiskSnippetCache(File dir) {
377  
    DiskSnippetCache_dir = dir;
378  
    dir.mkdirs();
379  
  }
380  
381  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
382  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
383  
  }
384  
385  
  private static File DiskSnippetCache_getFile(long snippetID) {
386  
    return new File(DiskSnippetCache_dir, "" + snippetID);
387  
  }
388  
389  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
390  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
391  
  }
392  
393  
  public static File DiskSnippetCache_getDir() {
394  
    return DiskSnippetCache_dir;
395  
  }
396  
397  
  public static void initSnippetCache() {
398  
    if (DiskSnippetCache_dir == null)
399  
      initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
400  
  }
401  
402  
  public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
403  
    String text = loadSnippet(snippetID);
404  
    String realHash = getHash(text.getBytes("UTF-8"));
405  
    if (!realHash.equals(hash)) {
406  
      String msg;
407  
      if (hash.isEmpty())
408  
        msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
409  
      else
410  
        msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
411  
      throw new RuntimeException(msg);
412  
    }
413  
    return text;
414  
  }
415  
416  
  public static String getHash(byte[] data) {
417  
    return bytesToHex(getFullFingerprint(data));
418  
  }
419  
420  
  public static byte[] getFullFingerprint(byte[] data) {
421  
    try {
422  
      return MessageDigest.getInstance("MD5").digest(data);
423  
    } catch (NoSuchAlgorithmException e) {
424  
      throw new RuntimeException(e);
425  
    }
426  
  }
427  
428  
  public static String bytesToHex(byte[] bytes) {
429  
    return bytesToHex(bytes, 0, bytes.length);
430  
  }
431  
432  
  public static String bytesToHex(byte[] bytes, int ofs, int len) {
433  
    StringBuilder stringBuilder = new StringBuilder(len*2);
434  
    for (int i = 0; i < len; i++) {
435  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
436  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
437  
    }
438  
    return stringBuilder.toString();
439  
  }
440  
441  
  public static String loadSnippet(String snippetID) throws IOException {
442  
    return loadSnippet(parseSnippetID(snippetID));
443  
  }
444  
445  
  public static long parseSnippetID(String snippetID) {
446  
    return Long.parseLong(shortenSnippetID(snippetID));
447  
  }
448  
449  
  private static String shortenSnippetID(String snippetID) {
450  
    if (snippetID.startsWith("#"))
451  
      snippetID = snippetID.substring(1);
452  
    String httpBlaBla = "http://tinybrain.de/";
453  
    if (snippetID.startsWith(httpBlaBla))
454  
      snippetID = snippetID.substring(httpBlaBla.length());
455  
    return snippetID;
456  
  }
457  
458  
  public static boolean isSnippetID(String snippetID) {
459  
    snippetID = shortenSnippetID(snippetID);
460  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
461  
  }
462  
463  
  public static boolean isInteger(String s) {
464  
    return Pattern.matches("\\-?\\d+", s);
465  
  }
466  
467  
  public static String loadSnippet(long snippetID) throws IOException {
468  
    String text = memSnippetCache.get(snippetID);
469  
    if (text != null)
470  
      return text;
471  
472  
    if (preferCached) {
473  
      initSnippetCache();
474  
      text = DiskSnippetCache_get(snippetID);
475  
      if (text != null)
476  
        return text;
477  
    }
478  
479  
    try {
480  
      URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
481  
      text = loadPage(url);
482  
    } catch (FileNotFoundException e) {
483  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
484  
    }
485  
486  
    memSnippetCache.put(snippetID, text);
487  
488  
    try {
489  
      initSnippetCache();
490  
      DiskSnippetCache_put(snippetID, text);
491  
    } catch (IOException e) {
492  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
493  
    }
494  
495  
    return text;
496  
  }
497  
498  
  private static String loadPage(URL url) throws IOException {
499  
    System.err.println("Loading: " + url.toExternalForm());
500  
    URLConnection con = url.openConnection();
501  
    return loadPage(con, url);
502  
  }
503  
504  
  public static String loadPage(URLConnection con, URL url) throws IOException {
505  
    String contentType = con.getContentType();
506  
    if (contentType == null)
507  
      throw new IOException("Page could not be read: " + url);
508  
    //Log.info("Content-Type: " + contentType);
509  
    String charset = guessCharset(contentType);
510  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
511  
    StringBuilder buf = new StringBuilder();
512  
    while (true) {
513  
      int ch = r.read();
514  
      if (ch < 0)
515  
        break;
516  
      //Log.info("Chars read: " + buf.length());
517  
      buf.append((char) ch);
518  
    }
519  
    return buf.toString();
520  
  }
521  
522  
  public static String guessCharset(String contentType) {
523  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
524  
    Matcher m = p.matcher(contentType);
525  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
526  
    return m.matches() ? m.group(1) : "ISO-8859-1";
527  
  }
528  
529  
  public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess) throws Exception {
530  
    // collect sources
531  
532  
    List<File> sources = new ArrayList<File>();
533  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
534  
    scanForSources(srcDir, sources, true);
535  
    if (sources.isEmpty()) {
536  
      System.out.println("No sources found");
537  
      return;
538  
    }
539  
540  
    // compile
541  
542  
    File optionsFile = File.createTempFile("javax", "");
543  
    File classesDir = TempDirMaker_make();
544  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
545  
    String options = "-d " + bashQuote(classesDir.getPath());
546  
    writeOptions(sources, optionsFile, options);
547  
    classesDir.mkdirs();
548  
    String javacOutput = invokeJavac(optionsFile);
549  
550  
    // run
551  
552  
    if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
553  
      + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
554  
    runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess);
555  
  }
556  
557  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
558  
                                 boolean silent, boolean runInProcess) throws Exception {
559  
    // print javac output if compile failed and it hasn't been printed yet
560  
    boolean didNotCompile = !hasFile(classesDir, "main.class");
561  
    if (verbose || didNotCompile)
562  
      System.out.println(javacOutput);
563  
    if (didNotCompile)
564  
      return;
565  
566  
    if (runInProcess
567  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
568  
      runProgramQuick(classesDir);
569  
      return;
570  
    }
571  
572  
    boolean echoOK = false;
573  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
574  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
575  
    if (verbose) System.out.println(bashCmd);
576  
    String output = backtick(bashCmd);
577  
    if (verbose || !silent)
578  
      System.out.println(output);
579  
  }
580  
581  
  private static void runProgramQuick(File classesDir) throws Exception {
582  
    URLClassLoader classLoader = new URLClassLoader(new URL[]{classesDir.toURI().toURL()});
583  
    Class<?> mainClass = classLoader.loadClass("main");
584  
    Method main = mainClass.getMethod("main", String[].class);
585  
    main.invoke(null, (Object) new String[0]);
586  
  }
587  
588  
  private static String invokeJavac(File optionsFile) throws IOException {
589  
    String output;
590  
    try {
591  
      output = invokeEcj(optionsFile);
592  
    } catch (NoClassDefFoundError e) {
593  
      if (verbose) {
594  
        System.err.println("ecj not found - using javac");
595  
        e.printStackTrace();
596  
      }
597  
      output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
598  
    }
599  
    if (verbose) System.out.println(output);
600  
    return output;
601  
  }
602  
603  
  // throws ClassNotFoundError if ecj is not in classpath
604  
  static String invokeEcj(File optionsFile) {
605  
    StringWriter writer = new StringWriter();
606  
    PrintWriter printWriter = new PrintWriter(writer);
607  
    org.eclipse.jdt.core.compiler.CompilationProgress progress = null;
608  
    org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
609  
      new String[] { "@" + optionsFile.getPath(), "-source", "1.7" },
610  
      printWriter,
611  
      printWriter,
612  
      progress);
613  
    return writer.toString();
614  
  }
615  
616  
  private static void writeOptions(List<File> sources, File sourcesFile, String moreOptions) throws IOException {
617  
    FileWriter writer = new FileWriter(sourcesFile);
618  
    for (File source : sources)
619  
      writer.write(bashQuote(source.getPath()) + " ");
620  
    writer.write(moreOptions);
621  
    writer.close();
622  
  }
623  
624  
  private static void scanForSources(File source, List<File> sources, boolean topLevel) {
625  
    if (source.isFile() && source.getName().endsWith(".java"))
626  
      sources.add(source);
627  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
628  
      File[] files = source.listFiles();
629  
      for (File file : files)
630  
        scanForSources(file, sources, false);
631  
    }
632  
  }
633  
634  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
635  
    if (topLevel) return false; // input or output ok as highest directory (intentionally specified by user, not just found by a directory scan in which case we probably don't want it. it's more like heuristics actually.)
636  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
637  
  }
638  
639  
  public static String backtick(String cmd) throws IOException {
640  
    ++processesStarted;
641  
    File outFile = File.createTempFile("_backtick", "");
642  
    File scriptFile = File.createTempFile("_backtick", "");
643  
644  
    String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1";
645  
    //Log.info("[Backtick] " + command);
646  
    try {
647  
      saveTextFile(scriptFile.getPath(), command);
648  
      String[] command2 = {"/bin/bash", scriptFile.getPath() };
649  
      Process process = Runtime.getRuntime().exec(command2);
650  
      try {
651  
        process.waitFor();
652  
      } catch (InterruptedException e) {
653  
        throw new RuntimeException(e);
654  
      }
655  
      process.exitValue();
656  
      return loadTextFile(outFile.getPath(), "");
657  
    } finally {
658  
      scriptFile.delete();
659  
    }
660  
  }
661  
662  
  /** possibly improvable */
663  
  public static String javaQuote(String text) {
664  
    return bashQuote(text);
665  
  }
666  
667  
  /** possibly improvable */
668  
  public static String bashQuote(String text) {
669  
    if (text == null) return null;
670  
    return "\"" + text
671  
      .replace("\\", "\\\\")
672  
      .replace("\"", "\\\"")
673  
      .replace("\n", "\\n")
674  
      .replace("\r", "\\r") + "\"";
675  
  }
676  
677  
  public final static String charsetForTextFiles = "UTF8";
678  
679  
  static long TempDirMaker_lastValue;
680  
681  
  public static File TempDirMaker_make() {
682  
    File dir = new File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue());
683  
    dir.mkdirs();
684  
    return dir;
685  
  }
686  
687  
  private static long TempDirMaker_newValue() {
688  
    long value;
689  
    do
690  
      value = System.currentTimeMillis();
691  
    while (value == TempDirMaker_lastValue);
692  
    TempDirMaker_lastValue = value;
693  
    return value;
694  
  }
695  
696  
}

Author comment

Began life as a copy of #599

download  show line numbers   

Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #616
Snippet name: x10.java (under development)
Eternal ID of this version: #616/1
Text MD5: 5f0b950beb8c81019d034b48834b41cc
Author: stefan
Category: javax
Type: Java source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-05-13 03:10:55
Source code size: 24999 bytes / 696 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 712 / 225
Referenced in: [show references]