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

845
LINES

< > BotCompany Repo | #2000389 // class x14 (embeddable)

New Tinybrain snippet

1  
/**
2  
 JavaX runner version 14, embeddable.
3  
*/
4  
5  
class _x14 {
6  
  static final String version = "JavaX 14";
7  
8  
  static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
9  
  static boolean preferCached = false;
10  
  static List<String[]> mainTranslators = new ArrayList<String[]>();
11  
  private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
12  
  private static int processesStarted;
13  
14  
  public static void main(String[] args) throws Exception {
15  
    File ioBaseDir = new File("."), inputDir = null, outputDir = null;
16  
    String src = null;
17  
    List<String> programArgs = new ArrayList<String>();
18  
19  
    for (int i = 0; i < args.length; i++) {
20  
      String arg = args[i];
21  
      if (arg.equals("-v") || arg.equals("-verbose"))
22  
        verbose = true;
23  
      else if (arg.equals("-finderror"))
24  
        verbose = true;
25  
      else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
26  
        preferCached = true;
27  
      else if (arg.equals("-novirt"))
28  
        virtualizeTranslators = false;
29  
      else if (arg.equals("translate"))
30  
        translate = true;
31  
      else if (arg.equals("list"))
32  
        list = true;
33  
      else if (arg.equals("run")) {
34  
        // it's the default command anyway
35  
      } else if (arg.startsWith("input="))
36  
        inputDir = new File(arg.substring(6));
37  
      else if (arg.startsWith("output="))
38  
        outputDir = new File(arg.substring(7));
39  
      else if (arg.equals("with"))
40  
        mainTranslators.add(new String[] {args[++i], null});
41  
      else if (src == null)
42  
        src = arg;
43  
      else
44  
        programArgs.add(arg);
45  
    }
46  
47  
    if (src == null) src = ".";
48  
49  
    if (virtualizeTranslators && !preferCached)
50  
      initDiskSnippetCache(TempDirMaker_make());
51  
52  
    if (inputDir != null) {
53  
      ioBaseDir = TempDirMaker_make();
54  
      System.out.println("Taking input from: " + inputDir.getAbsolutePath());
55  
      System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
56  
      copyInput(inputDir, new File(ioBaseDir, "input"));
57  
    }
58  
59  
    javax4(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()]));
60  
61  
    if (outputDir != null) {
62  
      copyInput(new File(ioBaseDir, "output"), outputDir);
63  
      System.out.println("Output copied to: " + outputDir.getAbsolutePath());
64  
    }
65  
66  
    if (verbose)
67  
      System.out.println("Processes started: " + processesStarted);
68  
  }
69  
70  
  public static void javax4(String src, File ioDir, boolean translate, boolean list,
71  
                            String[] args) throws Exception {
72  
    File srcDir;
73  
    if (isSnippetID(src))
74  
      srcDir = loadSnippetAsMainJava(src);
75  
    else {
76  
      srcDir = new File(src);
77  
      if (!new File(srcDir, "main.java").exists()) {
78  
        System.out.println("This is " + version  + ".\n" +
79  
          "No main.java found, exiting");
80  
        return;
81  
      }
82  
    }
83  
84  
    // translate
85  
86  
    List<File> libraries = new ArrayList<File>();
87  
    File X = srcDir;
88  
    X = applyTranslators(X, mainTranslators, libraries);
89  
    X = defaultTranslate(X, libraries);
90  
91  
    // list or run
92  
93  
    if (translate)
94  
      System.out.println("Program translated to: " + X.getAbsolutePath());
95  
    else if (list)
96  
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
97  
    else
98  
      javax2(X, ioDir, false, false, libraries, args);
99  
  }
100  
101  
  private static File defaultTranslate(File x, List<File> libraries_out) throws Exception {
102  
    x = luaPrintToJavaPrint(x);
103  
    x = repeatAutoTranslate(x, libraries_out);
104  
    return x;
105  
  }
106  
107  
  private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception {
108  
    while (true) {
109  
      File y = autoTranslate(x, libraries_out);
110  
      if (y == x)
111  
        return x;
112  
      x = y;
113  
    }
114  
  }
