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

1787
LINES

< > BotCompany Repo | #1001209 // Default boot-up code for JavaX/Android 26 (backup)

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

import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.lang.reflect.*;
import java.net.*;
import javax.swing.*;
import java.util.regex.*;
import java.util.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;

import android.widget.*;
import android.view.*;
import android.content.Context;
import android.app.Activity;
import android.view.inputmethod.*;
import android.content.*;

public class main {
  static List<Prog> programsStarted = new ArrayList<Prog>();

  static class Prog {
    String snippetID;
    Thread thread;
  }

  static class Lg {
    static int maxBufferLength = 2048;
    
    Activity context;
    ScrollView sv;
    TextView tv;
    StringBuilder buf = new StringBuilder();
    
    Lg(Activity context) {
      this.context = context;
      sv = new ScrollView(context);
      tv = new TextView(context);
      tv.setText(buf.toString());
      sv.addView(tv);
    }
    
    View getView() {
      return sv;
    }
    
    void shortenBuffer() {
      while (buf.length() > maxBufferLength) {
        String s = buf.toString();
        int i = s.indexOf('\n');
        if (i < 0) return;
        buf = new StringBuilder(s.substring(i+1));
      }
    }
    
    void print(final String s) {
      context.runOnUiThread(new Runnable() {
        public void run() {
          buf.append(s);
          shortenBuffer();
          tv.setText(buf.toString());
          
          sv.post(new Runnable() {
            public void run() {
              // This method works but animates the scrolling 
              // which looks weird on first load
              sv.fullScroll(View.FOCUS_DOWN);

              // This method works even better because there are no animations.
              //sv.scrollTo(0, sv.getBottom());
            }
          });
        }
      });
    }
    
    void println(String s) {
      print(s + "\n");
    }
  }
  
