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

1424
LINES

< > BotCompany Repo | #2000501 // _x18.java (modified for Android, copied from #676)

New Tinybrain snippet

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

Author comment

Began life as a copy of #2000500

download  show line numbers   

Snippet is not live.

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

No comments. add comment

Snippet ID: #2000501
Snippet name: _x18.java (modified for Android, copied from #676)
Eternal ID of this version: #2000501/1
Text MD5: 56527527c6b95e24829b1b6ce68b9809
Author: stefan
Category:
Type: New Tinybrain snippet
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-07 18:31:59
Source code size: 52017 bytes / 1424 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 587 / 104
Referenced in: [show references]