115  
116  
  private static File autoTranslate(File x, List<File> libraries_out) throws Exception {
117  
    String main = loadTextFile(new File(x, "main.java").getPath(), null);
118  
    List<String> lines = toLines(main);
119  
    List<String[]> translators = findTranslators(lines);
120  
    if (translators.isEmpty())
121  
      return x;
122  
123  
    main = fromLines(lines);
124  
    File newDir = TempDirMaker_make();
125  
    saveTextFile(new File(newDir, "main.java").getPath(), main);
126  
    return applyTranslators(newDir, translators, libraries_out);
127  
  }
128  
129  
  private static List<String[]> findTranslators(List<String> lines) {
130  
    List<String[]> translators = new ArrayList<String[]>();
131  
    Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
132  
    Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
133  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
134  
      String line = iterator.next();
135  
      line = line.trim();
136  
      Matcher matcher = pattern.matcher(line);
137  
      if (matcher.find()) {
138  
        String[] t = matcher.group(1).split("[ \t]+");
139  
        String rest = line.substring(matcher.end());
140  
        String arg = null;
141  
        if (t.length == 1) {
142  
          Matcher mArgs = pArgs.matcher(rest);
143  
          if (mArgs.find())
144  
            arg = mArgs.group(1);
145  
        }
146  
        for (String transi : t)
147  
          translators.add(new String[]{transi, arg});
148  
        iterator.remove();
149  
      }
150  
    }
151  
    return translators;
152  
  }
153  
154  
  public static List<String> toLines(String s) {
155  
    List<String> lines = new ArrayList<String>();
156  
    int start = 0;
157  
    while (true) {
158  
      int i = toLines_nextLineBreak(s, start);
159  
      if (i < 0) {
160  
        if (s.length() > start) lines.add(s.substring(start));
161  
        break;
162  
      }
163  
164  
      lines.add(s.substring(start, i));
165  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
166  
        i += 2;
167  
      else
168  
        ++i;
169  
170  
      start = i;
171  
    }
172  
    return lines;
173  
  }
174  
175  
  private static int toLines_nextLineBreak(String s, int start) {
176  
    for (int i = start; i < s.length(); i++) {
177  
      char c = s.charAt(i);
178  
      if (c == '\r' || c == '\n')
179  
        return i;
180  
    }
181  
    return -1;
182  
  }
183  
184  
  public static String fromLines(List<String> lines) {
185  
    StringBuilder buf = new StringBuilder();
186  
    for (String line : lines) {
187  
      buf.append(line).append('\n');
188  
    }
189  
    return buf.toString();
190  
  }
191  
192  
  private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception {
193  
    for (String[] translator : translators)
194  
      x = applyTranslator(x, translator[0], translator[1], libraries_out);
195  
    return x;
196  
  }
197  
198  
  // also takes a library
199  
  private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception {
200  
    if (verbose)
201  
      System.out.println("Using translator " + translator + " on sources in " + x.getPath());
202  
203  
    File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out);
204  
205  
    if (!new File(newDir, "main.java").exists()) {
206  
      throw new Exception("Translator " + translator + " did not generate main.java");
207  
      // TODO: show translator output
208  
    }
209  
    if (verbose)
210  
      System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
211  
    x = newDir;
212  
    return x;
213  
  }
214  
215  
  private static File luaPrintToJavaPrint(File x) throws IOException {
216  
    File newDir = TempDirMaker_make();
217  
    String code = loadTextFile(new File(x, "main.java").getPath(), null);
218  
    code = luaPrintToJavaPrint(code);
219  
    if (verbose)
220  
      System.out.println(code);
221  
    saveTextFile(new File(newDir, "main.java").getPath(), code);
222  
    return newDir;
223  
  }
224  
225  
  public static String luaPrintToJavaPrint(String code) {
226  
    return ("\n" + code).replaceAll(
227  
      "(\n\\s*)print (\".*\")",
228  
      "$1System.out.println($2);").substring(1);
229  
  }
230  
231  
  public static File loadSnippetAsMainJava(String snippetID) throws IOException {
232  
    File srcDir = TempDirMaker_make();
233  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
234  
    return srcDir;
235  
  }
236  
237  
  public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
