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

1428
LINES

< > BotCompany Repo | #1000413 // Porting JavaX 18 to Android (transpiled, EDITING)

JavaX source code (Android) - run with: the app

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

download  show line numbers  debug dex  old transpilations   

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

Comments [hide]

ID Author/Program Comment Date
85 stefan It seems to work - at least with the "hello world" :) 2015-08-03 22:23:31

add comment

Snippet ID: #1000413
Snippet name: Porting JavaX 18 to Android (transpiled, EDITING)
Eternal ID of this version: #1000413/1
Text MD5: 2cb805e8fc5afe2a051624b74e1eee22
Author: stefan
Category: javax android
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 22:34:31
Source code size: 51199 bytes / 1428 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1098 / 977
Referenced in: [show references]