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

1193
LINES

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

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

download  show line numbers   

Snippet is not live.

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

No comments. add comment

Snippet ID: #2000493
Snippet name: _x18.java (JavaX 18, embeddable)
Eternal ID of this version: #2000493/1
Text MD5: 0cb07b3b443d7ff047944eeeb2ace13e
Author: stefan
Category:
Type: New Tinybrain snippet
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 01:33:13
Source code size: 43635 bytes / 1193 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 564 / 138
Referenced in: [show references]