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

1200
LINES

< > BotCompany Repo | #2000496 // _x18.java (JavaX 18, embeddable, fixed 3)

New Tinybrain snippet

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

Author comment

Began life as a copy of #2000494

download  show line numbers   

Snippet is not live.

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

Comments [hide]

ID Author/Program Comment Date
866 #1000610 Edit suggestion:
!636
!629

main {
static Object androidContext;
static String programID;

public static void main(String[] args) throws Exception {
/**
JavaX runner version 18

Changes to v17:
-can run server-transpiled main programs for super-quick compilation
(no local transpiling except for nested solvers or something)

*/

class _x18 {
static final String version = "JavaX 18";

static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
static String translateTo = null;
static boolean preferCached = false, safeOnly = false, noID = false, noPrefetch = false;
static List<String[]> mainTranslators = new ArrayList<String[]>();
private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
private static int processesStarted, compilations;

// snippet ID -> md5
private static HashMap<Long, String> prefetched = new HashMap<Long, String>();
private static File virtCache;

// doesn't work yet
private static Map<String, Class<?>> programCache = new HashMap<String, Class<?>>();
static boolean cacheTranslators = false;

// this should work (caches transpiled translators)
private static HashMap<Long, Object[]> translationCache = new HashMap<Long, Object[]>();
static boolean cacheTranspiledTranslators = true;

// which snippets are available pre-transpiled server-side?
private static Set<Long> hasTranspiledSet = new HashSet<Long>();
static boolean useServerTranspiled = true;

public static void main(String[] args) throws Exception {
File ioBaseDir = new File("."), inputDir = null, outputDir = null;
String src = null;
List<String> programArgs = new ArrayList<String>();

for (int i = 0; i < args.length; i++) {
String arg = args[i];

if (arg.equals("-version")) {
showVersion();
return;
}

if (arg.equals("-sysprop")) {
showSystemProperties();
return;
}

if (arg.equals("-v") || arg.equals("-verbose"))
verbose = true;
else if (arg.equals("-finderror"))
verbose = true;
else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
preferCached = true;
else if (arg.equals("-novirt"))
virtualizeTranslators = false;
else if (arg.equals("-safeonly"))
safeOnly = true;
else if (arg.equals("-noid"))
noID = true;
else if (arg.equals("-nocachetranspiled"))
cacheTranspiledTranslators = false;
else if (arg.equals("-localtranspile"))
useServerTranspiled = false;
else if (arg.equals("translate"))
translate = true;
else if (arg.equals("list")) {
list = true;
virtualizeTranslators = false; // so they are silenced
} else if (arg.equals("run")) {
// it's the default command anyway
} else if (arg.startsWith("input="))
inputDir = new File(arg.substring(6));
else if (arg.startsWith("output="))
outputDir = new File(arg.substring(7));
else if (arg.equals("with"))
mainTranslators.add(new String[] {args[++i], null});
else if (translate && arg.equals("to"))
translateTo = args[++i];
else if (src == null) {
//System.out.println("src=" + arg);
src = arg;
} else
programArgs.add(arg);
}

cleanCache();

if (useServerTranspiled)
noPrefetch = true;

if (src == null) src = ".";

// Might actually want to write to 2 disk caches (global/per program).
if (virtualizeTranslators && !preferCached)
virtCache = TempDirMaker_make();

if (inputDir != null) {
ioBaseDir = TempDirMaker_make();
System.out.println("Taking input from: " + inputDir.getAbsolutePath());
System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
copyInput(inputDir, new File(ioBaseDir, "input"));
}

javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()]));

if (outputDir != null) {
copyInput(new File(ioBaseDir, "output"), outputDir);
System.out.println("Output copied to: " + outputDir.getAbsolutePath());
}

if (verbose) {
// print stats
System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations);
}
}

public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
String[] args) throws Exception {
List<File> libraries = new ArrayList<File>();
File X = transpileMain(src, libraries);
if (X == null)
return;

// list or run

if (translate) {
File to = X;
if (translateTo != null)
if (new File(translateTo).isDirectory())
to = new File(translateTo, "main.java");
else
to = new File(translateTo);
if (to != X)
copy(new File(X, "main.java"), to);
System.out.println("Program translated to: " + to.getAbsolutePath());
} else if (list)
System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
else
javax2(X, ioDir, false, false, libraries, args, null);
}

