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

1571
LINES

< > BotCompany Repo | #1000572 // _javax.java (JavaX 19)

JavaX fragment (include)

1  
/**
2  
 JavaX runner version 19
3  
4  
 Changes to v18:
5  
 -safeTranslate
6  
 -"list", "translate" and "run" ok in program args
7  
 -TODO: find a solution for -v etc.
8  
 -"-javac" option to force using javac
9  
 -compiler errors now detected robustly, both with javac and ecj.
10  
 -and some more...
11  
12  
 */
13  
14  
class _javax {
15  
  static final String version = "JavaX 19";
16  
17  
  static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
18  
  static String translateTo = null;
19  
  static boolean preferCached = false, noID = false, noPrefetch = false;
20  
  static boolean safeOnly = false, safeTranslate = false, javacOnly = false;
21  
  static boolean runMainInProcess = true;
22  
  static List<String[]> mainTranslators = new ArrayList<String[]>();
23  
  private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
24  
  private static int processesStarted, compilations;
25  
26  
  // snippet ID -> md5
27  
  private static HashMap<Long, String> prefetched = new HashMap<Long, String>();
28  
  private static File virtCache;
29  
30  
  // doesn't work yet
31  
  private static Map<String, Class<?>> programCache = new HashMap<String, Class<?>>();
32  
  static boolean cacheTranslators = false;
33  
34  
  // this should work (caches transpiled translators)
35  
  private static HashMap<Long, Object[]> translationCache = new HashMap<Long, Object[]>();
36  
  static boolean cacheTranspiledTranslators = true;
37  
38  
  // which snippets are available pre-transpiled server-side?
39  
  private static Set<Long> hasTranspiledSet = new HashSet<Long>();
40  
  static boolean useServerTranspiled = true;
41  
42  
  static Object androidContext;
43  
  static boolean android = isAndroid();
44  
45  
  // Translators currently being translated (to detect recursions)
46  
  private static Set<Long> translating = new HashSet<Long>();
47  
48  
  static String lastOutput;
49  
50  
  public static void main(String[] args) throws Exception {
51  
    File ioBaseDir = new File("."), inputDir = null, outputDir = null;
52  
    String src = null;
53  
    List<String> programArgs = new ArrayList<String>();
54  
    String programID;
55  
56  
    for (int i = 0; i < args.length; i++) {
57  
      String arg = args[i];
58  
59  
      if (arg.equals("-version")) {
60  
        showVersion();
61  
        return;
62  
      }
63  
64  
      if (arg.equals("-sysprop")) {
65  
        showSystemProperties();
66  
        return;
67  
      }
68  
69  
      if (arg.equals("-v") || arg.equals("-verbose"))
70  
        verbose = true;
71  
      else if (arg.equals("-finderror"))
72  
        verbose = true;
73  
      else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
74  
        preferCached = true;
75  
      else if (arg.equals("-novirt"))
76  
        virtualizeTranslators = false;
77  
      else if (arg.equals("-safeonly"))
78  
        safeOnly = true;
79  
      else if (arg.equals("-safetranslate"))
80  
        safeTranslate = true;
81  
      else if (arg.equals("-noid"))
82  
        noID = true;
83  
      else if (arg.equals("-nocachetranspiled"))
84  
        cacheTranspiledTranslators = false;
85  
      else if (arg.equals("-javac"))
86  
        javacOnly = true;
87  
      else if (arg.equals("-localtranspile"))
88  
        useServerTranspiled = false;
89  
      else if (arg.equals("translate") && src == null)
90  
        translate = true;
91  
      else if (arg.equals("list") && src == null) {
92  
        list = true;
93  
        virtualizeTranslators = false; // so they are silenced
94  
      } else if (arg.equals("run") && src == null) {
95  
        // it's the default command anyway
96  
      } else if (arg.startsWith("input="))
97  
        inputDir = new File(arg.substring(6));
98  
      else if (arg.startsWith("output="))
99  
        outputDir = new File(arg.substring(7));
100  
      else if (arg.equals("with"))
101  
        mainTranslators.add(new String[] {args[++i], null});
102  
      else if (translate && arg.equals("to"))
103  
        translateTo = args[++i];
104  
      else if (src == null) {
105  
        //System.out.println("src=" + arg);
106  
        src = arg;
107  
      } else
108  
        programArgs.add(arg);
109  
    }
110  
111  
    cleanCache();
112  
113  
    if (useServerTranspiled)
114  
      noPrefetch = true;
115  
116  
    if (src == null) src = ".";
117  
118  
    // Might actually want to write to 2 disk caches (global/per program).
119  
    if (virtualizeTranslators && !preferCached)
120  
      virtCache = TempDirMaker_make();
121  
122  
    if (inputDir != null) {
123  
      ioBaseDir = TempDirMaker_make();
124  
      System.out.println("Taking input from: " + inputDir.getAbsolutePath());
125  
      System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
126  
      copyInput(inputDir, new File(ioBaseDir, "input"));
127  
    }
128  
129  
    javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()]));
130  
131  
    if (outputDir != null) {
132  
      copyInput(new File(ioBaseDir, "output"), outputDir);
133  
      System.out.println("Output copied to: " + outputDir.getAbsolutePath());
134  
    }
135  
136  
    if (verbose) {
137  
      // print stats
138  
      System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations);
139  
    }
140  
  }
141  
142  
  public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
143  
                               String[] args) throws Exception {
144  
    String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null;
145  
    List<File> libraries = new ArrayList<File>();
146  
    File X = transpileMain(src, libraries);
147  
    if (X == null)
148  
      return;
149  
150  
    // list or run
151  
152  
    if (translate) {
153  
      File to = X;
154  
      if (translateTo != null)
155  
        if (new File(translateTo).isDirectory())
156  
          to = new File(translateTo, "main.java");
157  
        else
158  
          to = new File(translateTo);
159  
      if (to != X)
160  
        copy(new File(X, "main.java"), to);
161  
      System.out.println("Program translated to: " + to.getAbsolutePath());
162  
    } else if (list)
163  
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
164  
    else
165  
      javax2(X, ioDir, false, runMainInProcess, libraries, args, null, programID);
166  
  }
167  
168  
  static File transpileMain(String src, List<File> libraries) throws Exception {
169  
    File srcDir;
170  
    boolean isTranspiled = false;
171  
    if (isSnippetID(src)) {
172  
      prefetch(src);
173  
      long id = parseSnippetID(src);
174  
      prefetched.remove(id); // hackfix to ensure transpiled main program is found.
175  
      srcDir = loadSnippetAsMainJava(src);
176  
      if (verbose)
177  
        System.err.println("hasTranspiledSet: " + hasTranspiledSet);
178  
      if (hasTranspiledSet.contains(id) && useServerTranspiled) {
179  
        //System.err.println("Trying pretranspiled main program: #" + id);
180  
        String transpiledSrc = getServerTranspiled("#" + id);
181  
        int i = transpiledSrc.indexOf('\n');
182  
        String libs = transpiledSrc.substring(0, Math.max(0, i));
183  
        transpiledSrc = transpiledSrc.substring(i+1);
184  
        if (!transpiledSrc.isEmpty()) {
185  
          srcDir = TempDirMaker_make();
186  
          saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
187  
          isTranspiled = true;
188  
          //translationCache.put(id, new Object[] {srcDir, libraries});
189  
190  
          Matcher m = Pattern.compile("\\d+").matcher(libs);
191  
          while (m.find()) {
192  
            String libid = m.group();
193  
            File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid));
194  
            loadLibrary(libid, libraries, libraryFile);
195  
          }
196  
        }
197  
      }