238  
    File srcDir = TempDirMaker_make();
239  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
240  
    return srcDir;
241  
  }
242  
243  
  /** returns output dir */
244  
  private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
245  
                                           boolean silent,
246  
                                           List<File> libraries_out) throws Exception {
247  
    File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
248  
    if (libraryFile != null) {
249  
      loadLibrary(snippetID, libraries_out, libraryFile);
250  
      return input;
251  
    }
252  
253  
    File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
254  
      : loadSnippetAsMainJavaVerified(snippetID, hash);
255  
256  
    long mainJavaSize = new File(srcDir, "main.java").length();
257  
258  
    if (mainJavaSize == 0) { // no text in snippet? assume it's a library
259  
      loadLibrary(snippetID, libraries_out, libraryFile);
260  
      return input;
261  
    }
262  
263  
    List<File> libraries = new ArrayList<File>();
264  
    srcDir = defaultTranslate(srcDir, libraries);
265  
    boolean runInProcess = false;
266  
    File ioBaseDir = TempDirMaker_make();
267  
268  
    if (virtualizeTranslators) {
269  
      if (verbose) System.out.println("Virtualizing translator");
270  
271  
      //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
272  
      // that doesn't work because it recurses infinitely...
273  
274  
      // So we do it right here:
275  
      String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
276  
      s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
277  
      s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
278  
      s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
279  
      s += "\n\n" + loadSnippet("#2000355"); // load class virtual
280  
281  
      // change baseDir
282  
      s = s.replace("virtual_baseDir = \"\";",
283  
        "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";");
284  
285  
      // forward snippet cache
286  
      s = s.replace("static File DiskSnippetCache_dir;",
287  
        "static File DiskSnippetCache_dir = new File(" + javaQuote(DiskSnippetCache_dir.getAbsolutePath()) + ");");
288  
      s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");
289  
290  
      if (verbose) {
291  
        System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
292  
        System.out.println(s);
293  
        System.out.println("==END VIRTUALIZED TRANSLATOR==");
294  
      }
295  
      saveTextFile(new File(srcDir, "main.java").getPath(), s);
296  
297  
      // TODO: silence translator also
298  
      runInProcess = true;
299  
    }
300  
301  
    return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries,
302  
      arg != null ? new String[] {arg} : new String[0]);
303  
  }
304  
305  
  private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException {
306  
    if (verbose)
307  
      System.out.println("Assuming " + snippetID + " is a library.");
308  
309  
    if (libraryFile == null) {
310  
      byte[] data;
311  
      try {
312  
        URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID)
313  
          + "&contentType=application/binary");
314  
        System.err.println("Loading library: " + url);
315  
        data = loadBinaryPage(url.openConnection(), url);
316  
        if (verbose)
317  
          System.err.println("Bytes loaded: " + data.length);
318  
      } catch (FileNotFoundException e) {
319  
        throw new IOException("Binary snippet #" + snippetID + " not found or not public");
320  
      }
321  
      DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data);
322  
      libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
323  
    }
324  
325  
    if (!libraries_out.contains(libraryFile))
326  
      libraries_out.add(libraryFile);
327  
  }
328  
329  
  /** returns output dir */
330  
  private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput,
331  
                               boolean silent, boolean runInProcess,
332  
                               List<File> libraries, String[] args) throws Exception {
333  
    File srcDir = new File(ioBaseDir, "src");
334  
    File inputDir = new File(ioBaseDir, "input");
335  
    File outputDir = new File(ioBaseDir, "output");
336  
    copyInput(originalSrcDir, srcDir);
337  
    copyInput(originalInput, inputDir);
338  
    javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args);
339  
    return outputDir;
340  
  }
341  
342  
  private static void copyInput(File src, File dst) throws IOException {
343  
    copyDirectory(src, dst);
344  
  }
345  
346  
  public static boolean hasFile(File inputDir, String name) {
347  
    return new File(inputDir, name).exists();
348  
  }