static File transpileMain(String src, List<File> libraries) throws Exception {
File srcDir;
boolean isTranspiled = false;
if (isSnippetID(src)) {
prefetch(src);
long id = parseSnippetID(src);
srcDir = loadSnippetAsMainJava(src);
if (hasTranspiledSet.contains(id)) {
System.err.println("Trying pretranspiled main program: #" + id);
String transpiledSrc = getServerTranspiled("#" + id);
if (!transpiledSrc.isEmpty()) {
srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
isTranspiled = true;
//translationCache.put(id, new Object[] {srcDir, libraries});
}
}
} else {
srcDir = new File(src);

// if the argument is a file, it is assumed to be main.java
if (srcDir.isFile()) {
srcDir = TempDirMaker_make();
copy(new File(src), new File(srcDir, "main.java"));
}

if (!new File(srcDir, "main.java").exists()) {
showVersion();
System.out.println("No main.java found, exiting");
return null;
}
}

// translate

File X = srcDir;

if (!isTranspiled) {
X = topLevelTranslate(X, libraries);
System.err.println("Translated " + src);

// save prefetch data
if (isSnippetID(src))
savePrefetchData(src);
}
return X;
}

private static void prefetch(String mainSnippetID) throws IOException {
if (noPrefetch) return;

long mainID = parseSnippetID(mainSnippetID);
String s = mainID + " " + loadTextFile(new File(System.getProperty("user.home"), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), "");
String[] ids = s.trim().split(" ");
if (ids.length > 1) {
String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8");
String data = loadPage(new URL(url));
String[] split = data.split(" ");
if (split.length == ids.length)
for (int i = 0; i < ids.length; i++)
prefetched.put(parseSnippetID(ids[i]), split[i]);
}
}

private static void savePrefetchData(String mainSnippetID) throws IOException {
List<String> ids = new ArrayList<String>();
long mainID = parseSnippetID(mainSnippetID);

for (long id : memSnippetCache.keySet())
if (id != mainID)
ids.add(String.valueOf(id));

saveTextFile(new File(System.getProperty("user.home"),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids));
}

static File topLevelTranslate(File srcDir, List<File> libraries_out) throws Exception {
File X = srcDir;
X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual)

// actual inner translation of the JavaX source
X = defaultTranslate(X, libraries_out);
return X;
}

private static File defaultTranslate(File x, List<File> libraries_out) throws Exception {
x = luaPrintToJavaPrint(x);
x = repeatAutoTranslate(x, libraries_out);
return x;
}

private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception {
while (true) {
File y = autoTranslate(x, libraries_out);
if (y == x)
return x;
x = y;
}
}

private static File autoTranslate(File x, List<File> libraries_out) throws Exception {
String main = loadTextFile(new File(x, "main.java").getPath(), null);
List<String> lines = toLines(main);
List<String[]> translators = findTranslators(lines);
if (translators.isEmpty())
return x;

main = fromLines(lines);
File newDir = TempDirMaker_make();
saveTextFile(new File(newDir, "main.java").getPath(), main);
return applyTranslators(newDir, translators, libraries_out);
}

private static List<String[]> findTranslators(List<String> lines) {
List<String[]> translators = new ArrayList<String[]>();
Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
String line = iterator.next();
line = line.trim();
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String[] t = matcher.group(1).split("[ \t]+");
String rest = line.substring(matcher.end());
String arg = null;
if (t.length == 1) {
Matcher mArgs = pArgs.matcher(rest);
if (mArgs.find())
arg = mArgs.group(1);
}
for (String transi : t)
translators.add(new String[]{transi, arg});
iterator.remove();
}
}
return translators;
}

public static List<String> toLines(String s) {
List<String> lines = new ArrayList<String>();
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}

lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;

start = i;
}
return lines;
}

private static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}

public static String fromLines(List<String> lines) {
StringBuilder buf = new StringBuilder();
for (String line : lines) {
buf.append(line).append('\n');
}
return buf.toString();
}

private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception {
for (String[] translator : translators)
x = applyTranslator(x, translator[0], translator[1], libraries_out);
return x;
}

// also takes a library
private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception {
if (verbose)
System.out.println("Using translator " + translator + " on sources in " + x.getPath());

File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out);

if (!new File(newDir, "main.java").exists()) {
throw new Exception("Translator " + translator + " did not generate main.java");
// TODO: show translator output
}
if (verbose)
System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
x = newDir;
return x;
}