198  
    } else {
199  
      srcDir = new File(src);
200  
201  
      // if the argument is a file, it is assumed to be main.java
202  
      if (srcDir.isFile()) {
203  
        srcDir = TempDirMaker_make();
204  
        copy(new File(src), new File(srcDir, "main.java"));
205  
      }
206  
207  
      if (!new File(srcDir, "main.java").exists()) {
208  
        showVersion();
209  
        System.out.println("No main.java found, exiting");
210  
        return null;
211  
      }
212  
    }
213  
214  
    // translate
215  
216  
    File X = srcDir;
217  
218  
    if (!isTranspiled) {
219  
      X = topLevelTranslate(X, libraries);
220  
      System.err.println("Translated " + src);
221  
222  
      // save prefetch data
223  
      if (isSnippetID(src))
224  
        savePrefetchData(src);
225  
    }
226  
    return X;
227  
  }
228  
229  
  private static void prefetch(String mainSnippetID) throws IOException {
230  
    if (noPrefetch) return;
231  
232  
    long mainID = parseSnippetID(mainSnippetID);
233  
    String s = mainID + " " + loadTextFile(new File(userHome(), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), "");
234  
    String[] ids = s.trim().split(" ");
235  
    if (ids.length > 1) {
236  
      String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8");
237  
      String data = loadPage(new URL(url));
238  
      String[] split = data.split(" ");
239  
      if (split.length == ids.length)
240  
        for (int i = 0; i < ids.length; i++)
241  
          prefetched.put(parseSnippetID(ids[i]), split[i]);
242  
    }
243  
  }
244  
245  
  static String userHome() {
246  
    if (android)
247  
      return ((File) call(androidContext, "getFilesDir")).getAbsolutePath();
248  
    else
249  
      return System.getProperty("user.home");
250  
  }
251  
252  
  private static void savePrefetchData(String mainSnippetID) throws IOException {
253  
    List<String> ids = new ArrayList<String>();
254  
    long mainID = parseSnippetID(mainSnippetID);
255  
256  
    for (long id : memSnippetCache.keySet())
257  
      if (id != mainID)
258  
        ids.add(String.valueOf(id));
259  
260  
    saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids));
261  
  }
262  
263  
  static File topLevelTranslate(File srcDir, List<File> libraries_out) throws Exception {
264  
    File X = srcDir;
265  
    X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual)
266  
267  
    // actual inner translation of the JavaX source
268  
    X = defaultTranslate(X, libraries_out);
269  
    return X;
270  
  }
271  
272  
  private static File defaultTranslate(File x, List<File> libraries_out) throws Exception {
273  
    x = luaPrintToJavaPrint(x);
274  
    x = repeatAutoTranslate(x, libraries_out);
275  
    return x;
276  
  }
277  
278  
  private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception {
279  
    while (true) {
280  
      File y = autoTranslate(x, libraries_out);
281  
      if (y == x)
282  
        return x;
283  
      x = y;
284  
    }
285  
  }
286  
287  
  private static File autoTranslate(File x, List<File> libraries_out) throws Exception {
288  
    String main = loadTextFile(new File(x, "main.java").getPath(), null);
289  
    List<String> lines = toLines(main);
290  
    List<String[]> translators = findTranslators(lines);
291  
    if (translators.isEmpty())
292  
      return x;
293  
294  
    main = fromLines(lines);
295  
    File newDir = TempDirMaker_make();
296  
    saveTextFile(new File(newDir, "main.java").getPath(), main);
297  
    return applyTranslators(newDir, translators, libraries_out);
298  
  }
299  
300  
  private static List<String[]> findTranslators(List<String> lines) {
301  
    List<String[]> translators = new ArrayList<String[]>();
302  
    Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
303  
    Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
304  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
305  
      String line = iterator.next();
306  
      line = line.trim();
307  
      Matcher matcher = pattern.matcher(line);
308  
      if (matcher.find()) {
309  
        String[] t = matcher.group(1).split("[ \t]+");
310  
        String rest = line.substring(matcher.end());
311  
        String arg = null;
312  
        if (t.length == 1) {
313  
          Matcher mArgs = pArgs.matcher(rest);
314  
          if (mArgs.find())
315  
            arg = mArgs.group(1);
316  
        }
317  
        for (String transi : t)
318  
          translators.add(new String[]{transi, arg});
319  
        iterator.remove();
320  
      }
321  
    }
322  
    return translators;
323  
  }
324  
325  
  public static List<String> toLines(String s) {
326  
    List<String> lines = new ArrayList<String>();
327  
    int start = 0;
328  
    while (true) {
329  
      int i = toLines_nextLineBreak(s, start);
330  
      if (i < 0) {
331  
        if (s.length() > start) lines.add(s.substring(start));
332  
        break;
333  
      }
334  
335  
      lines.add(s.substring(start, i));
336  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
337  
        i += 2;
338  
      else
339  
        ++i;
340  
341  
      start = i;
342  
    }
343  
    return lines;
344  
  }
345  
346  
  private static int toLines_nextLineBreak(String s, int start) {
347  
    for (int i = start; i < s.length(); i++) {
348  
      char c = s.charAt(i);
349  
      if (c == '\r' || c == '\n')
350  
        return i;
351  
    }
352  
    return -1;
353  
  }
354  
355  
  public static String fromLines(List<String> lines) {
356  
    StringBuilder buf = new StringBuilder();
357  
    for (String line : lines) {
358  
      buf.append(line).append('\n');
359  
    }
360  
    return buf.toString();
361  
  }
362  
363  
  private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception {
364  
    for (String[] translator : translators)
365  
      x = applyTranslator(x, translator[0], translator[1], libraries_out);
366  
    return x;
367  
  }
368  
369  
  // also takes a library
370  
  private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception {
371  
    if (verbose)
372  
      System.out.println("Using translator " + translator + " on sources in " + x.getPath());
373  
374  
    File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out);
375  
376  
    if (!new File(newDir, "main.java").exists()) {
377  
      throw new Exception("Translator " + translator + " did not generate main.java");
378  
      // TODO: show translator output
379  
    }
380  
    if (verbose)
381  
      System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
382  
    x = newDir;
383  
    return x;
384  
  }
385  
386  
  private static File luaPrintToJavaPrint(File x) throws IOException {
387  
    File newDir = TempDirMaker_make();
388  
    String code = loadTextFile(new File(x, "main.java").getPath(), null);
389  
    code = luaPrintToJavaPrint(code);
390  
    if (verbose)
391  
      System.out.println(code);
392  
    saveTextFile(new File(newDir, "main.java").getPath(), code);
393  
    return newDir;
394  
  }