349  
350  
  public static void copyDirectory(File src, File dst) throws IOException {
351  
    if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
352  
    dst.mkdirs();
353  
    File[] files = src.listFiles();
354  
    if (files == null) return;
355  
    for (File file : files) {
356  
      File dst1 = new File(dst, file.getName());
357  
      if (file.isDirectory())
358  
        copyDirectory(file, dst1);
359  
      else {
360  
        if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
361  
        copy(file, dst1);
362  
      }
363  
    }
364  
  }
365  
366  
  /** Quickly copy a file without a progress bar or any other fancy GUI... :) */
367  
  public static void copy(File src, File dest) throws IOException {
368  
    FileInputStream inputStream = new FileInputStream(src);
369  
    FileOutputStream outputStream = new FileOutputStream(dest);
370  
    try {
371  
      copy(inputStream, outputStream);
372  
      inputStream.close();
373  
    } finally {
374  
      outputStream.close();
375  
    }
376  
  }
377  
378  
  public static void copy(InputStream in, OutputStream out) throws IOException {
379  
    byte[] buf = new byte[65536];
380  
    while (true) {
381  
      int n = in.read(buf);
382  
      if (n <= 0) return;
383  
      out.write(buf, 0, n);
384  
    }
385  
  }
386  
387  
  /** writes safely (to temp file, then rename) */
388  
  public static void saveTextFile(String fileName, String contents) throws IOException {
389  
    File file = new File(fileName);
390  
    File parentFile = file.getParentFile();
391  
    if (parentFile != null)
392  
      parentFile.mkdirs();
393  
    String tempFileName = fileName + "_temp";
394  
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
395  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
396  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
397  
    printWriter.print(contents);
398  
    printWriter.close();
399  
    if (file.exists() && !file.delete())
400  
      throw new IOException("Can't delete " + fileName);
401  
402  
    if (!new File(tempFileName).renameTo(file))
403  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
404  
  }
405  
406  
  /** writes safely (to temp file, then rename) */
407  
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
408  
    File file = new File(fileName);
409  
    File parentFile = file.getParentFile();
410  
    if (parentFile != null)
411  
      parentFile.mkdirs();
412  
    String tempFileName = fileName + "_temp";
413  
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
414  
    fileOutputStream.write(contents);
415  
    fileOutputStream.close();
416  
    if (file.exists() && !file.delete())
417  
      throw new IOException("Can't delete " + fileName);
418  
419  
    if (!new File(tempFileName).renameTo(file))
420  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
421  
  }
422  
423  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
424  
    if (!new File(fileName).exists())
425  
      return defaultContents;
426  
427  
    FileInputStream fileInputStream = new FileInputStream(fileName);
428  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
429  
    return loadTextFile(inputStreamReader);
430  
  }
431  
432  
  public static String loadTextFile(Reader reader) throws IOException {
433  
    StringBuilder builder = new StringBuilder();
434  
    try {
435  
      BufferedReader bufferedReader = new BufferedReader(reader);
436  
      String line;
437  
      while ((line = bufferedReader.readLine()) != null)
438  
        builder.append(line).append('\n');
439  
    } finally {
440  
      reader.close();
441  
    }
442  
    return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1);
443  
  }
444  
445  
  static File DiskSnippetCache_dir;
446  
447  
  public static void initDiskSnippetCache(File dir) {
448  
    DiskSnippetCache_dir = dir;
449  
    dir.mkdirs();
450  
  }
451  
452  
  // Data files are immutable, use centralized cache
453  
  public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
454  
    File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
455  
    if (verbose)
456  
      System.out.println("Checking data cache: " + file.getPath());
457  
    return file.exists() ? file : null;
458  
  }
459  
460  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
461  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
462  
  }
463  
464  
  private static File DiskSnippetCache_getFile(long snippetID) {
465  
    return new File(DiskSnippetCache_dir, "" + snippetID);
466  
  }
467  
468  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
469  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
470  
  }
471  
472  
  public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
473  
    saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
474  
  }
475  
476  
  public static File DiskSnippetCache_getDir() {
477  
    return DiskSnippetCache_dir;
478  
  }
479  
480  
  public static void initSnippetCache() {
481  
    if (DiskSnippetCache_dir == null)
482  
      initDiskSnippetCache(getGlobalCache());
483  
  }