private static File luaPrintToJavaPrint(File x) throws IOException {
File newDir = TempDirMaker_make();
String code = loadTextFile(new File(x, "main.java").getPath(), null);
code = luaPrintToJavaPrint(code);
if (verbose)
System.out.println(code);
saveTextFile(new File(newDir, "main.java").getPath(), code);
return newDir;
}

public static String luaPrintToJavaPrint(String code) {
return ("\n" + code).replaceAll(
"(\n\\s*)print (\".*\")",
"$1System.out.println($2);").substring(1);
}

public static File loadSnippetAsMainJava(String snippetID) throws IOException {
checkProgramSafety(snippetID);
File srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
return srcDir;
}

public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
checkProgramSafety(snippetID);
File srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
return srcDir;
}

/** returns output dir */
private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
boolean silent,
List<File> libraries_out) throws Exception {
long id = parseSnippetID(snippetID);
File libraryFile = DiskSnippetCache_getLibrary(id);
if (libraryFile != null) {
loadLibrary(snippetID, libraries_out, libraryFile);
return input;
}

String[] args = arg != null ? new String[]{arg} : new String[0];

File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
: loadSnippetAsMainJavaVerified(snippetID, hash);
long mainJavaSize = new File(srcDir, "main.java").length();

if (mainJavaSize == 0) { // no text in snippet? assume it's a library
loadLibrary(snippetID, libraries_out, libraryFile);
return input;
}

List<File> libraries = new ArrayList<File>();
Object[] cached = translationCache.get(id);
if (cached != null) {
//System.err.println("Taking translator " + snippetID + " from cache!");
srcDir = (File) cached[0];
libraries = (List<File>) cached[1];
} else if (hasTranspiledSet.contains(id)) {
System.err.println("Trying pretranspiled translator: #" + snippetID);
String transpiledSrc = getServerTranspiled(snippetID);
if (!transpiledSrc.isEmpty()) {
srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
translationCache.put(id, cached = new Object[] {srcDir, libraries});
}
}

File ioBaseDir = TempDirMaker_make();

/*Class<?> mainClass = programCache.get("" + parseSnippetID(snippetID));
if (mainClass != null)
return runCached(ioBaseDir, input, args);*/
// Doesn't work yet because virtualized directories are hardcoded in translator...

if (cached == null) {
System.err.println("Translating translator #" + id);
srcDir = defaultTranslate(srcDir, libraries);
System.err.println("Translated translator #" + id);
if (cacheTranspiledTranslators)
translationCache.put(id, new Object[]{srcDir, libraries});
}

boolean runInProcess = false;

if (virtualizeTranslators) {
if (verbose) System.out.println("Virtualizing translator");

//srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
// that doesn't work because it recurses infinitely...

// So we do it right here:
String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
s += "\n\n" + loadSnippet("#2000355"); // load class virtual

// change baseDir
s = s.replace("virtual_baseDir = \"\";",
"virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";");

// forward snippet cache (virtualized one)
File dir = virtCache != null ? virtCache : DiskSnippetCache_dir;
s = s.replace("static File DiskSnippetCache_dir;",
"static File DiskSnippetCache_dir = new File(" + javaQuote(dir.getAbsolutePath()) + ");");
s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");

if (verbose) {
System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
System.out.println(s);
System.out.println("==END VIRTUALIZED TRANSLATOR==");
}
srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), s);

// TODO: silence translator also
runInProcess = true;
}

return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries,
args, cacheTranslators ? "" + id : null);
}

private static String getServerTranspiled(String snippetID) throws IOException {
long id = parseSnippetID(snippetID);
URL url = new URL("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&id=" + id);
return loadPage(url);
}

static void checkProgramSafety(String snippetID) throws IOException {
if (!safeOnly) return;
URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID));
String text = loadPage(url);
if (!text.startsWith("{\"safe\":\"1\"}"))
throw new RuntimeException("Translator not safe: #" + parseSnippetID(snippetID));
}

private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException {
if (verbose)
System.out.println("Assuming " + snippetID + " is a library.");

if (libraryFile == null) {
byte[] data = loadDataSnippetImpl(snippetID);
DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data);
libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
}

if (!libraries_out.contains(libraryFile))
libraries_out.add(libraryFile);
}

private static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ parseSnippetID(snippetID) + "&contentType=application/binary");
System.err.println("Loading library: " + url);
data = loadBinaryPage(url.openConnection());
if (verbose)
System.err.println("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}

/** returns output dir */
private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput,
boolean silent, boolean runInProcess,
List<File> libraries, String[] args, String cacheAs) throws Exception {
File srcDir = new File(ioBaseDir, "src");
File inputDir = new File(ioBaseDir, "input");
File outputDir = new File(ioBaseDir, "output");
copyInput(originalSrcDir, srcDir);
copyInput(originalInput, inputDir);
javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs);
return outputDir;
}