395  
396  
  public static String luaPrintToJavaPrint(String code) {
397  
    return ("\n" + code).replaceAll(
398  
      "(\n\\s*)print (\".*\")",
399  
      "$1System.out.println($2);").substring(1);
400  
  }
401  
402  
  public static File loadSnippetAsMainJava(String snippetID) throws IOException {
403  
    checkProgramSafety(snippetID);
404  
    File srcDir = TempDirMaker_make();
405  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
406  
    return srcDir;
407  
  }
408  
409  
  public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
410  
    checkProgramSafety(snippetID);
411  
    File srcDir = TempDirMaker_make();
412  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
413  
    return srcDir;
414  
  }
415  
416  
  /** returns output dir */
417  
  private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
418  
                                           boolean silent,
419  
                                           List<File> libraries_out) throws Exception {
420  
    if (safeTranslate)
421  
      checkProgramSafetyImpl(snippetID);
422  
    long id = parseSnippetID(snippetID);
423  
424  
    File libraryFile = DiskSnippetCache_getLibrary(id);
425  
    if (libraryFile != null) {
426  
      loadLibrary(snippetID, libraries_out, libraryFile);
427  
      return input;
428  
    }
429  
430  
    String[] args = arg != null ? new String[]{arg} : new String[0];
431  
432  
    File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
433  
      : loadSnippetAsMainJavaVerified(snippetID, hash);
434  
    long mainJavaSize = new File(srcDir, "main.java").length();
435  
436  
    if (mainJavaSize == 0) { // no text in snippet? assume it's a library
437  
      loadLibrary(snippetID, libraries_out, libraryFile);
438  
      return input;
439  
    }
440  
441  
    List<File> libraries = new ArrayList<File>();
442  
    Object[] cached = translationCache.get(id);
443  
    if (cached != null) {
444  
      //System.err.println("Taking translator " + snippetID + " from cache!");
445  
      srcDir = (File) cached[0];
446  
      libraries = (List<File>) cached[1];
447  
    } else if (hasTranspiledSet.contains(id) && useServerTranspiled) {
448  
      System.err.println("Trying pretranspiled translator: #" + snippetID);
449  
      String transpiledSrc = getServerTranspiled(snippetID);
450  
      transpiledSrc = transpiledSrc.substring(transpiledSrc.indexOf('\n')+1);
451  
      // TODO: check for libraries
452  
      if (!transpiledSrc.isEmpty()) {
453  
        srcDir = TempDirMaker_make();
454  
        saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
455  
        translationCache.put(id, cached = new Object[] {srcDir, libraries});
456  
      }
457  
    }
458  
459  
    File ioBaseDir = TempDirMaker_make();
460  
461  
    /*Class<?> mainClass = programCache.get("" + parseSnippetID(snippetID));
462  
    if (mainClass != null)
463  
      return runCached(ioBaseDir, input, args);*/
464  
    // Doesn't work yet because virtualized directories are hardcoded in translator...
465  
466  
    if (cached == null) {
467  
      System.err.println("Translating translator #" + id);
468  
      if (translating.contains(id))
469  
        throw new RuntimeException("Recursive translator reference chain including #" + id);
470  
      translating.add(id);
471  
      try {
472  
        srcDir = defaultTranslate(srcDir, libraries);
473  
      } finally {
474  
        translating.remove(id);
475  
      }
476  
      System.err.println("Translated translator #" + id);
477  
      translationCache.put(id, new Object[]{srcDir, libraries});
478  
    }
479  
480  
    boolean runInProcess = false;
481  
482  
    if (virtualizeTranslators) {
483  
      if (verbose) System.out.println("Virtualizing translator");
484  
485  
      // TODO: don't virtualize class _javax (as included in, say, #636)
486  
487  
      //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
488  
      // that doesn't work because it recurses infinitely...
489  
490  
      // So we do it right here:
491  
      String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
492  
      s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
493  
      s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
494  
      s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
495  
      s += "\n\n" + loadSnippet("#2000355"); // load class virtual
496  
497  
      // change baseDir
498  
      s = s.replace("virtual_baseDir = \"\";",
499  
        "virtual_baseDir " + "= " + javaQuote(ioBaseDir.getAbsolutePath()) + ";"); // extra + is necessary for Dumb TinyBrain :)
500  
501  
      // forward snippet cache (virtualized one)
502  
      File dir = virtCache != null ? virtCache : DiskSnippetCache_dir;
503  
      s = s.replace("static File DiskSnippetCache_dir" + ";",
504  
        "static File DiskSnippetCache_dir " + "= new File(" + javaQuote(dir.getAbsolutePath()) + ");"); // extra + is necessary for Dumb TinyBrain :)
505  
      s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");
506  
507  
      if (verbose) {
508  
        System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
509  
        System.out.println(s);
510  
        System.out.println("==END VIRTUALIZED TRANSLATOR==");
511  
      }
512  
      srcDir = TempDirMaker_make();
513  
      saveTextFile(new File(srcDir, "main.java").getPath(), s);
514  
515  
      // TODO: silence translator also
516  
      runInProcess = true;
517  
    }
518  
519  
    return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries,
520  
      args, cacheTranslators ? "" + id : null, "" + id);
521  
  }
522  
523  
  private static String getServerTranspiled(String snippetID) throws IOException {
524  
    long id = parseSnippetID(snippetID);
525  
    URL url = new URL("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id);
526  
    return loadPage(url);
527  
  }
528  
529  
  static void checkProgramSafety(String snippetID) throws IOException {
530  
    if (!safeOnly) return;
531  
    checkProgramSafetyImpl(snippetID);
532  
  }
533  
534  
  static void checkProgramSafetyImpl(String snippetID) throws IOException {
535  
    URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID));
536  
    String text = loadPage(url);
537  
    if (!text.startsWith("{\"safe\":\"1\"}"))
538  
      throw new RuntimeException("Program not safe: #" + parseSnippetID(snippetID));
539  
  }
540  
541  
  static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException {
542  
    if (verbose)
543  
      System.out.println("Assuming " + snippetID + " is a library.");
544  
545  
    if (libraryFile == null) {
546  
      byte[] data = loadDataSnippetImpl(snippetID);
547  
      DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data);
548  
      libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
549  
    }
550  
551  
    if (!libraries_out.contains(libraryFile))
552  
      libraries_out.add(libraryFile);
553  
  }
554  
555  
  private static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
556  
    byte[] data;
557  
    try {
558  
      URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
559  
        + parseSnippetID(snippetID) + "&contentType=application/binary");
560  
      System.err.println("Loading library: " + url);
561  
      data = loadBinaryPage(url.openConnection());
562  
      if (verbose)
563  
        System.err.println("Bytes loaded: " + data.length);
564  
    } catch (FileNotFoundException e) {
565  
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
566  
    }
567  
    return data;
568  
  }
569  
570  
  /** returns output dir */