484  
485  
  private static File getGlobalCache() {
486  
    File file = new File(System.getProperty("user.home"), ".tinybrain/snippet-cache");
487  
    file.mkdirs();
488  
    return file;
489  
  }
490  
491  
  public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
492  
    String text = loadSnippet(snippetID);
493  
    String realHash = getHash(text.getBytes("UTF-8"));
494  
    if (!realHash.equals(hash)) {
495  
      String msg;
496  
      if (hash.isEmpty())
497  
        msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
498  
      else
499  
        msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
500  
      throw new RuntimeException(msg);
501  
    }
502  
    return text;
503  
  }
504  
505  
  public static String getHash(byte[] data) {
506  
    return bytesToHex(getFullFingerprint(data));
507  
  }
508  
509  
  public static byte[] getFullFingerprint(byte[] data) {
510  
    try {
511  
      return MessageDigest.getInstance("MD5").digest(data);
512  
    } catch (NoSuchAlgorithmException e) {
513  
      throw new RuntimeException(e);
514  
    }
515  
  }
516  
517  
  public static String bytesToHex(byte[] bytes) {
518  
    return bytesToHex(bytes, 0, bytes.length);
519  
  }
520  
521  
  public static String bytesToHex(byte[] bytes, int ofs, int len) {
522  
    StringBuilder stringBuilder = new StringBuilder(len*2);
523  
    for (int i = 0; i < len; i++) {
524  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
525  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
526  
    }
527  
    return stringBuilder.toString();
528  
  }
529  
530  
  public static String loadSnippet(String snippetID) throws IOException {
531  
    return loadSnippet(parseSnippetID(snippetID));
532  
  }
533  
534  
  public static long parseSnippetID(String snippetID) {
535  
    return Long.parseLong(shortenSnippetID(snippetID));
536  
  }
537  
538  
  private static String shortenSnippetID(String snippetID) {
539  
    if (snippetID.startsWith("#"))
540  
      snippetID = snippetID.substring(1);
541  
    String httpBlaBla = "http://tinybrain.de/";
542  
    if (snippetID.startsWith(httpBlaBla))
543  
      snippetID = snippetID.substring(httpBlaBla.length());
544  
    return snippetID;
545  
  }
546  
547  
  public static boolean isSnippetID(String snippetID) {
548  
    snippetID = shortenSnippetID(snippetID);
549  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
550  
  }
551  
552  
  public static boolean isInteger(String s) {
553  
    return Pattern.matches("\\-?\\d+", s);
554  
  }
555  
556  
  public static String loadSnippet(long snippetID) throws IOException {
557  
    String text = memSnippetCache.get(snippetID);
558  
    if (text != null)
559  
      return text;
560  
561  
    if (preferCached) {
562  
      initSnippetCache();
563  
      text = DiskSnippetCache_get(snippetID);
564  
      if (text != null)
565  
        return text;
566  
    }
567  
568  
    try {
569  
      URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
570  
      text = loadPage(url);
571  
    } catch (FileNotFoundException e) {
572  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
573  
    }
574  
575  
    memSnippetCache.put(snippetID, text);
576  
577  
    try {
578  
      initSnippetCache();
579  
      DiskSnippetCache_put(snippetID, text);
580  
    } catch (IOException e) {
581  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
582  
    }
583  
584  
    return text;
585  
  }
586  
587  
  private static String loadPage(URL url) throws IOException {
588  
    System.err.println("Loading: " + url.toExternalForm());
589  
    URLConnection con = url.openConnection();
590  
    return loadPage(con, url);
591  
  }
592  
593  
  public static String loadPage(URLConnection con, URL url) throws IOException {
594  
    String contentType = con.getContentType();
595  
    if (contentType == null)
596  
      throw new IOException("Page could not be read: " + url);
597  
    //Log.info("Content-Type: " + contentType);
598  
    String charset = guessCharset(contentType);
599  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
600  
    StringBuilder buf = new StringBuilder();
601  
    while (true) {
602  
      int ch = r.read();
603  
      if (ch < 0)
604  
        break;
605  
      //Log.info("Chars read: " + buf.length());
606  
      buf.append((char) ch);
607  
    }
608  
    return buf.toString();
609  
  }