private static void copyInput(File src, File dst) throws IOException {
copyDirectory(src, dst);
}

public static boolean hasFile(File inputDir, String name) {
return new File(inputDir, name).exists();
}

public static void copyDirectory(File src, File dst) throws IOException {
if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
dst.mkdirs();
File[] files = src.listFiles();
if (files == null) return;
for (File file : files) {
File dst1 = new File(dst, file.getName());
if (file.isDirectory())
copyDirectory(file, dst1);
else {
if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
copy(file, dst1);
}
}
}

/** Quickly copy a file without a progress bar or any other fancy GUI... :) */
public static void copy(File src, File dest) throws IOException {
FileInputStream inputStream = new FileInputStream(src);
FileOutputStream outputStream = new FileOutputStream(dest);
try {
copy(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
}

public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
}
}

/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);

if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}

/** writes safely (to temp file, then rename) */
public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);

if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}

public static String loadTextFile(String fileName, String defaultContents) throws IOException {
if (!new File(fileName).exists())
return defaultContents;

FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
return loadTextFile(inputStreamReader, (int) new File(fileName).length());
}

public static String loadTextFile(Reader reader, int length) throws IOException {
try {
char[] chars = new char[length];
int n = reader.read(chars);
return new String(chars, 0, n);
} finally {
reader.close();
}
}

static File DiskSnippetCache_dir;

public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}

// Data files are immutable, use centralized cache
public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
if (verbose)
System.out.println("Checking data cache: " + file.getPath());
return file.exists() ? file : null;
}

public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}

private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}

public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}

public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
}

public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}

public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}

private static File getGlobalCache() {
File file = new File(System.getProperty("user.home"), ".tinybrain/snippet-cache");
file.mkdirs();
return file;
}

public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
String text = loadSnippet(snippetID);
String realHash = getHash(text.getBytes("UTF-8"));
if (!realHash.equals(hash)) {
String msg;
if (hash.isEmpty())
msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
else
msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
throw new RuntimeException(msg);
}
return text;
}

public static String getHash(byte[] data) {
return bytesToHex(getFullFingerprint(data));
}

public static byte[] getFullFingerprint(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}

public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}

public static String loadSnippet(String snippetID) throws IOException {
return loadSnippet(parseSnippetID(snippetID));
}

public static long parseSnippetID(String snippetID) {
return Long.parseLong(shortenSnippetID(snippetID));
}

private static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return snippetID;
}

public static boolean isSnippetID(String snippetID) {
snippetID = shortenSnippetID(snippetID);
return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
}

public static boolean isInteger(String s) {
return Pattern.matches("\\-?\\d+", s);
}

public static String loadSnippet(long snippetID) throws IOException {
String text = memSnippetCache.get(snippetID);
if (text != null)
return text;

initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;

String md5 = text != null ? md5(text) : "-";
if (text != null) {
String hash = prefetched.get(snippetID);
if (hash != null) {
if (md5.equals(hash)) {
memSnippetCache.put(snippetID, text);
return text;
} else
prefetched.remove(snippetID); // (maybe this is not necessary)
}
}

try {
/*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
text = loadPage(url);*/
String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1";
if (text != null) {
//System.err.println("MD5: " + md5);
theURL += "&md5=" + md5;
}
URL url = new URL(theURL);
String page = loadPage(url);

// parse & drop transpilation flag available line
int i = page.indexOf('\n');
boolean hasTranspiled = page.substring(0, i).trim().equals("1");
if (hasTranspiled)
hasTranspiledSet.add(snippetID);
else
hasTranspiledSet.remove(snippetID);
page = page.substring(i+1);

if (page.startsWith("==*#*==")) {
// same, keep text
//System.err.println("Snippet unchanged, keeping.");
} else {
// drop md5 line
i = page.indexOf('\n');
String hash = page.substring(0, i).trim();
text = page.substring(i+1);

String myHash = md5(text);
if (myHash.equals(hash)) {
//System.err.println("Hash match: " + hash);
} else
System.err.println("Hash mismatch");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}

memSnippetCache.put(snippetID, text);

try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}

return text;
}