571  
  private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput,
572  
                               boolean silent, boolean runInProcess,
573  
                               List<File> libraries, String[] args, String cacheAs,
574  
                               String programID) throws Exception {
575  
    File srcDir = new File(ioBaseDir, "src");
576  
    File inputDir = new File(ioBaseDir, "input");
577  
    File outputDir = new File(ioBaseDir, "output");
578  
    copyInput(originalSrcDir, srcDir);
579  
    copyInput(originalInput, inputDir);
580  
    javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID);
581  
    return outputDir;
582  
  }
583  
584  
  private static void copyInput(File src, File dst) throws IOException {
585  
    copyDirectory(src, dst);
586  
  }
587  
588  
  public static boolean hasFile(File inputDir, String name) {
589  
    return new File(inputDir, name).exists();
590  
  }
591  
592  
  public static void copyDirectory(File src, File dst) throws IOException {
593  
    if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
594  
    dst.mkdirs();
595  
    File[] files = src.listFiles();
596  
    if (files == null) return;
597  
    for (File file : files) {
598  
      File dst1 = new File(dst, file.getName());
599  
      if (file.isDirectory())
600  
        copyDirectory(file, dst1);
601  
      else {
602  
        if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
603  
        copy(file, dst1);
604  
      }
605  
    }
606  
  }
607  
608  
  /** Quickly copy a file without a progress bar or any other fancy GUI... :) */
609  
  public static void copy(File src, File dest) throws IOException {
610  
    FileInputStream inputStream = newFileInputStream(src);
611  
    FileOutputStream outputStream = newFileOutputStream(dest);
612  
    try {
613  
      copy(inputStream, outputStream);
614  
      inputStream.close();
615  
    } finally {
616  
      outputStream.close();
617  
    }
618  
  }
619  
620  
  static Object call(Object o, String method, Object... args) {
621  
    try {
622  
      Method m = call_findMethod(o, method, args, false);
623  
      m.setAccessible(true);
624  
      return m.invoke(o, args);
625  
    } catch (Exception e) {
626  
      throw new RuntimeException(e);
627  
    }
628  
  }
629  
630  
  static Object call(Class c, String method, Object... args) {
631  
    try {
632  
      Method m = call_findStaticMethod(c, method, args, false);
633  
      m.setAccessible(true);
634  
      return m.invoke(null, args);
635  
    } catch (Exception e) {
636  
      throw new RuntimeException(e);
637  
    }
638  
  }
639  
640  
  static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
641  
    while (c != null) {
642  
      for (Method m : c.getDeclaredMethods()) {
643  
        if (debug)
644  
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
645  
        if (!m.getName().equals(method)) {
646  
          if (debug) System.out.println("Method name mismatch: " + method);
647  
          continue;
648  
        }
649  
650  
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
651  
          continue;
652  
653  
        return m;
654  
      }
655  
      c = c.getSuperclass();
656  
    }
657  
    throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + c.getName());
658  
  }
659  
660  
  static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
661  
    Class c = o.getClass();
662  
    while (c != null) {
663  
      for (Method m : c.getDeclaredMethods()) {
664  
        if (debug)
665  
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
666  
        if (m.getName().equals(method) && call_checkArgs(m, args, debug))
667  
          return m;
668  
      }
669  
      c = c.getSuperclass();
670  
    }
671  
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
672  
  }
673  
674  
  private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
675  
    Class<?>[] types = m.getParameterTypes();
676  
    if (types.length != args.length) {
677  
      if (debug)
678  
        System.out.println("checkArgs: Bad parameter length: " + args.length + " vs " + types.length);
679  
      return false;
680  
    }
681  
    for (int i = 0; i < types.length; i++)
682  
      if (!(args[i] == null || types[i].isInstance(args[i]))) {
683  
        if (debug)
684  
          System.out.println("checkArgs: Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
685  
        return false;
686  
      }
687  
    return true;
688  
  }
689  
690  
  private static FileInputStream newFileInputStream(File f) throws FileNotFoundException {
691  
    /*if (androidContext != null)
692  
      return (FileInputStream) call(androidContext,
693  
        "openFileInput", f.getPath());
694  
    else*/
695  
    return new // line break for Dumb TinyBrain :)
696  
    FileInputStream(f);
697  
  }
698  
699  
  private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException {
700  
    /*if (androidContext != null)
701  
      return (FileOutputStream) call(androidContext,
702  
        "openFileOutput", f.getPath(), 0);
703  
    else*/
704  
    return new // line break for Dumb TinyBrain :)
705  
    FileOutputStream(f);
706  
  }
707  
708  
  public static void copy(InputStream in, OutputStream out) throws IOException {
709  
    byte[] buf = new byte[65536];
710  
    while (true) {
711  
      int n = in.read(buf);
712  
      if (n <= 0) return;
713  
      out.write(buf, 0, n);
714  
    }
715  
  }
716  
717  
  /** writes safely (to temp file, then rename) */
718  
  public static void saveTextFile(String fileName, String contents) throws IOException {
719  
    File file = new File(fileName);
720  
    File parentFile = file.getParentFile();
721  
    if (parentFile != null)
722  
      parentFile.mkdirs();
723  
    String tempFileName = fileName + "_temp";
724  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
725  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
726  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
727  
    printWriter.print(contents);
728  
    printWriter.close();
729  
    if (file.exists() && !file.delete())
730  
      throw new IOException("Can't delete " + fileName);
731  
732  
    if (!new File(tempFileName).renameTo(file))
733  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
734  
  }
735  
736  
  /** writes safely (to temp file, then rename) */
737  
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
738  
    File file = new File(fileName);
739  
    File parentFile = file.getParentFile();
740  
    if (parentFile != null)
741  
      parentFile.mkdirs();
742  
    String tempFileName = fileName + "_temp";
743  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
744  
    fileOutputStream.write(contents);
745  
    fileOutputStream.close();
746  
    if (file.exists() && !file.delete())
747  
      throw new IOException("Can't delete " + fileName);
748  
749  
    if (!new File(tempFileName).renameTo(file))
750  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
751  
  }
752  
753  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
754  
    if (!new File(fileName).exists())
755  
      return defaultContents;
756  
757  
    FileInputStream fileInputStream = newFileInputStream(new File(fileName));
758  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
759  
    return loadTextFile(inputStreamReader, (int) new File(fileName).length());
760  
  }
761  
762  
  public static String loadTextFile(Reader reader, int length) throws IOException {
763  
    try {
764  
      char[] chars = new char[length];
765  
      int n = reader.read(chars);
766  
      return new String(chars, 0, n);
767  
    } finally {
768  
      reader.close();
769  
    }
770  
  }
771  
772  
  static File DiskSnippetCache_dir;
773  
774  
  public static void initDiskSnippetCache(File dir) {
775  
    DiskSnippetCache_dir = dir;
776  
    dir.mkdirs();
777  
  }
778  
779  
  // Data files are immutable, use centralized cache
780  
  public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
781  
    File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
782  
    if (verbose)
783  
      System.out.println("Checking data cache: " + file.getPath());