610  
611  
  public static byte[] loadBinaryPage(URLConnection con, URL url) throws IOException {
612  
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
613  
    InputStream inputStream = con.getInputStream();
614  
    while (true) {
615  
      int ch = inputStream.read();
616  
      if (ch < 0)
617  
        break;
618  
      buf.write(ch);
619  
    }
620  
    inputStream.close();
621  
    return buf.toByteArray();
622  
  }
623  
624  
  public static String guessCharset(String contentType) {
625  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
626  
    Matcher m = p.matcher(contentType);
627  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
628  
    return m.matches() ? m.group(1) : "ISO-8859-1";
629  
  }
630  
631  
  /** runs a transpiled set of sources */
632  
  public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess,
633  
                            List<File> libraries, String[] args) throws Exception {
634  
    File classesDir = TempDirMaker_make();
635  
    String javacOutput = compileJava(srcDir, libraries, classesDir);
636  
637  
    // run
638  
639  
    if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
640  
      + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
641  
    runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args);
642  
  }
643  
644  
  static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
645  
    // collect sources
646  
647  
    List<File> sources = new ArrayList<File>();
648  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
649  
    scanForSources(srcDir, sources, true);
650  
    if (sources.isEmpty())
651  
      throw new IOException("No sources found");
652  
653  
    // compile
654  
655  
    File optionsFile = File.createTempFile("javax", "");
656  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
657  
    String options = "-d " + bashQuote(classesDir.getPath());
658  
    writeOptions(sources, libraries, optionsFile, options);
659  
    classesDir.mkdirs();
660  
    return invokeJavac(optionsFile);
661  
  }
662  
663  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
664  
                                 boolean silent, boolean runInProcess,
665  
                                 List<File> libraries, String[] args) throws Exception {
666  
    // print javac output if compile failed and it hasn't been printed yet
667  
    boolean didNotCompile = !didCompile(classesDir);
668  
    if (verbose || didNotCompile)
669  
      System.out.println(javacOutput);
670  
    if (didNotCompile)
671  
      return;
672  
673  
    if (runInProcess
674  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
675  
      runProgramQuick(classesDir, libraries, args);
676  
      return;
677  
    }
678  
679  
    boolean echoOK = false;
680  
    // TODO: add libraries to class path
681  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
682  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
683  
    if (verbose) System.out.println(bashCmd);
684  
    String output = backtick(bashCmd);
685  
    if (verbose || !silent)
686  
      System.out.println(output);
687  
  }
688  
689  
  static boolean didCompile(File classesDir) {
690  
    return hasFile(classesDir, "main.class");
691  
  }
692  
693  
  private static void runProgramQuick(File classesDir, List<File> libraries,
694  
                                      String[] args) throws Exception {
695  
    // collect urls
696  
    URL[] urls = new URL[libraries.size()+1];
697  
    urls[0] = classesDir.toURI().toURL();
698  
    for (int i = 0; i < libraries.size(); i++)
699  
      urls[i+1] = libraries.get(i).toURI().toURL();
700  
701  
    // make class loader
702  
    URLClassLoader classLoader = new URLClassLoader(urls);
703  
704  
    // load JavaX main class
705  
    Class<?> mainClass = classLoader.loadClass("main");
706  
707  
    // run main method
708  
    Method main = mainClass.getMethod("main", String[].class);
709  
    main.invoke(null, (Object) args);
710  
  }
711  
712  
  private static String invokeJavac(File optionsFile) throws IOException {
713  
    String output;
714  
    try {
715  
      output = invokeEcj(optionsFile);
716  
    } catch (NoClassDefFoundError e) {
717  
      if (verbose) {
718  
        System.err.println("ecj not found - using javac");
719  
        e.printStackTrace();
720  
      }
721  
      output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
722  
    }
723  
    if (verbose) System.out.println(output);
724  
    return output;
725  
  }
726  
727  
  // throws ClassNotFoundError if ecj is not in classpath
728  
  static String invokeEcj(File optionsFile) {
729  
    StringWriter writer = new StringWriter();
730  
    PrintWriter printWriter = new PrintWriter(writer);
731  
    org.eclipse.jdt.core.compiler.CompilationProgress progress = null;
732  
    org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
733  
      new String[] { "@" + optionsFile.getPath(), "-source", "1.7" },
734  
      printWriter,
735  
      printWriter,
736  
      progress);