private static String md5(String text) {
try {
return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

public static byte[] md5impl(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

private static String loadPage(URL url) throws IOException {
System.err.println("Loading: " + url.toExternalForm());
URLConnection con = url.openConnection();
return loadPage(con, url);
}

public static String loadPage(URLConnection con, URL url) throws IOException {
setHeaders(con);
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//Log.info("Content-Type: " + contentType);
String charset = guessCharset(contentType);
//System.err.println("Charset: " + charset);
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
//Log.info("Chars read: " + buf.length());
buf.append((char) ch);
}
return buf.toString();
}

public static byte[] loadBinaryPage(URLConnection con) throws IOException {
setHeaders(con);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
}
inputStream.close();
return buf.toByteArray();
}

private static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID();
if (computerID != null)
con.setRequestProperty("X-ComputerID", computerID);
}

public static String guessCharset(String contentType) {
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return m.matches() ? m.group(1) : "ISO-8859-1";
}

/** runs a transpiled set of sources */
public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess,
List<File> libraries, String[] args, String cacheAs) throws Exception {
File classesDir = TempDirMaker_make();
String javacOutput = compileJava(srcDir, libraries, classesDir);

// run

if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
+ ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs);
}

static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
++compilations;

// collect sources

List<File> sources = new ArrayList<File>();
if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
scanForSources(srcDir, sources, true);
if (sources.isEmpty())
throw new IOException("No sources found");

// compile

File optionsFile = File.createTempFile("javax", "");
if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
String options = "-d " + bashQuote(classesDir.getPath());
writeOptions(sources, libraries, optionsFile, options);
classesDir.mkdirs();
return invokeJavac(optionsFile);
}

private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
boolean silent, boolean runInProcess,
List<File> libraries, String[] args, String cacheAs) throws Exception {
// print javac output if compile failed and it hasn't been printed yet
boolean didNotCompile = !didCompile(classesDir);
if (verbose || didNotCompile)
System.out.println(javacOutput);
if (didNotCompile)
return;

if (runInProcess
|| (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
runProgramQuick(classesDir, libraries, args, cacheAs);
return;
}

boolean echoOK = false;
// TODO: add libraries to class path
String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
+ bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
if (verbose) System.out.println(bashCmd);
String output = backtick(bashCmd);
if (verbose || !silent)
System.out.println(output);
}

static boolean didCompile(File classesDir) {
return hasFile(classesDir, "main.class");
}

private static void runProgramQuick(File classesDir, List<File> libraries,
String[] args, String cacheAs) throws Exception {
// collect urls
URL[] urls = new URL[libraries.size()+1];
urls[0] = classesDir.toURI().toURL();
for (int i = 0; i < libraries.size(); i++)
urls[i+1] = libraries.get(i).toURI().toURL();

// make class loader
URLClassLoader classLoader = new URLClassLoader(urls);

// load JavaX main class
Class<?> mainClass = classLoader.loadClass("main");

if (cacheAs != null)
programCache.put(cacheAs, mainClass);

// run main method
Method main = mainClass.getMethod("main", String[].class);
main.invoke(null, (Object) args);
}

private static String invokeJavac(File optionsFile) throws IOException {
String output;
try {
output = invokeEcj(optionsFile);
} catch (Exception e) {
if (verbose) {
System.err.println("ecj not found or misconfigured - using javac");
e.printStackTrace();
}
output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
}
if (verbose) System.out.println(output);
return output;
}

// throws ClassNotFoundException if ecj is not in classpath
static String invokeEcj(File optionsFile) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class batchCompiler = getEclipseCompiler();

StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);

// add more eclipse options in the line below

String[] args = { "@" + optionsFile.getPath(),
"-source", "1.7",
"-nowarn"
};
Method compile = batchCompiler.getDeclaredMethod("compile", args.getClass(), PrintWriter.class, PrintWriter.class,
Class.forName("org.eclipse.jdt.core.compiler.CompilationProgress"));
compile.invoke(null, args, printWriter, printWriter, null);
return writer.toString();
}

private static Class<?> getEclipseCompiler() throws ClassNotFoundException {
return Class.forName("org.eclipse.jdt.core.compiler.batch.BatchCompiler");
}

private static void writeOptions(List<File> sources, List<File> libraries,
File optionsFile, String moreOptions) throws IOException {
FileWriter writer = new FileWriter(optionsFile);
for (File source : sources)
writer.write(bashQuote(source.getPath()) + " ");
if (!libraries.isEmpty()) {
List<String> cp = new ArrayList<String>();
for (File lib : libraries)
cp.add(lib.getAbsolutePath());
writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
}
writer.write(moreOptions);
writer.close();
}