784  
    return file.exists() ? file : null;
785  
  }
786  
787  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
788  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
789  
  }
790  
791  
  private static File DiskSnippetCache_getFile(long snippetID) {
792  
    return new File(DiskSnippetCache_dir, "" + snippetID);
793  
  }
794  
795  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
796  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
797  
  }
798  
799  
  public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
800  
    saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
801  
  }
802  
803  
  public static File DiskSnippetCache_getDir() {
804  
    return DiskSnippetCache_dir;
805  
  }
806  
807  
  public static void initSnippetCache() {
808  
    if (DiskSnippetCache_dir == null)
809  
      initDiskSnippetCache(getGlobalCache());
810  
  }
811  
812  
  private static File getGlobalCache() {
813  
    File file = new File(userHome(), ".tinybrain/snippet-cache");
814  
    file.mkdirs();
815  
    return file;
816  
  }
817  
818  
  public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
819  
    String text = loadSnippet(snippetID);
820  
    String realHash = getHash(text.getBytes("UTF-8"));
821  
    if (!realHash.equals(hash)) {
822  
      String msg;
823  
      if (hash.isEmpty())
824  
        msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
825  
      else
826  
        msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
827  
      throw new RuntimeException(msg);
828  
    }
829  
    return text;
830  
  }
831  
832  
  public static String getHash(byte[] data) {
833  
    return bytesToHex(getFullFingerprint(data));
834  
  }
835  
836  
  public static byte[] getFullFingerprint(byte[] data) {
837  
    try {
838  
      return MessageDigest.getInstance("MD5").digest(data);
839  
    } catch (NoSuchAlgorithmException e) {
840  
      throw new RuntimeException(e);
841  
    }
842  
  }
843  
844  
  public static String bytesToHex(byte[] bytes) {
845  
    return bytesToHex(bytes, 0, bytes.length);
846  
  }
847  
848  
  public static String bytesToHex(byte[] bytes, int ofs, int len) {
849  
    StringBuilder stringBuilder = new StringBuilder(len*2);
850  
    for (int i = 0; i < len; i++) {
851  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
852  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
853  
    }
854  
    return stringBuilder.toString();
855  
  }
856  
857  
  public static String loadSnippet(String snippetID) throws IOException {
858  
    return loadSnippet(parseSnippetID(snippetID));
859  
  }
860  
861  
  public static long parseSnippetID(String snippetID) {
862  
    return Long.parseLong(shortenSnippetID(snippetID));
863  
  }
864  
865  
  private static String shortenSnippetID(String snippetID) {
866  
    if (snippetID.startsWith("#"))
867  
      snippetID = snippetID.substring(1);
868  
    String httpBlaBla = "http://tinybrain.de/";
869  
    if (snippetID.startsWith(httpBlaBla))
870  
      snippetID = snippetID.substring(httpBlaBla.length());
871  
    return snippetID;
872  
  }
873  
874  
  public static boolean isSnippetID(String snippetID) {
875  
    snippetID = shortenSnippetID(snippetID);
876  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
877  
  }
878  
879  
  public static boolean isInteger(String s) {
880  
    return Pattern.matches("\\-?\\d+", s);
881  
  }
882  
883  
  public static String loadSnippet(long snippetID) throws IOException {
884  
    String text = memSnippetCache.get(snippetID);
885  
    if (text != null) {
886  
      if (verbose)
887  
        System.out.println("Getting " + snippetID + " from mem cache");
888  
      return text;
889  
    }
890  
891  
    initSnippetCache();
892  
    text = DiskSnippetCache_get(snippetID);
893  
    if (preferCached && text != null) {
894  
      if (verbose)
895  
        System.out.println("Getting " + snippetID + " from disk cache (preferCached)");
896  
      return text;
897  
    }
898  
899  
    String md5 = text != null ? md5(text) : "-";
900  
    if (text != null) {
901  
      String hash = prefetched.get(snippetID);
902  
      if (hash != null) {
903  
        if (md5.equals(hash)) {
904  
          memSnippetCache.put(snippetID, text);
905  
          if (verbose)
906  
            System.out.println("Getting " + snippetID + " from prefetched");
907  
          return text;
908  
        } else
909  
          prefetched.remove(snippetID); // (maybe this is not necessary)
910  
      }
911  
    }
912  
913  
    try {
914  
      /*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
915  
      text = loadPage(url);*/
916  
      String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1";
917  
      if (text != null) {
918  
        //System.err.println("MD5: " + md5);
919  
        theURL += "&md5=" + md5;
920  
      }
921  
      URL url = new URL(theURL);
922  
      String page = loadPage(url);
923  
924  
      // parse & drop transpilation flag available line
925  
      int i = page.indexOf('\n');
926  
      boolean hasTranspiled = page.substring(0, i).trim().equals("1");
927  
      if (hasTranspiled)
928  
        hasTranspiledSet.add(snippetID);
929  
      else
930  
        hasTranspiledSet.remove(snippetID);
931  
      page = page.substring(i+1);
932  
933  
      if (page.startsWith("==*#*==")) {
934  
        // same, keep text
935  
        //System.err.println("Snippet unchanged, keeping.");
936  
      } else {
937  
        // drop md5 line
938  
        i = page.indexOf('\n');
939  
        String hash = page.substring(0, i).trim();
940  
        text = page.substring(i+1);
941  
942  
        String myHash = md5(text);
943  
        if (myHash.equals(hash)) {
944  
          //System.err.println("Hash match: " + hash);
945  
        } else
946  
          System.err.println("Hash mismatch");
947  
      }
948  
    } catch (FileNotFoundException e) {
949  
      e.printStackTrace();
950  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
951  
    }
952  
953  
    memSnippetCache.put(snippetID, text);
954  
955  
    try {
956  
      initSnippetCache();
957  
      DiskSnippetCache_put(snippetID, text);
958  
    } catch (IOException e) {
959  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
960  
    }
961  
962  
    return text;
963  
  }
964  
965  
  private static String md5(String text) {
966  
    try {
967  
      return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
968  
    } catch (UnsupportedEncodingException e) {
969  
      throw new RuntimeException(e);
970  
    }
971  
  }
972  
973  
  public static byte[] md5impl(byte[] data) {
974  
    try {
975  
      return MessageDigest.getInstance("MD5").digest(data);
976  
    } catch (NoSuchAlgorithmException e) {
977  
      throw new RuntimeException(e);
978  
    }
979  
  }
980  
981  
  private static String loadPage(URL url) throws IOException {
982  
    System.err.println("Loading: " + url.toExternalForm());
983  
    URLConnection con = url.openConnection();
984  
    return loadPage(con, url);
985  
  }
986  
987  
  public static String loadPage(URLConnection con, URL url) throws IOException {
988  
    setHeaders(con);
989  
    String contentType = con.getContentType();
990  
    if (contentType == null)
991  
      throw new IOException("Page could not be read: " + url);
992  
    //Log.info("Content-Type: " + contentType);
993  
    String charset = guessCharset(contentType);
994  
    //System.err.println("Charset: " + charset);
995  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
996  
    StringBuilder buf = new StringBuilder();
997  
    while (true) {
998  
      int ch = r.read();
999  
      if (ch < 0)
1000  
        break;
1001  
      //Log.info("Chars read: " + buf.length());
1002  
      buf.append((char) ch);
1003  
    }
1004  
    return buf.toString();
1005  
  }
