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

1445
LINES

< > BotCompany Repo | #1000571 // _x18.java, final merged

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

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: #1000571
Snippet name: _x18.java, final merged
Eternal ID of this version: #1000571/1
Text MD5: b57b12472b327dee3358fa08f1150eb3
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-14 22:14:20
Source code size: 53040 bytes / 1445 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 676 / 1014
Referenced in: [show references]