static void scanForSources(File source, List<File> sources, boolean topLevel) {
if (source.isFile() && source.getName().endsWith(".java"))
sources.add(source);
else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
File[] files = source.listFiles();
for (File file : files)
scanForSources(file, sources, false);
}
}

private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
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.)
return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
}

public static String backtick(String cmd) throws IOException {
++processesStarted;
File outFile = File.createTempFile("_backtick", "");
File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");

String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1";
//Log.info("[Backtick] " + command);
try {
saveTextFile(scriptFile.getPath(), command);
String[] command2;
if (isWindows())
command2 = new String[] { scriptFile.getPath() };
else
command2 = new String[] { "/bin/bash", scriptFile.getPath() };
Process process = Runtime.getRuntime().exec(command2);
try {
process.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
process.exitValue();
return loadTextFile(outFile.getPath(), "");
} finally {
scriptFile.delete();
}
}

/** possibly improvable */
public static String javaQuote(String text) {
return bashQuote(text);
}

/** possibly improvable */
public static String bashQuote(String text) {
if (text == null) return null;
return "\"" + text
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r") + "\"";
}

public final static String charsetForTextFiles = "UTF8";

static long TempDirMaker_lastValue;

public static File TempDirMaker_make() {
File dir = new File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue());
dir.mkdirs();
return dir;
}

private static long TempDirMaker_newValue() {
long value;
do
value = System.currentTimeMillis();
while (value == TempDirMaker_lastValue);
TempDirMaker_lastValue = value;
return value;
}

public static String join(String glue, Iterable<String> strings) {
StringBuilder buf = new StringBuilder();
Iterator<String> i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}

public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}

public static String makeRandomID(int length) {
Random random = new Random();
char[] id = new char[length];
for (int i = 0; i< id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}

static String computerID;
public static String getComputerID() throws IOException {
if (noID) return null;
if (computerID == null) {
File file = new File(System.getProperty("user.home"), ".tinybrain/computer-id");
computerID = loadTextFile(file.getPath(), null);
if (computerID == null) {
computerID = makeRandomID(12);
saveTextFile(file.getPath(), computerID);
}
if (verbose)
System.out.println("Local computer ID: " + computerID);
}
return computerID;
}

static int fileDeletions;

static void cleanCache() {
if (verbose)
System.out.println("Cleaning cache");
fileDeletions = 0;
File javax = new File(System.getProperty("user.home"), ".javax");
long now = System.currentTimeMillis();
File[] files = javax.listFiles();
if (files != null) for (File dir : files) {
if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) {
long time = Long.parseLong(dir.getName());
long seconds = (now - time) / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
if (hours >= 1) {
//System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
removeDir(dir);
}
}
}
if (verbose && fileDeletions != 0)
System.out.println("Cleaned cache. File deletions: " + fileDeletions);
}

static void removeDir(File dir) {
if (dir.getAbsolutePath().indexOf(".javax") < 0) // security check!
return;
for (File f : dir.listFiles()) {
if (f.isDirectory())
removeDir(f);
else {
if (verbose)
System.out.println("Deleting " + f.getAbsolutePath());
f.delete();
++fileDeletions;
}
}
dir.delete();
}

static void showSystemProperties() {
System.out.println("System properties:\n");
for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
System.out.println(" " + entry.getKey() + " = " + entry.getValue());
}
System.out.println();
}

static void showVersion() {
//showSystemProperties();
boolean eclipseFound = hasEclipseCompiler();
//String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version");
String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version");
String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
System.out.println("This is " + version + ".");
System.out.println("[Details: " +
(eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)")
+ ", " + platform + ", " + arch + ", " + os + "]");
}

private static boolean hasEclipseCompiler() {
boolean compilerFound = false;
try { getEclipseCompiler(); compilerFound = true; } catch (ClassNotFoundException e) {}
return compilerFound;
}
}

}}
2015-08-19 22:48:24  delete 
792 #1000604 (pitcher) 2015-08-18 00:07:22

add comment

Snippet ID: #2000496
Snippet name: _x18.java (JavaX 18, embeddable, fixed 3)
Eternal ID of this version: #2000496/1
Text MD5: 731b0488134ae0869230e319f397c7ae
Author: stefan
Category:
Type: New Tinybrain snippet
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 01:51:03
Source code size: 43828 bytes / 1200 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 856 / 375
Referenced in: [show references]