737  
    return writer.toString();
738  
  }
739  
740  
  private static void writeOptions(List<File> sources, List<File> libraries,
741  
                                   File optionsFile, String moreOptions) throws IOException {
742  
    FileWriter writer = new FileWriter(optionsFile);
743  
    for (File source : sources)
744  
      writer.write(bashQuote(source.getPath()) + " ");
745  
    if (!libraries.isEmpty()) {
746  
      List<String> cp = new ArrayList<String>();
747  
      for (File lib : libraries)
748  
        cp.add(lib.getAbsolutePath());
749  
      writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
750  
    }
751  
    writer.write(moreOptions);
752  
    writer.close();
753  
  }
754  
755  
  static void scanForSources(File source, List<File> sources, boolean topLevel) {
756  
    if (source.isFile() && source.getName().endsWith(".java"))
757  
      sources.add(source);
758  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
759  
      File[] files = source.listFiles();
760  
      for (File file : files)
761  
        scanForSources(file, sources, false);
762  
    }
763  
  }
764  
765  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
766  
    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.)
767  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
768  
  }
769  
770  
  public static String backtick(String cmd) throws IOException {
771  
    ++processesStarted;
772  
    File outFile = File.createTempFile("_backtick", "");
773  
    File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
774  
775  
    String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1";
776  
    //Log.info("[Backtick] " + command);
777  
    try {
778  
      saveTextFile(scriptFile.getPath(), command);
779  
      String[] command2;
780  
      if (isWindows())
781  
        command2 = new String[] { scriptFile.getPath() };
782  
      else
783  
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
784  
      Process process = Runtime.getRuntime().exec(command2);
785  
      try {
786  
        process.waitFor();
787  
      } catch (InterruptedException e) {
788  
        throw new RuntimeException(e);
789  
      }
790  
      process.exitValue();
791  
      return loadTextFile(outFile.getPath(), "");
792  
    } finally {
793  
      scriptFile.delete();
794  
    }
795  
  }
796  
797  
  /** possibly improvable */
798  
  public static String javaQuote(String text) {
799  
    return bashQuote(text);
800  
  }
801  
802  
  /** possibly improvable */
803  
  public static String bashQuote(String text) {
804  
    if (text == null) return null;
805  
    return "\"" + text
806  
      .replace("\\", "\\\\")
807  
      .replace("\"", "\\\"")
808  
      .replace("\n", "\\n")
809  
      .replace("\r", "\\r") + "\"";
810  
  }
811  
812  
  public final static String charsetForTextFiles = "UTF8";
813  
814  
  static long TempDirMaker_lastValue;
815  
816  
  public static File TempDirMaker_make() {
817  
    File dir = new File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue());
818  
    dir.mkdirs();
819  
    return dir;
820  
  }
821  
822  
  private static long TempDirMaker_newValue() {
823  
    long value;
824  
    do
825  
      value = System.currentTimeMillis();
826  
    while (value == TempDirMaker_lastValue);
827  
    TempDirMaker_lastValue = value;
828  
    return value;
829  
  }
830  
831  
  public static String join(String glue, Iterable<String> strings) {
832  
    StringBuilder buf = new StringBuilder();
833  
    Iterator<String> i = strings.iterator();
834  
    if (i.hasNext()) {
835  
      buf.append(i.next());
836  
      while (i.hasNext())
837  
        buf.append(glue).append(i.next());
838  
    }
839  
    return buf.toString();
840  
  }
841  
842  
  public static boolean isWindows() {
843  
    return System.getProperty("os.name").contains("Windows");
844  
  }
845  
}

Author comment

Renamed to _x14 to avoid clashes in runner...

Began life as a copy of #2000388

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: #2000389
Snippet name: class x14 (embeddable)
Eternal ID of this version: #2000389/1
Text MD5: 139b0ffe721c0c96666d0ccaeba988a7
Author: stefan
Category:
Type: New Tinybrain snippet
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-06-25 20:27:05
Source code size: 30813 bytes / 845 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 476 / 114
Referenced in: [show references]