  public static View main(final Activity context) throws Exception {
    x19.androidContext = context;
    final File defSnip = new File(x19.userHome(), ".javax/defsnip");
    String id = x19.loadTextFile(defSnip.getPath(), "675");
 final File defargs = new File(x19.userHome(), ".javax/defargs");
    String arg = x19.loadTextFile(defargs.getPath(), "");

    ScrollView sv = new ScrollView(context);
    LinearLayout ll = new LinearLayout(context);
    ll.setOrientation(LinearLayout.VERTICAL);
    
    LinearLayout line1 = new LinearLayout(context);
    
    TextView label = new TextView(context);
    label.setText("Run which snippet ID?");
    line1.addView(label);
    
    final EditText tv = new EditText(context);
    tv.setText(id);
    line1.addView(tv);
    
    Button btnGo = new Button(context);
    btnGo.setText("Go");
    line1.addView(btnGo);
    
    ll.addView(line1);
    
    LinearLayout line2 = new LinearLayout(context);
    
    label = new TextView(context);
    label.setText("Program arguments:");
    line2.addView(label);
    
    final EditText tvArgs = new EditText(context);
    tvArgs.setText(arg);
    line2.addView(tvArgs);
    
    ll.addView(line2);
    
    btnGo.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        hideKeyboard(context);
        String snippetID = tv.getText().toString();
        String text = "Running: " + snippetID;
        Toast.makeText(context, text, 2000).show();
        
        try {
          x19.saveTextFile(defSnip.getPath(), snippetID);
          x19.saveTextFile(defargs.getPath(), tvArgs.getText().toString());
        } catch (IOException e) {
        }
        run(context, snippetID, tvArgs.getText().toString().split(" +"));
      }
    });

    sv.addView(ll);
    return sv;
  }
  
  static Lg lg;
  
  public static void run(final Activity context, final String mainSnippet, final String[] args) {
    lg = new Lg(context);
    
    OutputStream outputStream = new OutputStream() {
      public void write(int b) {
        try {
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
      
      @Override
      public void write(byte[] b, int off, int len) {
        try {
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
    };
    
    PrintStream ps = new PrintStream(outputStream, true);
    System.setOut(ps);
    System.setErr(ps);
    
    Prog prog = new Prog();
    prog.snippetID = mainSnippet;

    prog.thread = new Thread() {
      public void run() {
        try {
          String[] a = new String[args.length+1];
          System.arraycopy(args, 0, a, 1, args.length);
          a[0] = mainSnippet;
          x19.main(a);
        } catch (Throwable e) {
          System.out.println("Whoa!");
          e.printStackTrace();
        }
      }
    };
    
    programsStarted.add(prog);
    prog.thread.start();
    
    context.setContentView(lg.getView());
  }
  
  static void setContentViewInUIThread(final View view) {
    ((Activity) x19.androidContext).runOnUiThread(new Runnable() {
      public void run() {
        ((Activity) x19.androidContext).setContentView(view);
      }
    });
  }
  
  public static void hideKeyboard(Activity context) {   
    View view = context.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
  }
  
  static void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (x19.mainClass != null)
      x19.call(x19.mainClass, "onActivityResult", requestCode, resultCode, data);
  }
}

class x19 {
  static final String version = "JavaX 19";

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

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

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

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

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

  static Object androidContext;
  static boolean android = isAndroid();

  // Translators currently being translated (to detect recursions)
  private static Set<Long> translating = new HashSet<Long>();

  static String lastOutput;

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

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

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

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

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

    cleanCache();

    if (useServerTranspiled)
      noPrefetch = true;

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

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

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

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

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

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

  public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
                               String[] args) throws Exception {
    String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null;
    
    if (android && !translate && !list && ioDir.getPath().equals(".")) {
      if (javaAndroidQuick(programID, args))
        return;
    }
    
    List<File> libraries = new ArrayList<File>();
    
    File X = transpileMain(src, libraries);
    if (X == null)
      return;

    // list or run

    if (translate) {
      File to = X;
      if (translateTo != null)
        if (new File(translateTo).isDirectory())
          to = new File(translateTo, "main.java");
        else
          to = new File(translateTo);
      if (to != X)
        copy(new File(X, "main.java"), to);
      System.out.println("Program translated to: " + to.getAbsolutePath());
    } else if (list)
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
    else
      javax2(X, ioDir, false, false, libraries, args, null, programID);
  }
  
  static boolean javaAndroidQuick(String programID, String[] args) throws Exception {
    URL url = new URL("http://tinybrain.de:8080/dexcompile.php?id=" + programID + "&transOnly=1");
    byte[] dexData = loadBinaryPage(url.openConnection());
    if (!isDex(dexData)) return false;
    javaAndroidGo(dexData, programID, args);
    return true;
  }

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

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

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

    // translate

    File X = srcDir;

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

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

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

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

  static String userHomeInternal() {
    if (android)
      return ((File) call(androidContext, "getFilesDir")).getAbsolutePath();
    else
      return System.getProperty("user.home");
  }
  
  static String userHome() {
    if (android)
      return "/storage/sdcard0/";
    else
      return System.getProperty("user.home");
  }

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

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

    saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids));
  }

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

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

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

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

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

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

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

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

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

      start = i;
    }
    return lines;
  }

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

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

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

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

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

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

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

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

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

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

  /** returns output dir */
  private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
                                           boolean silent,
                                           List<File> libraries_out) throws Exception {
    if (safeTranslate)
      checkProgramSafetyImpl(snippetID);
    long id = parseSnippetID(snippetID);

    File libraryFile = DiskSnippetCache_getLibrary(id);
    if (libraryFile != null) {
      loadLibrary(snippetID, libraries_out, libraryFile);
      return input;
    }

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

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

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

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

    File ioBaseDir = TempDirMaker_make();

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

    if (cached == null) {
      System.err.println("Translating translator #" + id);
      if (translating.contains(id))
        throw new RuntimeException("Recursive translator reference chain including #" + id);
      translating.add(id);
      try {
        srcDir = defaultTranslate(srcDir, libraries);
      } finally {
        translating.remove(id);
      }
      System.err.println("Translated translator #" + id);
      translationCache.put(id, new Object[]{srcDir, libraries});
    }

    boolean runInProcess = false;

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

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

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

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

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

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

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

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

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

  static void checkProgramSafety(String snippetID) throws IOException {
    if (!safeOnly) return;
    checkProgramSafetyImpl(snippetID);
  }

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

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

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

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

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

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

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

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

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

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

  static Object call(Object o, String method, Object... args) {
    try {
      Method m = call_findMethod(o, method, args, false);
      m.setAccessible(true);
      return m.invoke(o, args);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static Object call(Class c, String method, Object... args) {
    try {
      Method m = call_findStaticMethod(c, method, args, false);
      m.setAccessible(true);
      return m.invoke(null, args);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
        if (!m.getName().equals(method)) {
          if (debug) System.out.println("Method name mismatch: " + method);
          continue;
        }

        if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
          continue;

        return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + c.getName());
  }

  static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
    Class c = o.getClass();
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
        if (m.getName().equals(method) && call_checkArgs(m, args, debug))
          return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
  }

  private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        System.out.println("checkArgs: Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++)
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
        if (debug)
          System.out.println("checkArgs: Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
        return false;
      }
    return true;
  }

  private static FileInputStream newFileInputStream(File f) throws FileNotFoundException {
    /*if (androidContext != null)
      return (FileInputStream) call(androidContext,
        "openFileInput", f.getPath());
    else*/
    return new FileInputStream(f);
  }

  private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException {
    /*if (androidContext != null)
      return (FileOutputStream) call(androidContext,
        "openFileOutput", f.getPath(), 0);
    else*/
    return new FileOutputStream(f);
  }

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

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

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

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

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

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

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

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

  static File DiskSnippetCache_dir;

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

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

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

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

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

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

  public static File DiskSnippetCache_getDir() {
    return DiskSnippetCache_dir;
  }

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

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

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

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

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

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

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

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

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

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

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

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

  public static String loadSnippet(long snippetID) throws IOException {
    String text = memSnippetCache.get(snippetID);
    if (text != null) {
      if (verbose)
        System.out.println("Getting " + snippetID + " from mem cache");
      return text;
    }

    initSnippetCache();
    text = DiskSnippetCache_get(snippetID);
    if (preferCached && text != null) {
      if (verbose)
        System.out.println("Getting " + snippetID + " from disk cache (preferCached)");
      return text;
    }

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

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

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

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

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

    memSnippetCache.put(snippetID, text);

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

    return text;
  }

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

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

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

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

  public static byte[] loadBinaryPage(URLConnection con) throws IOException {
    setHeaders(con);
    return loadBinaryPage_noHeaders(con);
  }

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

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

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

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

      // run

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

  static void javax2android(File srcDir, String[] args, String programID) throws Exception {
    byte[] dexData;
    String isTranspiled = /*loadTextFile(new File(srcDir, "is-transpiled").getPath(), null)*/null;
    if (isTranspiled != null) {
      URL url = new URL("http://tinybrain.de:8080/dexcompile.php?id=" + isTranspiled + "&transOnly=1");
      dexData = loadBinaryPage(url.openConnection());
    } else {
      URL url = new URL("http://tinybrain.de:8080/dexcompile.php");
      URLConnection conn = url.openConnection();
      String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8");
      dexData = doPostBinary(postData, conn);
    }
    
    javaAndroidGo(dexData, programID, args);
  }
  
  static Class<?> mainClass;
  
  static void javaAndroidGo(byte[] dexData, String programID, String[] args) throws Exception {
    if (!isDex(dexData))
      throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8"));
    System.out.println("Dex loaded: " + dexData.length + "b");

    File dexDir = TempDirMaker_make();
    File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
    File dexOutputDir = TempDirMaker_make_internal();

    //System.out.println("Saving dex to: " + dexDir.getAbsolutePath());
    try {
      saveBinaryFile(dexFile.getPath(), dexData);
    } catch (Throwable e) {
      System.out.println("Whoa!");
      throw new RuntimeException(e);
    }

    //System.out.println("Getting parent class loader.");
    ClassLoader parentClassLoader =
      //ClassLoader.getSystemClassLoader(); // does not find support jar
      //getClass().getClassLoader(); // Let's try this...
      x19.class.getClassLoader().getParent(); // XXX !

    //System.out.println("Making DexClassLoader.");
    //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
    //  parentClassLoader);
    Class dcl = Class.forName("dalvik.system.DexClassLoader");
    Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
      parentClassLoader);

    System.out.println("Loading main class.");
    //Class<?> theClass = classLoader.loadClass(mainClassName);
    Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");
    mainClass = theClass;

    //System.out.println("Main class loaded.");
    try {
      set(theClass, "androidContext", androidContext);
    } catch (Throwable e) {}

    try {
      set(theClass, "programID", programID);
    } catch (Throwable e) {}

    Method main = null;
    try {
      main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false);
    } catch (RuntimeException e) {
    }

    //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main);

    if (main != null) {
      // old style main program that returns a View
      System.out.println("Calling main (old-style)");
      Object view = main.invoke(null, androidContext);
      System.out.println("Calling setContentView with " + view);
      call(Class.forName("main"), "setContentViewInUIThread", view);
      //call(androidContext, "setContentView", view);
      System.out.println("Done.");
    } else {
      System.out.println("New-style main method running.\n\n====\n");
      runMainMethod(args, theClass);
    }
  }

  static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };

  static boolean isDex(byte[] dexData) {
    if (dexData.length < DEX_FILE_MAGIC.length) return false;
    for (int i = 0; i < DEX_FILE_MAGIC.length; i++)
      if (dexData[i] != DEX_FILE_MAGIC[i])
        return false;
    return true;
  }

  static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException {
    // connect and do POST
    setHeaders(conn);
    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(urlParameters);
    writer.flush();

    byte[] contents = loadBinaryPage_noHeaders(conn);
    writer.close();
    return contents;
  }

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

    // collect sources

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

    // compile

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

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

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

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

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

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

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

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

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

    try {
      set(mainClass, "programID", programID);
    } catch (Throwable e) {}

    runMainMethod(args, mainClass);
  }


  static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Method main = mainClass.getMethod("main", String[].class);
    main.invoke(null, args);
  }

  private static String invokeJavaCompiler(File optionsFile) throws IOException {
    String output;
    if (hasEcj() && !javacOnly)
      output = invokeEcj(optionsFile);
    else
      output = invokeJavac(optionsFile);
    if (verbose) System.out.println(output);
    return output;
  }

  private static boolean hasEcj() {
    try {
      Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
      return true;
    } catch (ClassNotFoundException e) {
      return false;
    }
  }

  private static String invokeJavac(File optionsFile) throws IOException {
    String output;
    output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
    if (exitValue != 0) {
      System.out.println(output);
      throw new RuntimeException("javac returned errors.");
    }
    return output;
  }

  // throws ClassNotFoundException if ecj is not in classpath
  static String invokeEcj(File optionsFile) {
    try {
      StringWriter writer = new StringWriter();
      PrintWriter printWriter = new PrintWriter(writer);

      // add more eclipse options in the line below

      String[] args = {"@" + optionsFile.getPath(),
        "-source", "1.7",
        "-nowarn"
      };

      Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
      Object main = newInstance(ecjClass, printWriter, printWriter, false);
      call(main, "compile", new Object[]{args});
      int errors = (Integer) get(main, "globalErrorsCount");

      String output = writer.toString();
      if (errors != 0) {
        System.out.println(output);
        throw new RuntimeException("Java compiler returned errors.");
      }
      return output;
    } catch (Exception e) {
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
    }
  }

  static Object get(Object o, String field) {
    try {
      Field f = findField(o.getClass(), field);
      f.setAccessible(true);
      return f.get(o);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static Object newInstance(Class c, Object... args) { try {
    Constructor m = findConstructor(c, args);
    m.setAccessible(true);
    return m.newInstance(args);
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

  static Constructor findConstructor(Class c, Object... args) {
    for (Constructor m : c.getDeclaredConstructors()) {
      if (!checkArgs(m.getParameterTypes(), args, verbose))
        continue;
      return m;
    }
    throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
  }

  static boolean checkArgs(Class[] types, Object[] args, boolean debug) {
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++)
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
        if (debug)
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
        return false;
      }
    return true;
  }

  // extended to handle primitive types
  private static boolean isInstanceX(Class type, Object arg) {
    if (type == boolean.class) return arg instanceof Boolean;
    if (type == int.class) return arg instanceof Integer;
    if (type == long.class) return arg instanceof Long;
    if (type == float.class) return arg instanceof Float;
    if (type == short.class) return arg instanceof Short;
    if (type == char.class) return arg instanceof Character;
    if (type == byte.class) return arg instanceof Byte;
    return type.isInstance(arg);
  }

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

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

  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
    if (topLevel) return false; // input or output ok as highest directory (intentionally specified by user, not just found by a directory scan in which case we probably don't want it. it's more like heuristics actually.)
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
  }

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

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

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

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

  public final static String charsetForTextFiles = "UTF8";

  static long TempDirMaker_lastValue;

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

  public static File TempDirMaker_make_internal() {
    File dir = new File(userHomeInternal(), ".javax/" + TempDirMaker_newValue());
    dir.mkdirs();
    return dir;
  }

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

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

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

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

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

  static int fileDeletions;

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

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

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

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

  static boolean isAndroid() {
    return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0;
  }

  static void set(Class c, String field, Object value) {
    try {
      Field f = findStaticField(c, field);
      f.setAccessible(true);
      f.set(null, value);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static Field findStaticField(Class<?> c, String field) {
    for (Field f : c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
        return f;
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
  }

  static Field findField(Class<?> c, String field) {
    for (Field f : c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
  }
}

Author comment

Began life as a copy of #676

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1001209
Snippet name: Default boot-up code for JavaX/Android 26 (backup)
Eternal ID of this version: #1001209/1
Text MD5: 4cf4b204f287f5df40810b1696b494ac
Author: stefan
Category: javax
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-09-30 20:24:36
Source code size: 63605 bytes / 1787 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 773 / 657
Referenced in: #3000189 - Answer for stefanreich(>> t bla)
#3000190 - Answer for stefanreich(>> t 20 questions)
#3000202 - Answer for stefanreich (>> T conversion bot)
#3000238 - Answer for stefanreich (>> t power bot)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)