1006  
1007  
  public static byte[] loadBinaryPage(URLConnection con) throws IOException {
1008  
    setHeaders(con);
1009  
    return loadBinaryPage_noHeaders(con);
1010  
  }
1011  
1012  
  private static byte[] loadBinaryPage_noHeaders(URLConnection con) throws IOException {
1013  
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
1014  
    InputStream inputStream = con.getInputStream();
1015  
    while (true) {
1016  
      int ch = inputStream.read();
1017  
      if (ch < 0)
1018  
        break;
1019  
      buf.write(ch);
1020  
    }
1021  
    inputStream.close();
1022  
    return buf.toByteArray();
1023  
  }
1024  
1025  
  private static void setHeaders(URLConnection con) throws IOException {
1026  
    String computerID = getComputerID();
1027  
    if (computerID != null)
1028  
      con.setRequestProperty("X-ComputerID", computerID);
1029  
  }
1030  
1031  
  public static String guessCharset(String contentType) {
1032  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
1033  
    Matcher m = p.matcher(contentType);
1034  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
1035  
    return m.matches() ? m.group(1) : "ISO-8859-1";
1036  
  }
1037  
1038  
  /** runs a transpiled set of sources */
1039  
  public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess,
1040  
                            List<File> libraries, String[] args, String cacheAs,
1041  
                            String programID) throws Exception {
1042  
    if (android)
1043  
      javax2android(srcDir, args, programID);
1044  
    else {
1045  
      File classesDir = TempDirMaker_make();
1046  
      String javacOutput = compileJava(srcDir, libraries, classesDir);
1047  
1048  
      // run
1049  
1050  
      if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
1051  
        + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
1052  
      runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID);
1053  
    }
1054  
  }
1055  
1056  
  static Class<?> loadx2android(File srcDir, String programID) throws Exception {
1057  
    // TODO: optimize if it's a loaded snippet anyway
1058  
    URL url = new URL("http://tinybrain.de:8080/dexcompile.php");
1059  
    URLConnection conn = url.openConnection();
1060  
    String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8");
1061  
    byte[] dexData = doPostBinary(postData, conn);
1062  
    if (!isDex(dexData))
1063  
      throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8"));
1064  
    System.out.println("Dex loaded: " + dexData.length + "b");
1065  
1066  
    File dexDir = TempDirMaker_make();
1067  
    File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
1068  
    File dexOutputDir = TempDirMaker_make();
1069  
1070  
    System.out.println("Saving dex to: " + dexDir.getAbsolutePath());
1071  
    try {
1072  
      saveBinaryFile(dexFile.getPath(), dexData);
1073  
    } catch (Throwable e) {
1074  
      System.out.println("Whoa!");
1075  
      throw new RuntimeException(e);
1076  
    }
1077  
1078  
    System.out.println("Getting parent class loader.");
1079  
    ClassLoader parentClassLoader =
1080  
      //ClassLoader.getSystemClassLoader(); // does not find support jar
1081  
      //getClass().getClassLoader(); // Let's try this...
1082  
      _javax.class.getClassLoader().getParent(); // XXX !
1083  
1084  
    //System.out.println("Making DexClassLoader.");
1085  
    //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1086  
    //  parentClassLoader);
1087  
    Class dcl = Class.forName("dalvik.system.DexClassLoader");
1088  
    Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1089  
      parentClassLoader);
1090  
1091  
    //System.out.println("Loading main class.");
1092  
    //Class<?> theClass = classLoader.loadClass(mainClassName);
1093  
    Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");
1094  
1095  
    //System.out.println("Main class loaded.");
1096  
    try {
1097  
      set(theClass, "androidContext", androidContext);
1098  
    } catch (Throwable e) {}
1099  
1100  
    try {
1101  
      set(theClass, "programID", programID);
1102  
    } catch (Throwable e) {}
1103  
1104  
    return theClass;
1105  
  }
1106  
1107  
  static void javax2android(File srcDir, String[] args, String programID) throws Exception {
1108  
    Class<?> theClass = loadx2android(srcDir, programID);
1109  
1110  
    Method main = null;
1111  
    try {
1112  
      main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false);
1113  
    } catch (RuntimeException e) {
1114  
    }
1115  
1116  
    //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main);
1117  
1118  
    if (main != null) {
1119  
      // old style main program that returns a View
1120  
      System.out.println("Calling main (old-style)");
1121  
      Object view = main.invoke(null, androidContext);
1122  
      System.out.println("Calling setContentView with " + view);
1123  
      call(Class.forName("main"), "setContentViewInUIThread", view);
1124  
      //call(androidContext, "setContentView", view);
1125  
      System.out.println("Done.");
1126  
    } else {
1127  
      System.out.println("New-style main method running.\n\n====\n");
1128  
      runMainMethod(args, theClass);
1129  
    }
1130  
  }
1131  
1132  
  static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };
1133  
1134  
  static boolean isDex(byte[] dexData) {
1135  
    if (dexData.length < DEX_FILE_MAGIC.length) return false;
1136  
    for (int i = 0; i < DEX_FILE_MAGIC.length; i++)
1137  
      if (dexData[i] != DEX_FILE_MAGIC[i])
1138  
        return false;
1139  
    return true;
1140  
  }
1141  
1142  
  static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException {
1143  
    // connect and do POST
1144  
    setHeaders(conn);
1145  
    conn.setDoOutput(true);
1146  
1147  
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
1148  
    writer.write(urlParameters);
1149  
    writer.flush();
1150  
1151  
    byte[] contents = loadBinaryPage_noHeaders(conn);
1152  
    writer.close();
1153  
    return contents;
1154  
  }
1155  
1156  
  static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
1157  
    ++compilations;
1158  
1159  
    // collect sources
1160  
1161  
    List<File> sources = new ArrayList<File>();
1162  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
1163  
    scanForSources(srcDir, sources, true);
1164  
    if (sources.isEmpty())
1165  
      throw new IOException("No sources found");
1166  
1167  
    // compile
1168  
1169  
    File optionsFile = File.createTempFile("javax", "");
1170  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
1171  
    String options = "-d " + bashQuote(classesDir.getPath());
1172  
    writeOptions(sources, libraries, optionsFile, options);
1173  
    classesDir.mkdirs();
1174  
    return invokeJavaCompiler(optionsFile);
1175  
  }
1176  
1177  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
1178  
                                 boolean silent, boolean runInProcess,
1179  
                                 List<File> libraries, String[] args, String cacheAs,
