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

1338
LINES

< > BotCompany Repo | #1000434 // _x18.java (modifying for Android)

JavaX fragment (include)

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

Author comment

Began life as a copy of #2000496

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

No comments. add comment

Snippet ID: #1000434
Snippet name: _x18.java (modifying for Android)
Eternal ID of this version: #1000434/1
Text MD5: 216ba564cee73c118ae873cabe321fbc
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-06 00:36:13
Source code size: 48951 bytes / 1338 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 564 / 539
Referenced in: [show references]