1180  
                                 String programID) throws Exception {
1181  
    // print javac output if compile failed and it hasn't been printed yet
1182  
    boolean didNotCompile = !didCompile(classesDir);
1183  
    if (verbose || didNotCompile)
1184  
      System.out.println(javacOutput);
1185  
    if (didNotCompile)
1186  
      return;
1187  
1188  
    if (runInProcess
1189  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
1190  
      runProgramQuick(classesDir, libraries, args, cacheAs, programID);
1191  
      return;
1192  
    }
1193  
1194  
    boolean echoOK = false;
1195  
    // TODO: add libraries to class path
1196  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
1197  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
1198  
    if (verbose) System.out.println(bashCmd);
1199  
    String output = backtick(bashCmd);
1200  
    lastOutput = output;
1201  
    if (verbose || !silent)
1202  
      System.out.println(output);
1203  
  }
1204  
1205  
  static boolean didCompile(File classesDir) {
1206  
    return hasFile(classesDir, "main.class");
1207  
  }
1208  
1209  
  private static void runProgramQuick(File classesDir, List<File> libraries,
1210  
                                      String[] args, String cacheAs,
1211  
                                      String programID) throws Exception {
1212  
    // collect urls
1213  
    URL[] urls = new URL[libraries.size()+1];
1214  
    urls[0] = classesDir.toURI().toURL();
1215  
    for (int i = 0; i < libraries.size(); i++)
1216  
      urls[i+1] = libraries.get(i).toURI().toURL();
1217  
1218  
    // make class loader
1219  
    URLClassLoader classLoader = new URLClassLoader(urls);
1220  
1221  
    // load JavaX main class
1222  
    Class<?> mainClass = classLoader.loadClass("main");
1223  
1224  
    if (cacheAs != null)
1225  
      programCache.put(cacheAs, mainClass);
1226  
1227  
    try {
1228  
      set(mainClass, "programID", programID);
1229  
    } catch (Throwable e) {}
1230  
1231  
    runMainMethod(args, mainClass);
1232  
  }
1233  
1234  
1235  
  static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
1236  
    Method main = mainClass.getMethod("main", String[].class);
1237  
    main.invoke(null, args);
1238  
  }
1239  
1240  
  private static String invokeJavaCompiler(File optionsFile) throws IOException {
1241  
    String output;
1242  
    if (hasEcj() && !javacOnly)
1243  
      output = invokeEcj(optionsFile);
1244  
    else
1245  
      output = invokeJavac(optionsFile);
1246  
    if (verbose) System.out.println(output);
1247  
    return output;
1248  
  }
1249  
1250  
  private static boolean hasEcj() {
1251  
    try {
1252  
      Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1253  
      return true;
1254  
    } catch (ClassNotFoundException e) {
1255  
      return false;
1256  
    }
1257  
  }
1258  
1259  
  private static String invokeJavac(File optionsFile) throws IOException {
1260  
    String output;
1261  
    output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
1262  
    if (exitValue != 0) {
1263  
      System.out.println(output);
1264  
      throw new RuntimeException("javac returned errors.");
1265  
    }
1266  
    return output;
1267  
  }
1268  
1269  
  // throws ClassNotFoundException if ecj is not in classpath
1270  
  static String invokeEcj(File optionsFile) {
1271  
    try {
1272  
      StringWriter writer = new StringWriter();
1273  
      PrintWriter printWriter = new PrintWriter(writer);
1274  
1275  
      // add more eclipse options in the line below
1276  
1277  
      String[] args = {"@" + optionsFile.getPath(),
1278  
        "-source", "1.7",
1279  
        "-nowarn"
1280  
      };
1281  
1282  
      Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1283  
      Object main = newInstance(ecjClass, printWriter, printWriter, false);
1284  
      call(main, "compile", new Object[]{args});
1285  
      int errors = (Integer) get(main, "globalErrorsCount");
1286  
1287  
      String output = writer.toString();
1288  
      if (errors != 0) {
1289  
        System.out.println(output);
1290  
        throw new RuntimeException("Java compiler returned errors.");
1291  
      }
1292  
      return output;
1293  
    } catch (Exception e) {
1294  
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
1295  
    }
1296  
  }
1297  
1298  
  static Object get(Object o, String field) {
1299  
    try {
1300  
      Field f = findField(o.getClass(), field);
1301  
      f.setAccessible(true);
1302  
      return f.get(o);
1303  
    } catch (Exception e) {
1304  
      throw new RuntimeException(e);
1305  
    }
1306  
  }
1307  
1308  
  static Object newInstance(Class c, Object... args) { try {
1309  
    Constructor m = findConstructor(c, args);
1310  
    m.setAccessible(true);
1311  
    return m.newInstance(args);
1312  
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
1313  
1314  
  static Constructor findConstructor(Class c, Object... args) {
1315  
    for (Constructor m : c.getDeclaredConstructors()) {
1316  
      if (!checkArgs(m.getParameterTypes(), args, verbose))
1317  
        continue;
1318  
      return m;
1319  
    }
1320  
    throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
1321  
  }
1322  
1323  
  static boolean checkArgs(Class[] types, Object[] args, boolean debug) {
1324  
    if (types.length != args.length) {
1325  
      if (debug)
1326  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
1327  
      return false;
1328  
    }
1329  
    for (int i = 0; i < types.length; i++)
1330  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
1331  
        if (debug)
1332  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
1333  
        return false;
1334  
      }
1335  
    return true;
1336  
  }
1337  
1338  
  // extended to handle primitive types
1339  
  private static boolean isInstanceX(Class type, Object arg) {
1340  
    if (type == boolean.class) return arg instanceof Boolean;
1341  
    if (type == int.class) return arg instanceof Integer;
1342  
    if (type == long.class) return arg instanceof Long;
1343  
    if (type == float.class) return arg instanceof Float;
1344  
    if (type == short.class) return arg instanceof Short;
1345  
    if (type == char.class) return arg instanceof Character;
1346  
    if (type == byte.class) return arg instanceof Byte;
1347  
    return type.isInstance(arg);
1348  
  }
1349  
1350  
  private static void writeOptions(List<File> sources, List<File> libraries,
1351  
                                   File optionsFile, String moreOptions) throws IOException {
1352  
    FileWriter writer = new FileWriter(optionsFile);
1353  
    for (File source : sources)
1354  
      writer.write(bashQuote(source.getPath()) + " ");
1355  
    if (!libraries.isEmpty()) {
1356  
      List<String> cp = new ArrayList<String>();
1357  
      for (File lib : libraries)
1358  
        cp.add(lib.getAbsolutePath());
1359  
      writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
1360  
    }
1361  
    writer.write(moreOptions);
1362  
    writer.close();
1363  
  }
1364  
1365  
  static void scanForSources(File source, List<File> sources, boolean topLevel) {
1366  
    if (source.isFile() && source.getName().endsWith(".java"))
1367  
      sources.add(source);
1368  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
1369  
      File[] files = source.listFiles();
1370  
      for (File file : files)
1371  
        scanForSources(file, sources, false);
1372  
    }
1373  
  }
1374  
1375  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
1376  
    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.)
1377  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
1378  
  }
1379  
1380  
  static int exitValue;
1381  
  public static String backtick(String cmd) throws IOException {
1382  
    ++processesStarted;
1383  
    File outFile = File.createTempFile("_backtick", "");
1384  
    File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
1385  
1386  
    String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1";
1387  
    //Log.info("[Backtick] " + command);
1388  
    try {
1389  
      saveTextFile(scriptFile.getPath(), command);
1390  
      String[] command2;
1391  
      if (isWindows())
1392  
        command2 = new String[] { scriptFile.getPath() };
1393  
      else
1394  
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
1395  
      Process process = Runtime.getRuntime().exec(command2);
1396  
      try {
1397  
        process.waitFor();
1398  
      } catch (InterruptedException e) {
1399  
        throw new RuntimeException(e);
1400  
      }
1401  
      exitValue = process.exitValue();
1402  
      if (verbose)
1403  
        System.out.println("Process return code: " + exitValue);
1404  
      return loadTextFile(outFile.getPath(), "");
1405  
    } finally {
1406  
      scriptFile.delete();
1407  
    }
1408  
  }
1409  
1410  
  /** possibly improvable */
1411  
  public static String javaQuote(String text) {
1412  
    return bashQuote(text);
1413  
  }
1414  
1415  
  /** possibly improvable */
1416  
  public static String bashQuote(String text) {
1417  
    if (text == null) return null;
1418  
    return "\"" + text
1419  
      .replace("\\", "\\\\")
1420  
      .replace("\"", "\\\"")
1421  
      .replace("\n", "\\n")
1422  
      .replace("\r", "\\r") + "\"";
1423  
  }
1424  
1425  
  public final static String charsetForTextFiles = "UTF8";
1426  
1427  
  static long TempDirMaker_lastValue;
1428  
1429  
  public static File TempDirMaker_make() {
1430  
    File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue());
1431  
    dir.mkdirs();
1432  
    return dir;
1433  
  }
1434  
1435  
  private static long TempDirMaker_newValue() {
1436  
    long value;
1437  
    do
1438  
      value = System.currentTimeMillis();
1439  
    while (value == TempDirMaker_lastValue);
1440  
    TempDirMaker_lastValue = value;
1441  
    return value;
1442  
  }
1443  
1444  
  public static String join(String glue, Iterable<String> strings) {
1445  
    StringBuilder buf = new StringBuilder();
1446  
    Iterator<String> i = strings.iterator();
1447  
    if (i.hasNext()) {
1448  
      buf.append(i.next());
1449  
      while (i.hasNext())
1450  
        buf.append(glue).append(i.next());
1451  
    }
1452  
    return buf.toString();
1453  
  }
1454  
1455  
  public static boolean isWindows() {
1456  
    return System.getProperty("os.name").contains("Windows");
1457  
  }
1458  
1459  
  public static String makeRandomID(int length) {
1460  
    Random random = new Random();
1461  
    char[] id = new char[length];
1462  
    for (int i = 0; i< id.length; i++)
1463  
      id[i] = (char) ((int) 'a' + random.nextInt(26));
1464  
    return new String(id);
1465  
  }
1466  
1467  
  static String computerID;
1468  
  public static String getComputerID() throws IOException {
1469  
    if (noID) return null;
1470  
    if (computerID == null) {
1471  
      File file = new File(userHome(), ".tinybrain/computer-id");
1472  
      computerID = loadTextFile(file.getPath(), null);
1473  
      if (computerID == null) {
1474  
        computerID = makeRandomID(12);
1475  
        saveTextFile(file.getPath(), computerID);
1476  
      }
1477  
      if (verbose)
1478  
        System.out.println("Local computer ID: " + computerID);
1479  
    }
1480  
    return computerID;
1481  
  }
1482  
1483  
  static int fileDeletions;
1484  
1485  
  static void cleanCache() {
1486  
    if (verbose)
1487  
      System.out.println("Cleaning cache");
1488  
    fileDeletions = 0;
1489  
    File javax = new File(userHome(), ".javax");
1490  
    long now = System.currentTimeMillis();
1491  
    File[] files = javax.listFiles();
1492  
    if (files != null) for (File dir : files) {
1493  
      if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) {
1494  
        long time = Long.parseLong(dir.getName());
1495  
        long seconds = (now - time) / 1000;
1496  
        long minutes = seconds / 60;
1497  
        long hours = minutes / 60;
1498  
        if (hours >= 1) {
1499  
          //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
1500  
          removeDir(dir);
1501  
        }
1502  
      }
1503  
    }
1504  
    if (verbose && fileDeletions != 0)
1505  
      System.out.println("Cleaned cache. File deletions: " + fileDeletions);
1506  
  }
1507  
1508  
  static void removeDir(File dir) {
1509  
    if (dir.getAbsolutePath().indexOf(".javax") < 0)  // security check!
1510  
      return;
1511  
    for (File f : dir.listFiles()) {
1512  
      if (f.isDirectory())
1513  
        removeDir(f);
1514  
      else {
1515  
        if (verbose)
1516  
          System.out.println("Deleting " + f.getAbsolutePath());
1517  
        f.delete();
1518  
        ++fileDeletions;
1519  
      }
1520  
    }
1521  
    dir.delete();
1522  
  }
1523  
1524  
  static void showSystemProperties() {
1525  
    System.out.println("System properties:\n");
1526  
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1527  
      System.out.println("  " + entry.getKey() + " = " + entry.getValue());
1528  
    }
1529  
    System.out.println();
1530  
  }
1531  
1532  
  static void showVersion() {
1533  
    //showSystemProperties();
1534  
    boolean eclipseFound = hasEcj();
1535  
    //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version");
1536  
    String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version");
1537  
    String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
1538  
    System.out.println("This is " + version + ".");
1539  
    System.out.println("[Details: " +
1540  
      (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)")
1541  
      + ", " + platform + ", " + arch + ", " + os + "]");
1542  
  }
1543  
1544  
  static boolean isAndroid() {
1545  
    return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0;
1546  
  }
1547  
1548  
  static void set(Class c, String field, Object value) {
1549  
    try {
1550  
      Field f = findStaticField(c, field);
1551  
      f.setAccessible(true);
1552  
      f.set(null, value);
1553  
    } catch (Exception e) {
1554  
      throw new RuntimeException(e);
1555  
    }
1556  
  }
1557  
1558  
  static Field findStaticField(Class<?> c, String field) {
1559  
    for (Field f : c.getDeclaredFields())
1560  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
1561  
        return f;
1562  
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
1563  
  }
1564  
1565  
  static Field findField(Class<?> c, String field) {
1566  
    for (Field f : c.getDeclaredFields())
1567  
      if (f.getName().equals(field))
1568  
        return f;
1569  
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
1570  
  }
1571  
}

download  show line numbers  debug dex  old transpilations   

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

Comments [hide]

ID Author/Program Comment Date
385 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #1000572
Snippet name: _javax.java (JavaX 19)
Eternal ID of this version: #1000572/1
Text MD5: 6d5d4cb194c6d449955c0ae5f92522f7
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-09-03 23:49:40
Source code size: 57511 bytes / 1571 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1061 / 2442
Referenced in: [show references]