import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.math.*;
import android.widget.*;
import android.view.*;
import android.view.View;
import android.content.Context;
import android.app.Activity;
import android.view.inputmethod.*;
import android.content.*;
import android.text.*;
public class main {} // dummy
class x30 implements Runnable {
static final String version = "JavaX 30";
static final int subversion = 1;
static final String javaxProgramID = "#1001638";
static Class bootUpClass;
// If programs run longer than this, they might have their class files
// deleted. One day for now.
static int tempFileRetentionTime = 1*24; // hours
static int maxConsoleChars = 1024*1024;
static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
static String translateTo = null;
static boolean preferCached = false, noID = false, noPrefetch = false, noAWT = false;
static boolean safeOnly = false, safeTranslate = false, javacOnly = false, logOn = true;
static boolean runMainInProcess = true, consoleOn = true, hasHelloMessage = 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();
// We stick to 1.7 for now to support android.
// Scripts like #1001155 might change to 1.6
static String javaTarget = System.getProperty("java.version").startsWith("1.6.") ? "1.6" : "1.7";
// Translators currently being translated (to detect recursions)
private static Set<Long> translating = new HashSet<Long>();
static String lastOutput;
static String[] fullArgs;
private static Console console;
static String javaCompilerOutput;
static int systemOutPipeSize = 128*1024; // 128 K
static int systemErrPipeSize = 4*1024; // 4 K
static int systemInPipeSize = 4*1024; // 4 K
public static void main(String[] args) {
try {
goMain(args);
} catch (Throwable e) {
e.printStackTrace();
}
}
static void goMain(String[] args) throws Exception {
__javax = x30.class; // for hotwire
if (args.length != 0 && args[0].equals("-v")) verbose = true;
for (String arg : args)
if (arg.equals("-noawt"))
noAWT = true;
if (!hasHelloMessage) {
hasHelloMessage = true;
//installHelloMessage(args.length == 0 ? "JavaX Start-Up VM" : "JavaX VM (" + smartJoin(args) + ")");
makeVMAndroid();
}
File ioBaseDir = new File("."), inputDir = null, outputDir = null;
String src = null;
List<String> programArgs = new ArrayList<String>();
fullArgs = args;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("-version")) {
showVersion();
System.exit(0);
}
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("-noawt"))
noAWT = 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"));
}
if (logOn)
logStart(args);
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);
}
}
static void saveTranspiledCode(String progID, String code) {
saveTextFile(new File(getCodeProgramDir(progID), "Transpilation"), code);
}
static File getCodeProgramDir() {
return getCodeProgramDir(getProgramID());
}
static File getCodeProgramDir(String snippetID) {
return new File(userHome(), "JavaX-Code/" + formatSnippetID(snippetID));
}
static File getCodeProgramDir(long snippetID) {
return getCodeProgramDir(formatSnippetID(snippetID));
}
public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
String[] args) throws Exception {
String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null;
if (programID != null)
System.err.println("JavaX TRANSLATE " + programID + " " + smartJoin(args));
List<File> libraries = new ArrayList<File>();
File X = transpileMain(src, libraries);
if (verbose)
print("After transpileMain: " + X);
if (X == null) {
showVersion();
if (fullArgs != null) {
String[] nargs;
if (fullArgs.length == 0)
nargs = new String[] {"1000825"}; // swing-start
else {
// forward to search
nargs = new String[fullArgs.length+1];
nargs[0] = "636";
// nargs[1] = "search-runnables";
System.arraycopy(fullArgs, 0, nargs, 1, fullArgs.length);
}
main(nargs); // Hopefully we get no infinite recursion :)
return;
}
System.out.println("No main.java found, exiting");
return;
}
info.transpiledSrc = X;
// list or run
if (translate) {
File to = X;
if (translateTo != null) {
StringBuilder buf = new StringBuilder();
for (File f : libraries) buf.append(f.getName()+"\n");
if (new File(translateTo).isDirectory()) {
to = new File(translateTo, "main.java");
saveTextFile(new File(translateTo, "libraries.txt").getPath(), buf.toString());
} else {
to = new File(translateTo);
saveTextFile(new File(translateTo + "_libraries").getPath(), buf.toString());
}
}
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 {
if (programID != null)
System.err.println("JavaX RUN " + programID + " " + smartJoin(args));
System.err.println(); // Make empty line before actual program starts
javax2(X, ioDir, false, runMainInProcess, libraries, args, null, programID, info);
System.out.println("[main done]");
}
}
static File transpileMain(String src, List<File> libraries) throws Exception {
File srcDir = null;
boolean isTranspiled = false;
if (isSnippetID(src)) {
String transpiledSrc = getTranspilationFromBossBot(parseSnippetID(src));
if (transpiledSrc != null) {
int i = transpiledSrc.indexOf('\n');
String libs = transpiledSrc.substring(0, Math.max(0, i));
transpiledSrc = transpiledSrc.substring(i+1);
if (!transpiledSrc.isEmpty()) {
srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
isTranspiled = true;
Matcher m = Pattern.compile("\\d+").matcher(libs);
while (m.find()) {
String libid = m.group();
File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid));
loadLibrary(libid, libraries, libraryFile);
}
}
}
if (srcDir == null) {
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);
transpiledSrc = getServerTranspiled2("#" + id);
int i = transpiledSrc.indexOf('\n');
String libs = transpiledSrc.substring(0, Math.max(0, i));
transpiledSrc = transpiledSrc.substring(i+1);
if (!transpiledSrc.isEmpty()) {
srcDir = TempDirMaker_make();
saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
isTranspiled = true;
//translationCache.put(id, new Object[] {srcDir, libraries});
Matcher m = Pattern.compile("\\d+").matcher(libs);
while (m.find()) {
String libid = m.group();
File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid));
loadLibrary(libid, libraries, libraryFile);
}
}
}
}
} 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())
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") + standardCredentials();
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() {
return ((File) call(androidContext, "getFilesDir")).getAbsolutePath();
}
static String _userHome;
static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
//System.out.println("userHome: " + _userHome);
}
return _userHome;
}
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 {
List<String[]> postTranslators = new ArrayList<String[]>();
while (true) {
String main = loadTextFile(new File(x, "main.java").getPath(), null);
List<String> lines = toLines(main);
List<String[]> t = findPostTranslators(lines);
postTranslators.addAll(t);
if (!t.isEmpty()) {
main = fromLines(lines);
x = TempDirMaker_make();
saveTextFile(new File(x, "main.java").getPath(), main);
}
File y = autoTranslate(x, libraries_out);
if (y == x)
break;
x = y;
}
x = applyTranslators(x, postTranslators, libraries_out);
return x;
}
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);
}
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;
}
static List<String[]> findPostTranslators(List<String> lines) {
List<String[]> translators = new ArrayList<String[]>();
Pattern pattern = Pattern.compile("^!post\\s*([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);
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;
}
@SuppressWarnings( "unchecked" )
/** 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);
// It's a library, not a translator.
File libraryFile = DiskSnippetCache_getLibrary(id);
if (verbose)
System.out.println("Library file for " + id + ": " + libraryFile);
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 (verbose)
System.out.println(snippetID + ": length = " + mainJavaSize);
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);
transpiledSrc = transpiledSrc.substring(transpiledSrc.indexOf('\n')+1);
// TODO: check for libraries
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: " + structure(translating));
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");
// TODO: don't virtualize class _javax (as included in, say, #636)
//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
// 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()) + ");"); // extra + is necessary for Dumb TinyBrain :)
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);
}
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) + standardCredentials());
String text = loadPage(url);
if (!text.startsWith("{\"safe\":\"1\"}"))
throw new RuntimeException("Program not safe: #" + parseSnippetID(snippetID));
}
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);
}
/** 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, null);
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();
}
}
private static FileInputStream newFileInputStream(File f) throws FileNotFoundException {
/*if (androidContext != null)
return (FileInputStream) call(androidContext,
"openFileInput", f.getPath());
else*/
return new // line break for Dumb TinyBrain :)
FileInputStream(f);
}
private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException {
/*if (androidContext != null)
return (FileOutputStream) call(androidContext,
"openFileOutput", f.getPath(), 0);
else*/
return new // line break for Dumb TinyBrain :)
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 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) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(String fileName, String defaultContents) throws IOException {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
}
public static String loadTextFile(File fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName, String defaultContents) throws IOException {
try {
return loadTextFile(fileName.getPath(), defaultContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
} // loadTextFile
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);
}
static String getTranspilationFromBossBot(long snippetID) {
return boss(format3("get transpilation for *", snippetID));
}
public static String loadSnippet(long snippetID) throws IOException {
String text = getSnippetFromBossBot(snippetID);
if (text != null) return text;
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 + standardCredentials());
text = loadPage(url);*/
String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1" + standardCredentials();
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 (Exception e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public / " + e);
}
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);
}
}
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();
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
System.err.println(" " + n + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
}
private static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {}
}
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, Info info) throws Exception {
if (android) {
// TODO: no translator virtualization? huh?
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, info);
}
}
static Class<?> loadx2android(File srcDir, String programID) throws Exception {
File dexDir = TempDirMaker_make();
File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
byte[] dexData;
if (isSnippetID(programID))
dexData = loadBinaryPage("http://tinybrain.de:8080/dexcompile.php?id=" + parseSnippetID(programID) + standardCredentials());
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);
}
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 dexOutputDir = TempDirMaker_makeInternal();
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...
x30.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");
//System.out.println("Main class loaded.");
try {
set(theClass, "androidContext", androidContext);
} catch (Throwable e) {}
setVars(theClass, programID);
addInstance(programID, theClass);
return theClass;
}
static void addInstance(String programID, Class mainClass) {
programID = "" + parseSnippetID(programID);
instances.put(programID, new WeakReference<Class>(mainClass));
}
static Class getInstance(String programID) {
programID = "" + parseSnippetID(programID);
List<WeakReference<Class>> l = instances.get(programID);
for (WeakReference<Class> c : l) {
Class theClass = c.get();
// TODO: shorten the list
if (theClass != null)
return theClass;
}
return null;
}
static MultiMap<String, WeakReference<Class>> instances = new MultiMap<String, WeakReference<Class>>();
static class MultiMap<A,B> {
Map<A, List<B>> data = new HashMap<A, List<B>>();
MultiMap() {}
MultiMap(MultiMap<A, B> map) { putAll(map); }
public void put(A key, B value) {
List<B> list = data.get(key);
if (list == null)
data.put(key, list = new ArrayList<B>());
list.add(value);
}
public void addAll(A key, Collection<B> values) {
putAll(key, values);
}
public void addAllIfNotThere(A key, Collection<B> values) {
for (B value : values)
setPut(key, value);
}
void setPut(A key, B value) {
if (!containsPair(key, value))
put(key, value);
}
boolean containsPair(A key, B value) {
return get(key).contains(value);
}
public void putAll(A key, Collection<B> values) {
for (B value : values)
put(key, value);
}
void removeAll(A key, Collection<B> values) {
for (B value : values)
remove(key, value);
}
public List<B> get(A key) {
List<B> list = data.get(key);
return list == null ? Collections.<B> emptyList() : list;
}
// returns actual mutable live list
// creates the list if not there
public List<B> getActual(A key) {
List<B> list = data.get(key);
if (list == null)
data.put(key, list = litlist());
return list;
}
void clean(A key) {
List<B> list = data.get(key);
if (list != null && list.isEmpty())
data.remove(key);
}
public Set<A> keySet() {
return data.keySet();
}
public Set<A> keys() {
return data.keySet();
}
public void remove(A key) {
data.remove(key);
}
public void remove(A key, B value) {
List<B> list = data.get(key);
if (list != null) {
list.remove(value);
if (list.isEmpty())
data.remove(key);
}
}
public void clear() {
data.clear();
}
public boolean containsKey(A key) {
return data.containsKey(key);
}
public B getFirst(A key) {
List<B> list = get(key);
return list.isEmpty() ? null : list.get(0);
}
public void putAll(MultiMap<A, B> map) {
for (A key : map.keySet())
putAll(key, map.get(key));
}
// note: expensive operation
int size() {
int n = 0;
for (List l : data.values())
n += l(l);
return n;
}
// expensive operation
List<A> reverseGet(B b) {
List<A> l = new ArrayList<A>();
for (A key : data.keySet())
if (data.get(key).contains(b))
l.add(key);
return l;
}
} // MultiMap
static void javax2android(File srcDir, String[] args, String programID) throws Exception {
Class<?> theClass = loadx2android(srcDir, programID);
// record injection
final PaA paa = new PaA(programID, args);
paa.injectionID = randomID(8);
paa.mainClass = theClass;
addInjection(paa);
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
// TODO: maybe allow programs without main method, although it doesn't seem to make sense here really (Android main program)
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 {
javaCompilerOutput = null;
++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());
if (verbose) System.out.println("Libraries: " + libraries);
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, Info info) throws Exception {
// print javac output if compile failed and it hasn't been printed yet
if (info != null) {
info.programID = programID;
info.programArgs = args;
}
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, info, ioBaseDir);
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, Info info,
File ioBaseDir) 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 (info != null) {
info.mainClass = mainClass;
if (info.transpiledSrc != null)
registerSourceCode(mainClass, loadTextFile(new File(info.transpiledSrc, "main.java")));
}
if (cacheAs != null)
programCache.put(cacheAs, mainClass);
// record injection
final PaA paa = new PaA(programID, args);
paa.injectionID = randomID(8);
paa.mainClass = mainClass;
addInjection(paa);
// change baseDir
try {
//print("Changing base dir to " + ioBaseDir.getAbsolutePath());
Class virtual = mainClass.getClassLoader().loadClass("virtual");
set(virtual, "virtual_baseDir", ioBaseDir.getAbsolutePath());
} catch (Throwable e) { /* whatever */ }
setVars(mainClass, programID);
addInstance(programID, mainClass);
try {
runMainMethod(args, mainClass);
} catch (Exception e) {
paa.exception = e;
throw e;
} finally {
paa.mainDone = true;
}
}
static void setVars(Class<?> theClass, String programID) {
try {
set(theClass, "programID", programID);
} catch (Throwable e) {}
try {
set(theClass, "__javax", x30.class);
} catch (Throwable e) {}
}
static void runMainMethod(String[] args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
callMain(mainClass, args);
}
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;
}
}
// TODO: fix UTF-8 here too
private static String invokeJavac(File optionsFile) throws IOException {
String output;
output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
javaCompilerOutput = output;
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 = {
"-source", javaTarget,
"-target", javaTarget,
"-nowarn",
"-encoding", "UTF-8",
"@" + optionsFile.getPath()
};
if (verbose)
print("ECJ options: " + structure(args));
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();
javaCompilerOutput = output;
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 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;
}
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_makeInternal() {
File dir = new File(userHomeInternal(), ".javax/" + TempDirMaker_newValue());
dir.mkdirs();
return dir;
}
public static File TempDirMaker_make() {
File dir = new File(userHome(), ".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 String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable<String> strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
// join
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 void cleanCache() {
cleanJavaXCache(tempFileRetentionTime, verbose);
}
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(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_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());
}
static Field set_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());
} // set function
static String smartJoin(String[] args) {
String[] a2 = new String[args.length];
for (int i = 0; i < args.length; i++) {
a2[i] = Pattern.compile("\\w+").matcher(args[i]).matches() ? args[i] : quote(args[i]);
}
return join(" ", a2);
}
static void logStart(String[] args) throws IOException {
String line = smartJoin(args);
appendToLog(new File(userHome(), ".javax/log.txt").getPath(), line);
}
static String quote(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
}
static void appendToLog(String path, String line) throws IOException {
appendToFile(path, "\n" + line + "\n");
}
static void appendToFile(String path, String s) throws IOException {
new File(path).getParentFile().mkdirs();
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path, true), "UTF-8"));
writer.write(s);
writer.close();
}
//// END CONSOLE STUFF
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static void print(Object o) {
System.out.println(o);
}
public synchronized void run()
{
}
static void nohupJavax(String javaxargs) {
try {
File xfile = new File(userHome(), ".javax/x30.jar");
if (!xfile.isFile()) {
String url = "http://tinybrain.de/x30.jar";
byte[] data = loadBinaryPage(new URL(url).openConnection());
if (data.length < 1000000)
throw new RuntimeException("Could not load " + url);
saveBinaryFile(xfile.getPath(), data);
}
String jarPath = xfile.getPath();
nohup("java -jar " + (isWindows() ? winQuote(jarPath) : bashQuote(jarPath)) + " " + javaxargs);
} catch (Exception e) { throw new RuntimeException(e); }
}
/** possibly improvable */
public static String winQuote(String text) {
if (text == null) return null;
return "\"" + text
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r") + "\"";
}
public static File nohup(String cmd) throws IOException {
File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out");
nohup(cmd, outFile, false);
return outFile;
}
static String nohup_sanitize(String s) {
return s.replaceAll("[^a-zA-Z0-9\\-_]", "");
}
/** outFile takes stdout and stderr. */
public static void nohup(String cmd, File outFile, boolean append) throws IOException {
String command = nohup_makeNohupCommand(cmd, outFile, append);
File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : "");
System.out.println("[Nohup] " + command);
try {
//System.out.println("[RealNohup] Script file: " + scriptFile.getPath());
saveTextFile(scriptFile.getPath(), command);
String[] command2;
if (isWindows())
command2 = new String[] {"cmd", "/c", "start", "/b", 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);
}
int value = process.exitValue();
//System.out.println("exit value: " + value);
} finally {
if (!isWindows())
scriptFile.delete();
}
}
public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) {
mkdirsForFile(outFile);
String command;
if (isWindows())
command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1";
else
command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &";
return command;
}
public static void mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) // is null if file is in current dir
dir.mkdirs();
}
static boolean portIsBound(int port) {
try {
ServerSocket s = new ServerSocket(port);
s.close();
return false;
} catch (IOException e) {
return true;
}
}
static class LineBuf {
StringBuffer buf = new StringBuffer();
void append(String s) {
buf.append(s);
}
String nextLine() {
int i = buf.indexOf("\n");
if (i >= 0) {
String s = buf.substring(0, i > 0 && buf.charAt(i-1) == '\r' ? i-1 : i);
buf.delete(0, i+1);
return s;
}
return null;
}
} // LineBuf
static int chatSend_chatPort = 9751;
static abstract class DialogIO {
String line;
boolean eos;
abstract String readLineImpl();
abstract boolean isStillConnected();
abstract void sendLine(String line);
abstract boolean isLocalConnection();
abstract Socket getSocket();
abstract void close();
int getPort() { return getSocket().getPort(); }
boolean helloRead;
String readLineNoBlock() {
String l = line;
line = null;
return l;
}
boolean waitForLine() { try {
if (line != null) return true;
//print("Readline");
line = readLineImpl();
//print("Readline done: " + line);
if (line == null) eos = true;
return line != null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
String readLine() {
waitForLine();
helloRead = true;
return readLineNoBlock();
}
String ask(String s, Object... args) {
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
sendLine(s);
return readLine();
}
String askLoudly(String s, Object... args) {
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
print("> " + s);
sendLine(s);
String answer = readLine();
print("< " + answer);
return answer;
}
void pushback(String l) {
if (line != null)
throw fail();
line = l;
helloRead = false;
}
}
static abstract class DialogHandler {
abstract void run(DialogIO io);
} // DialogIO
static DialogIO chatSend_dialog;
static String chatSend_id;
static void chatSend(String line) { try {
if (chatSend_dialog == null) {
chatSend_dialog = talkTo("localhost", chatSend_chatPort);
chatSend_dialog.waitForLine();
String l = chatSend_dialog.readLineNoBlock();
if (l.startsWith("Your ID: "))
chatSend_id = l.substring("Your ID: ".length());
}
chatSend_dialog.sendLine(line);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // chatSend
static class TeeOutputStream extends OutputStream {
protected OutputStream out, branch;
public TeeOutputStream( OutputStream out, OutputStream branch ) {
this.out = out;
this.branch = branch;
}
@Override
public synchronized void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public synchronized void write(byte[] b, int off, int len) throws IOException {
//if (verbose) oldOut.println("Tee write " + new String(b, "UTF-8"));
out.write(b, off, len);
this.branch.write(b, off, len);
}
@Override
public synchronized void write(int b) throws IOException {
write(new byte[] {(byte) b});
}
/**
* Flushes both streams.
* @throws IOException if an I/O error occurs
*/
@Override
public void flush() throws IOException {
out.flush();
this.branch.flush();
}
/**
* Closes both streams.
* @throws IOException if an I/O error occurs
*/
@Override
public void close() throws IOException {
out.close();
this.branch.close();
}
}
static boolean isChatServer(String[] args) {
for (int i = 0; i < args.length; i++)
if (isSnippetID(args[i]))
return parseSnippetID(args[i]) == 1000867;
return false;
}
static String getSnippetTitle(String id) {
try {
return loadPage(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title"));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }
}
static void listUserThreadsWithStackTraces() {
print("");
Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
int n = 0;
for (Thread t : threadMap.keySet()) {
ThreadGroup g = t.getThreadGroup();
if (g != null && g.getName().equals("system")) continue;
++n;
print(t);
for (StackTraceElement e : threadMap.get(t)) {
print(" " + e);
}
print("");
}
print(n + " user threads.");
}
static void killMyself() {
print("Killing myself. (insert overall feeling here)");
System.exit(0);
}
static void makeVMAndroid() {
Android3 a = new Android3("This is a JavaX VM.");
a.responder = new Responder() {
String answer(String s, List<String> history) {
return x30.answer(s, history);
}
};
a.daemon = true;
a.console = false;
a.incomingSilent = true; // to avoid too much printing
a.useMultiPort = false;
makeAndroid3(a);
}
static class Info {
String programID;
String[] programArgs;
File transpiledSrc;
Class mainClass;
}
static Info info = new Info(); // hmm...
// injectable info
static List<PaA> injectable_programsInjected = new ArrayList<PaA>();
static boolean injectable_on = true;
static class PaA {
String injectionID;
String progID;
String[] arguments;
Class mainClass; // TODO: release eventually...
WeakReference<Thread> mainThread;
volatile boolean mainDone;
volatile Throwable exception;
PaA(String progID, String[] arguments) {
this.arguments = arguments;
this.progID = progID;}
PaA() {}
}
static String vmID = makeRandomID(10);
static synchronized void addInjection(PaA paa) {
injectable_programsInjected.add(paa);
}
static synchronized void removeInjection(PaA paa) {
cleanUp(paa.mainClass);
injectable_programsInjected.remove(paa);
}
static synchronized List<PaA> getInjections() {
return cloneList(injectable_programsInjected);
}
static String answer(String s, List<String> history) { try {
Matches m = new Matches();
if (match3("kill!", s)) {
killMyself();
return "ok";
}
if (match3("What is your process ID?", s) || match3("what is your pid?", s))
return getPID();
if (match3("get vm id", s))
return vmID;
if (match3("what is the javax program id?", s))
return javaxProgramID;
if (match3("what is the main program id?", s))
return info.programID;
if (match3("what are your program arguments?", s))
return structure(info.programArgs);
if (match3("get fields of main class", s))
return structure(listFields(info.mainClass));
if (match3("get field * of main class", s, m))
return structure(get(info.mainClass, m.m[0]));
if (match3("invoke function * of main class", s, m))
return structure(call(info.mainClass, m.m[0]));
if (match3("set field * of main class to *", s, m)) {
set(info.mainClass, m.m[0], unstructure(m.m[1]));
return "ok";
}
if (match3("how much memory are you consuming", s))
return "Java heap size: " + (Runtime.getRuntime().totalMemory()+1024*1024-1)/1024/1024 + " MB";
if (match3("how much memory is used after GC?", s)) {
System.gc();
return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
}
if (match3("how much memory is used?", s))
return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
if (match3("please inject program *", s, m) || match3("please inject program * with arguments *", s, m)) {
synchronized(x30.class) {
final String progID = formatSnippetID(unquote(m.m[0]));
final String[] arguments = m.m.length > 1 ? toStringArray(unstructure(unquote(m.m[1]))) : new String[0];
final PaA paa = new PaA(progID, arguments);
paa.injectionID = randomID(8);
addInjection(paa);
// better call JavaX for translation in a single thread.
paa.mainClass = hotwire(progID);
// program may run in its own thread.
{ Thread _t_0 = new Thread(progID) {
public void run() {
try {
paa.mainThread = new WeakReference(currentThread());
try {
callMain(paa.mainClass, arguments);
} catch (Throwable e) {
paa.exception = e;
e.printStackTrace();
} finally {
paa.mainDone = true;
synchronized(x30.class) {}
}
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_0.start(); }
return format3("OK. Injection ID: *", paa.injectionID);
}
}
if (match3("get injection exception *", s, m)) {
String injectionID = unquote(m.m[0]);
PaA paa = findInjection(injectionID);
if (paa == null)
return "Sorry. Injection not found";
return "OK: " + paa.exception == null ? "no exception" : getStackTrace(paa.exception);
}
if (match3("get injection * variable *", s, m)) {
String injectionID = unquote(m.m[0]);
String var = unquote(m.m[1]);
PaA paa = findInjection(injectionID);
if (paa == null)
return "Sorry. Injection not found";
return "OK: " + structure(getOpt(paa.mainClass, var));
}
if (match3("get injection result *", s, m)) {
String injectionID = unquote(m.m[0]);
PaA paa = findInjection(injectionID);
if (paa == null)
return "Sorry. Injection not found";
return "OK: " + structure(getOpt(paa.mainClass, "result"));
}
if (match3("is injection's * main done", s, m)) {
String injectionID = unquote(m.m[0]);
PaA paa = findInjection(injectionID);
if (paa == null)
return "Sorry. Injection not found";
return paa.mainDone ? "Yes." : "No.";
}
if (match3("get injections", s, m)) {
return structure(getInjections());
}
if (match3("remove injection *", s, m)) {
String injectionID = unquote(m.m[0]);
PaA paa = findInjection(injectionID);
if (paa == null)
return "Sorry. Injection not found";
removeInjection(paa);
return "OK, removed.";
}
if (match3("which programs are you running (ids only)", s, m)) {
synchronized(x30.class) {
List<String> l = new ArrayList<String>();
for (String progID : instances.keySet())
if (getInstance(progID) != null)
l.add(progID);
return format3("these: *", structure(l));
}
}
List multiPorts = getMultiPorts();
if (!multiPorts.isEmpty()) {
Object multiPort = multiPorts.get(0);
String answer = makeResponder(multiPort).answer(s, history);
if (answer != null) return answer;
}
if (match3("list bots", s))
return structure(litmap());
return null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static synchronized PaA findInjection(String injectionID) {
for (PaA paa : injectable_programsInjected)
if (eq(paa.injectionID, injectionID))
return paa;
return null;
}
static int makeAndroid(String greeting) {
return makeAndroid3(greeting).port;
}
static void makeAndroid(Android3 a) {
makeAndroid3(a);
} // makeAndroid / makeAndroidNoConsole
static void setOpt(Object o, String field, Object value) {
if (o instanceof Class) setOpt((Class) o, field, value);
else try {
Field f = setOpt_findField(o.getClass(), field);
if (f != null)
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void setOpt(Class c, String field, Object value) {
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findField(Class<?> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field))
return f;
return null;
}
static Field setOpt_findStaticField(Class<?> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
return null;
} // setOpt
// get purpose 1: access a list/array (safer version of x.get(y))
static <A> A get(List<A> l, int idx) {
return idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static <A> A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
if (o.getClass().getName().equals("main$DynamicObject"))
return call(get_raw(o, "fieldValues"), "get", field);
return get_raw(o, field);
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class<?> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class<?> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
} // get
static Class getMainClass() { try {
return Class.forName("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // getMainClass
static DialogIO talkTo(int port) {
return talkTo("localhost", port);
}
static DialogIO talkTo(String ip, int port) { try {
final Socket s = new Socket(ip, port);
//print("Talking to " + ip + ":" + port);
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
return new DialogIO() {
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
String readLineImpl() { try {
return in.readLine();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // talkTo
static String[] toStringArray(List<String> list) {
return list.toArray(new String[list.size()]);
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof List)
return toStringArray((List<String>) o);
else
throw fail("Not a list or array: " + structure(o));
}
// toStringArray
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);
try {
data = loadBinaryPage(url.openConnection());
} catch (IOException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/"
+ parseSnippetID(snippetID));
System.err.println("Loading library: " + url);
data = loadBinaryPage(url.openConnection());
}
System.err.println("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static AtomicBoolean readLine_used = new AtomicBoolean();
static BufferedReader readLine_reader;
static String readLine() { try {
if (!readLine_used.compareAndSet(false, true))
throw fail("readLine is in use.");
try {
while (true) {
if (readLine_reader == null)
readLine_reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); // XX - is that right?
if (!readLine_reader.ready())
sleep(100);
else {
String s = readLine_reader.readLine();
if (s != null) {
print(s);
return s;
}
}
}
} finally {
readLine_used.set(false);
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static HashMap<String, WeakReference> weakrefs = new HashMap<String, WeakReference>();
// static WeakIdentityHashMap<O, S> reverseWeakrefs = new WeakIdentityHashMap<O, S>();
static long weakRefCounter;
// TODO: lookup in reverse map
static synchronized String weakref(Object o) {
if (o == null) return "null";
String id = vmID + "/" + ++weakRefCounter;
weakrefs.put(id, new WeakReference(o));
return id;
}
static synchronized Object getRef(String id) {
// TODO: clean up the list some time
WeakReference ref = weakrefs.get(id);
if (ref == null) return null;
return ref.get();
}
static List<Object> multiPorts = new ArrayList<Object>();
static synchronized List<Object> getMultiPorts() {
return cloneList(multiPorts);
}
// true if you're the first one
static synchronized boolean addMultiPort(Object o) {
multiPorts.add(o);
if (multiPorts.size() == 1) {
{ Thread _t_1 = new Thread("keep alive") {
public void run() {
try { x30.sleep(); } catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_1.start(); } // keep VM alive since there is a multiport
}
return multiPorts.size() == 1;
}
static synchronized void removeMultiPort(Object o) {
multiPorts.remove(o);
}
static String getInjectionID(Class mainClass) {
List<PaA> l = getInjections();
for (PaA injection : l)
if (injection.mainClass == mainClass)
return injection.injectionID;
return null;
}
static String getInjectionID() { return null; } // used somewhere...
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
print("Sleeping.");
synchronized(x30.class) { x30.class.wait(); }
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static WeakHashMap<Class, String> classToSourceCode = new WeakHashMap<Class, String>();
synchronized static void registerSourceCode(Class c, String src) {
classToSourceCode.put(c, src);
}
synchronized static String getSourceCodeForClass(Class c) {
return classToSourceCode.get(c);
}
static class Matches {
String[] m;
String get(int i) { return m[i]; }
String unq(int i) { return unquote(m[i]); }
String fsi(int i) { return formatSnippetID(unq(i)); }
String fsi() { return fsi(0); }
String tlc(int i) { return unq(i).toLowerCase(); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
int psi(int i) { return Integer.parseInt(unq(i)); }
}
// Matches
// get main class of first program (for console)
static Object getMainMainClass() {
PaA paa = first(getInjections());
return paa == null ? null : paa.mainClass;
}
static boolean _inCore() {
return true;
}
// This is for main classes that are all static.
// (We don't go to base classes.)
static Set<String> listFields(Object c) {
TreeSet<String> fields = new TreeSet<String>();
for (Field f : ((Class) c).getDeclaredFields())
fields.add(f.getName());
return fields;
}
static Thread currentThread() {
return Thread.currentThread();
}
static <A> List<A> cloneList(Collection<A> l) {
//O mutex = getOpt(l, "mutex");
/*if (mutex != null)
synchronized(mutex) {
ret new ArrayList<A>(l);
}
else
ret new ArrayList<A>(l);*/
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(l) {
return new ArrayList<A>(l);
}
}
static Map litmap(Object... x) {
TreeMap map = new TreeMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static void cleanJavaXCache(int retentionHours, boolean verbose) {
try {
if (verbose)
System.out.println("Cleaning JavaX Cache (" + retentionHours + " hours retention time)");
int fileDeletions = 0;
for (String userDir : litlist(userHome(), userHomeInternal())) {
File javax = new File(userHome(), ".javax");
long now = now();
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 >= retentionHours) {
//System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
fileDeletions += cleanJavaXCache_removeDir(dir, verbose);
}
}
}
}
if (verbose && fileDeletions != 0)
print("Cleaned cache. File deletions: " + fileDeletions);
} catch (Throwable __e) { printStackTrace(__e); }
}
static int cleanJavaXCache_removeDir(File dir, boolean verbose) {
int fileDeletions = 0;
if (dir.getAbsolutePath().indexOf(".javax") < 0) // security check!
throw fail("WHAT ARE YOU DOING!? >> " + dir.getAbsolutePath());
for (File f : dir.listFiles()) {
if (f.isDirectory())
cleanJavaXCache_removeDir(f, verbose);
else {
if (verbose)
print("Deleting " + f.getAbsolutePath());
f.delete();
++fileDeletions;
}
}
dir.delete();
return fileDeletions;
}
static String fsi(String id) {
return formatSnippetID(id);
}
static String boss(String line) {
try {
//S s = sendToLocalBotOpt("Boss Bot", line);
DialogIO io = talkTo(4990); // Boss Bot port
io.readLine();
io.sendLine(line);
String s = io.readLine();
Matches m = new Matches();
if (match3("text: *", s, m))
return unquote(m.m[0]);
return null;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
static class DynamicObject {
String className;
Map<String, Object> fieldValues = new TreeMap<String, Object>();
}
static Object unstructure(String text) {
return unstructure(text, false);
}
// TODO: backrefs for hashmap{} etc
static Object unstructure(String text, final boolean allDynamic) {
if (text == null) return null;
final List<String> tok = javaTok(text);
final boolean debug = unstructure_debug;
class X {
int i = 1;
HashMap<Integer, Object> refs = new HashMap<Integer, Object>();
Object parse() {
String t = tok.get(i);
int refID = 0;
if (t.startsWith("m") && isInteger(t.substring(1))) {
refID = parseInt(t.substring(1));
i += 2;
t = tok.get(i);
}
if (debug)
print("parse: " + quote(t));
if (t.startsWith("\"")) {
String s = unquote(tok.get(i));
i += 2;
return s;
}
if (t.startsWith("'")) {
char c = unquoteCharacter(tok.get(i));
i += 2;
return c;
}
if (t.equals("bigint"))
return parseBigInt();
if (t.equals("d"))
return parseDouble();
if (t.equals("false") || t.equals("f")) {
i += 2; return false;
}
if (t.equals("true") || t.equals("t")) {
i += 2; return true;
}
if (t.equals("-")) {
t = tok.get(i+2);
i += 4;
return isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t));
}
if (isInteger(t) || isLongConstant(t)) {
i += 2;
if (debug)
print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) return parseLong(t);
long l = parseLong(t);
return l != (int) l ? new Long(l) : new Integer((int) l);
}
if (t.equals("File")) {
File f = new File(unquote(tok.get(i+2)));
i += 4;
return f;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
i += 2;
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
return o;
}
return parse_inner(refID);
}
// everything that can be backreferenced
Object parse_inner(int refID) {
String t = tok.get(i);
if (debug)
print("parse_inner: " + quote(t));
if (t.equals("hashset"))
return parseHashSet();
if (t.equals("treeset"))
return parseTreeSet();
if (t.equals("hashmap"))
return parseHashMap();
if (t.equals("{"))
return parseMap();
if (t.equals("["))
return parseList();
if (t.equals("array"))
return parseArray();
if (t.equals("class"))
return parseClass();
if (t.equals("l"))
return parseLisp();
if (t.equals("null")) {
i += 2; return null;
}
if (isJavaIdentifier(t)) {
Class c = allDynamic ? null : findClass(t);
DynamicObject dO = null;
Object o = null;
if (c != null)
o = nuObject(c);
else {
dO = new DynamicObject();
dO.className = t;
}
if (refID != 0)
refs.put(refID, o);
i += 2;
if (i < tok.size() && tok.get(i).equals("(")) {
consume("(");
while (!tok.get(i).equals(")")) {
// It's like parsing a map.
//Object key = parse();
//if (tok.get(i).equals(")"))
// key = onlyField();
String key = unquote(tok.get(i));
i += 2;
consume("=");
Object value = parse();
if (o != null)
setOpt(o, key, value);
else
dO.fieldValues.put(key, value);
if (tok.get(i).equals(",")) i += 2;
}
consume(")");
}
return o != null ? o : dO;
}
throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
}
Object parseSet(Set set) {
set.addAll((List) parseList());
return set;
}
Object parseLisp() {
consume("l");
consume("(");
List list = new ArrayList();
while (!tok.get(i).equals(")")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume(")");
return newObject("main$Lisp", (String) list.get(0), subList(list, 1));
}
Object parseList() {
consume("[");
List list = new ArrayList();
while (!tok.get(i).equals("]")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume("]");
return list;
}
Object parseArray() {
consume("array");
consume("{");
List list = new ArrayList();
while (!tok.get(i).equals("}")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume("}");
return list.toArray();
}
Object parseClass() {
consume("class");
consume("(");
String name = tok.get(i);
i += 2;
consume(")");
Class c = allDynamic ? null : findClass(name);
if (c != null) return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
dO.fieldValues.put("name", name);
return dO;
}
Object parseBigInt() {
consume("bigint");
consume("(");
String val = tok.get(i);
i += 2;
if (eq(val, "-")) {
val = "-" + tok.get(i);
i += 2;
}
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tok.get(i));
i += 2;
consume(")");
return Double.parseDouble(val);
}
Object parseHashMap() {
consume("hashmap");
return parseMap(new HashMap());
}
Object parseHashSet() {
consume("hashset");
return parseSet(new HashSet());
}
Object parseTreeSet() {
consume("treeset");
return parseSet(new TreeSet());
}
Object parseMap() {
return parseMap(new TreeMap());
}
Object parseMap(Map map) {
consume("{");
while (!tok.get(i).equals("}")) {
Object key = parse();
consume("=");
Object value = parse();
map.put(key, value);
if (tok.get(i).equals(",")) i += 2;
}
consume("}");
return map;
}
void consume(String s) {
if (!tok.get(i).equals(s)) {
String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
}
i += 2;
}
}
return new X().parse();
}
static boolean unstructure_debug;
static <A> ArrayList<A> litlist(A... a) {
return new ArrayList<A>(Arrays.asList(a));
}
static ThreadLocal<String> loadPage_charset = new ThreadLocal<String>();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous; // don't send computer ID
static int loadPage_verboseness = 100000;
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPageSilently(URL url) {
try {
IOException e = null;
for (int tries = 0; tries < 60; tries++)
try {
URLConnection con = url.openConnection();
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
print("Retrying because of: " + e);
sleepSeconds(1);
}
throw e;
} catch (IOException e) { throw new RuntimeException(e); }
}
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = "tinybrain.de:8080/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
return loadPage(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
try {
if (!loadPage_anonymous) {
String computerID = getComputerID();
if (computerID != null)
con.setRequestProperty("X-ComputerID", computerID);
}
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
InputStream in = con.getInputStream();
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read");
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\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";
}
static int l(Object[] array) {
return array == null ? 0 : array.length;
}
static int l(byte[] array) {
return array == null ? 0 : array.length;
}
static int l(int[] array) {
return array == null ? 0 : array.length;
}
static int l(char[] array) {
return array == null ? 0 : array.length;
}
static int l(Collection c) {
return c == null ? 0 : c.size();
}
static int l(Map m) {
return m == null ? 0 : m.size();
}
static int l(String s) {
return s == null ? 0 : s.length();
}
static String getServerTranspiled2(String id) {
String transpiled = loadCachedTranspilation(id);
String md5 = null;
try { /* pcall 1*/
if (transpiled != null)
md5 = md5(transpiled);
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
String transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
if (eq(transpiledSrc, "SAME")) {
print("SAME");
transpiledSrc = loadCachedTranspilation(formatSnippetID(id));
}
return transpiledSrc;
}
static String loadCachedTranspilation(String id) {
return loadTextFile(new File(getCodeProgramDir(id), "Transpilation"));
}
static Object call(Object o) {
return callFunction(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
try {
if (o instanceof Class) {
Method m = call_findStaticMethod((Class) o, method, args, false);
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = call_findMethod(o, method, args, false);
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
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("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;
}
static Object first(Object list) {
return ((List) list).isEmpty() ? null : ((List) list).get(0);
}
static <A> A first(List<A> list) {
return list.isEmpty() ? null : list.get(0);
}
static <A> A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static String format3(String pat, Object... args) {
if (args.length == 0) return pat;
List<String> tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2)
if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static String format3_formatArg(Object arg) {
if (arg == null) return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
return quote(structure(arg));
}
// class Matches is added by #752
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (s == null) return false;
return match3(pat, parse3(s), matches);
}
static boolean match3(String pat, List<String> toks, Matches matches) {
List<String> tokpat = parse3(pat);
return match3(tokpat,toks,matches);
}
static boolean match3(List<String> tokpat, List<String> toks, Matches matches) {
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean daemon = false;
boolean incomingSilent = false;
boolean useMultiPort = true;
boolean verbose;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
//print("Dispoing virtual port " + vport);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace(__e); }
}
}
static abstract class Responder {
abstract String answer(String s, List<String> history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List<String> history) {
return callStaticAnswerMethod(s, history);
}
};
print(a.greeting);
if (a.useMultiPort) {
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.vport == 1)
makeAndroid3_handleConsole(a);
return a;
}
a.handler = makeAndroid3_makeDialogHandler(a);
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
a.server = startDialogServer_serverSocket;
if (a.console && makeAndroid3_consoleInUse()) a.console = false;
if (a.console)
makeAndroid3_handleConsole(a);
record(a);
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() {
try {
List<String> history = new ArrayList<String>();
String line;
while ((line = readLine()) != null) {
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList<S>();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_0.start(); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List<String> history = new ArrayList<String>();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(s);
if (line == "bye") {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else
answer = makeAndroid3_getAnswer(line, history, a);
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List<String> history, Android3 a) {
String answer;
try {
answer = makeAndroid3_fallback(line, history, a.responder.answer(line, history));
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
answer = e.toString();
}
if (!a.incomingSilent)
print("> " + shorten(answer, 500));
return answer;
}
static String makeAndroid3_fallback(String s, List<String> history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List<String> history) {
if (a.verbose)
print("> " + s);
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + answer);
return answer;
}
};
}
static void callMain(Object c, String... args) {
callOpt(c, "main", new Object[] {args});
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
static boolean empty(Map map) {
return map == null || map.isEmpty();
}
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
return false;
}
static String getServerTranspiled(String snippetID) {
return getServerTranspiled(snippetID, null);
}
// returns "SAME" if md5 matches
static String getServerTranspiled(String snippetID, String expectedMD5) { try {
long id = parseSnippetID(snippetID);
/*S t = getTranspilationFromBossBot(id);
if (t != null) return t;*/
String text = loadPage_utf8("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1"
+ (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "")
+ standardCredentials());
if (nempty(text) && neq(text, "SAME"))
saveTranspiledCode(snippetID, text);
return text;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
/** 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";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = new FileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String getStackTrace(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
// extended over Class.isInstance() to handle primitive types
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;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static boolean eq(Object a, Object b) {
if (a == null) return b == null;
if (a.equals(b)) return true;
if (a instanceof BigInteger) {
if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
}
return false;
}
static String getSnippetFromBossBot(long snippetID) {
return boss(format3("get text for *", snippetID));
}
static <A, B> Set<A> keys(Map<A, B> map) {
return map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
// try to get our current process ID
static String getPID() {
String name = ManagementFactory.getRuntimeMXBean().getName();
return name.replaceAll("@.*", "");
}
public static String unquote(String s) {
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if (s.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) {
String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length());
StringBuilder sb = new StringBuilder(st.length());
for (int i = 0; i < st.length(); i++) {
char ch = st.charAt(i);
if (ch == '\\') {
char nextChar = (i == st.length() - 1) ? '\\' : st
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= st.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + st.charAt(i + 2) + st.charAt(i + 3)
+ st.charAt(i + 4) + st.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
} else
return s; // return original
}
// compile JavaX source, load classes & return main class
// src can be a snippet ID or actual source code
// TODO: record injection?
static Class<?> hotwire(String src) {
try {
Class j = getJavaX();
synchronized(j) { // hopefully this goes well...
List<File> libraries = new ArrayList<File>();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
if (androidContext != null)
return (Class) call(j, "loadx2android", srcDir, src);
File classesDir = (File) call(j, "TempDirMaker_make");
String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
System.out.println(javacOutput);
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 & return main class
Class<?> theClass = classLoader.loadClass("main");
callOpt(j, "registerSourceCode", theClass, loadTextFile(new File(srcDir, "main.java")));
call(j, "setVars", theClass, isSnippetID(src) ? src: null);
if (isSnippetID(src))
callOpt(j, "addInstance", src, theClass);
if (!_inCore())
hotwire_copyOver(theClass);
return theClass;
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
f.set(o, value);
}
static String structure(Object o) {
HashSet refd = new HashSet();
return structure_2(structure_1(o, 0, new IdentityHashMap(), refd), refd);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static String structure_1(Object o, int stringSizeLimit, IdentityHashMap<Object, Integer> seen, HashSet<Integer> refd) {
if (o == null) return "null";
// these are never back-referenced (for readability)
if (o instanceof String)
return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
if (o instanceof BigInteger)
return "bigint(" + o + ")";
if (o instanceof Double)
return "d(" + quote(str(o)) + ")";
if (o instanceof Long)
return o + "L";
if (o instanceof Integer)
return str(o);
if (o instanceof Boolean)
return ((Boolean) o).booleanValue() ? "t" : "f";
if (o instanceof Character)
return quoteCharacter((Character) o);
if (o instanceof File)
return "File " + quote(((File) o).getPath());
// referencable objects follow
Integer ref = seen.get(o);
if (ref != null) {
refd.add(ref);
return "r" + ref;
}
ref = seen.size()+1;
seen.put(o, ref);
String r = "m" + ref + " "; // marker
String name = o.getClass().getName();
StringBuilder buf = new StringBuilder();
if (o instanceof HashSet)
return r + "hashset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd);
if (o instanceof TreeSet)
return r + "treeset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd);
if (o instanceof Collection) {
for (Object x : (Collection) o) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(x, stringSizeLimit, seen, refd));
}
return r + "[" + buf + "]";
}
if (o instanceof Map) {
for (Object e : ((Map) o).entrySet()) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(((Map.Entry) e).getKey(), stringSizeLimit, seen, refd));
buf.append("=");
buf.append(structure_1(((Map.Entry) e).getValue(), stringSizeLimit, seen, refd));
}
return r + (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}";
}
if (o.getClass().isArray()) {
int n = Array.getLength(o);
for (int i = 0; i < n; i++) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(Array.get(o, i), stringSizeLimit, seen, refd));
}
return r + "array{" + buf + "}";
}
if (o instanceof Class)
return r + "class(" + quote(((Class) o).getName()) + ")";
if (o instanceof Throwable)
return r + "exception(" + quote(((Throwable) o).getMessage()) + ")";
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (buf.length() != 0) buf.append(", ");
buf.append(i);
}
return "bitset{" + buf + "}";
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax."))
return r + String.valueOf(o);
String shortName = o.getClass().getName().replaceAll("^main\\$", "");
if (shortName.equals("Lisp")) {
buf.append("l(" + structure_1(getOpt(o, "head"), stringSizeLimit, seen, refd));
List args = (List) ( getOpt(o, "args"));
if (nempty(args))
for (int i = 0; i < l(args); i++) {
buf.append(", ");
Object arg = args.get(i);
// sweet shortening
if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty")))
arg = get(arg, "head");
buf.append(structure_1(arg, stringSizeLimit, seen, refd));
}
buf.append(")");
return r + str(buf);
}
int numFields = 0;
String fieldName = "";
if (shortName.equals("DynamicObject")) {
shortName = (String) get(o, "className");
Map<String, Object> fieldValues = (Map) get(o, "fieldValues");
for (String _fieldName : fieldValues.keySet()) {
fieldName = _fieldName;
Object value = fieldValues.get(fieldName);
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd));
}
++numFields;
}
} else {
// regular class
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
fieldName = field.getName();
// skip outer object reference
if (fieldName.indexOf("$") >= 0) continue;
Object value;
try {
field.setAccessible(true);
value = field.get(o);
} catch (Exception e) {
value = "?";
}
// put special cases here...
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd));
}
++numFields;
}
c = c.getSuperclass();
}
}
String b = buf.toString();
if (numFields == 1 && structure_allowShortening)
b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
String s = shortName;
if (buf.length() != 0)
s += "(" + b + ")";
return r + s;
}
// drop unused markers
static String structure_2(String s, HashSet<Integer> refd) {
List<String> tok = javaTok(s);
StringBuilder out = new StringBuilder();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("m") && isInteger(t.substring(1))
&& !refd.contains(parseInt(t.substring(1))))
continue;
out.append(t).append(tok.get(i+1));
}
return str(out);
}
static boolean master() {
return webAuthed() || litlist("stefanreich", "bgrgndz", "okhan", "mrshutco").contains(getUserName());
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static String randomID(int length) {
return makeRandomID(length);
}
static String makeResponder_callAnswerMethod(Object bot, String s, List<String> history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
return new Responder() {
String answer(String s, List<String> history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
static Object getOpt(Object o, String field) {
if (o instanceof String) o = getBot ((String) o);
if (o == null) return null;
if (o instanceof Class) return getOpt((Class) o, field);
if (o.getClass().getName().equals("main$DynamicObject"))
return ((Map) getOpt_raw(o, "fieldValues")).get(field);
if (o instanceof Map) return ((Map) o).get(field);
return getOpt_raw(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object getOpt(Class c, String field) {
try {
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class<?> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field getOpt_findField(Class<?> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object callFunction(Object f, Object... args) {
if (f == null) return null;
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
} else if (f instanceof String)
return call(mc(), (String) f, args);
else
return call(f, "get", args);
//else throw fail("Can't call a " + getClassName(f));
}
static String shorten(String s, int max) {
if (s == null) return "";
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static List<Object> record_list = synchroList();
static void record(Object o) {
record_list.add(o);
}
static Object getBot(String botID) {
return callOpt(getMainBot(), "getBot", botID);
}
static String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
return "'" + c + "'";
}
static String loadPage_utf8(String url) {
loadPage_charset.set("UTF-8");
try {
return loadPage(url);
} finally {
loadPage_charset.set(null);
}
}
static void printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
try {
return Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
return null;
}
}
static void removeFromMultiPort(long vport) {
for (Object port : getMultiPorts())
call(port, "removePort", vport);
}
static String str(Object o) {
return String.valueOf(o);
}
static boolean isJavaIdentifier(String s) {
if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static Object addToMultiPort_responder;
static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List<String> history) {
String answer = (String) ( callOpt(getMainClass(), "answer", s, history));
if (answer != null) return answer;
answer = (String) callOpt(getMainClass(), "answer", s);
if (answer != null) return answer;
if (match3("get injection id", s))
return getInjectionID();
return null;
}
});
}
static long addToMultiPort(final String botName, final Object responder) {
print(botName);
addToMultiPort_responder = responder;
startMultiPort();
List ports = getMultiPorts();
if (ports == null) return 0;
if (ports.isEmpty())
throw fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
Object responder2 = new Object() {
public String answer(String s, List<String> history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
};
record(responder2);
return (Long) call(port, "addResponder", botName, responder2);
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetID(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static String unnull(String s) {
return s == null ? "" : s;
}
static <A> List<A> unnull(List<A> l) {
return l == null ? emptyList() : l;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings
static List<String> javaTok(String s) {
List<String> tok = new ArrayList<String>();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i); // cc is not needed in rest of loop body
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static List<String> javaTok(List<String> tok) {
return javaTok(join(tok));
}
static List<String> parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static Object newObject(Class c, Object... args) {
return nuObject(c, args);
}
static Object newObject(String className, Object... args) {
return nuObject(className, args);
}
static boolean isLongConstant(String s) {
if (!s.endsWith("L")) return false;
s = s.substring(0, l(s)-1);
return isInteger(s);
}
static Class __javax;
static Class getJavaX() {
return __javax;
}
static <A> List<A> subList(List<A> l, int startIndex) {
return subList(l, startIndex, l(l));
}
static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
startIndex = max(0, min(l(l), startIndex));
endIndex = max(0, min(l(l), endIndex));
if (startIndex > endIndex) return litlist();
return l.subList(startIndex, endIndex);
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static boolean isTrue(Object o) {
return booleanValue(o);
}
static long parseLong(String s) {
if (s == null) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List<String> pat, List<String> tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList<String>(pat); // We're modifying it, so copy first
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i+1, ""); // doesn't matter
}
return match2_match(pat, tok);
}
static String[] match2_match(List<String> pat, List<String> tok) {
List<String> result = new ArrayList<String>();
if (pat.size() != tok.size()) {
/*if (debug)
print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
/*if (debug)
print("Checking " + p + " against " + t);*/
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
return null;
}
return result.toArray(new String[result.size()]);
}
static void hotwire_copyOver(Class c) {
synchronized(StringBuffer.class) {
for (String field : litlist("print_log", "print_silent")) {
Object o = get(mc(), field);
if (o != null)
setOpt(c, field, o);
}
Object mainBot = getMainBot();
if (mainBot != null)
setOpt(c, "mainBot", mainBot);
setOpt(c, "creator_class", new WeakReference(mc()));
}
}
static Class<?> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class _getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static String getUserName() {
return (String) callOpt(getMainBot(), "getUserName");
}
static boolean isNonNegativeInteger(String s) {
return s != null && Pattern.matches("\\d+", s);
}
static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Object nuObject(Object realm, String className, Object... args) {
return nuObject(_getClass(realm, className), args);
}
static <A> A nuObject(Class<A> c, Object... args) { try {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
}
static boolean nuObject_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;
}
// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).
static List<String> javaTokPlusPeriod(String s) {
List<String> tok = new ArrayList<String>();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == '\u201C' || c == '\u201D') c = '"'; // normalize quotes
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == '\u201C' || _c == '\u201D') _c = '"'; // normalize quotes
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
if (j-1 >= i+1) {
tok.add(opener + s.substring(i+1, j-1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else if (s.substring(j, Math.min(j+3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static void sleepSeconds(long s) {
if (s > 0) sleep(s*1000);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
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 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_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) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class<?>[] types = m.getParameterTypes();
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;
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static AtomicInteger dialogServer_clients = new AtomicInteger();
static boolean dialogServer_printConnects;
static Set<String> dialogServer_knownClients = synchroTreeSet();
static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!startDialogServerIfPortAvailable(port, handler))
++port;
return port;
}
static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!startDialogServerIfPortAvailable(port, handler, true))
++port;
return port;
}
static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
static ServerSocket startDialogServer_serverSocket;
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// probably the port number is used - let's assume there already is a chat server.
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) { public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
// This should be the same as #1001076 (talkTo)
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
String readLineImpl() { try {
return in.readLine();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
//print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
}
}
}; // Thread t2
t2.setDaemon(true); // ?
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}};
if (daemon) thread.setDaemon(true);
thread.start();
print("Dialog server on port " + port + " started.");
return true;
}
static boolean webAuthed() {
return eq(Boolean.TRUE, callOpt(getBot("#1002590"), "currentHttpRequestAuthorized"));
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static String callStaticAnswerMethod(List<Class> bots, String s) {
for (Class c : bots) try {
String answer = callStaticAnswerMethod(c, s);
if (!empty(answer)) return answer;
} catch (Throwable e) {
print("Error calling " + getProgramID(c));
e.printStackTrace();
}
return null;
}
static String callStaticAnswerMethod(Class c, String s) {
String answer = (String) callOpt(c, "answer", s, litlist(s));
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
static String callStaticAnswerMethod(String s, List<String> history) {
String answer = (String) callOpt(getMainClass(), "answer", s, history);
if (answer == null)
answer = (String) callOpt(getMainClass(), "answer", s);
return emptyToNull(answer);
}
static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static boolean equalsIgnoreCase(String a, String b) {
return a == null ? b == null : a.equalsIgnoreCase(b);
}
static <A> Set<A> synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet<A>());
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static void assertTrue(Object o) {
assertEquals(true, o);
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static int max(int a, int b) {
return Math.max(a, b);
}
static long max(int a, long b) {
return Math.max((long) a, b);
}
static long max(long a, long b) {
return Math.max(a, b);
}
static double max(int a, double b) {
return Math.max((double) a, b);
}
static int max(Collection<Integer> c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static Class<?> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Class mc() {
return getMainClass();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static <A> A last(List<A> l) {
return l.isEmpty() ? null : l.get(l.size()-1);
}
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static String emptyToNull(String s) {
return eq(s, "") ? null : s;
}
static boolean booleanValue(Object o) {
return eq(true, o);
}
static Method findMethod(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = findMethod_static((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
} else {
Method m = findMethod_instance(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method findMethod_static(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
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 || !findMethod_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method findMethod_instance(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) && findMethod_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class<?>[] types = m.getParameterTypes();
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;
}
static <A> List<A> synchroList() {
return Collections.synchronizedList(new ArrayList<A>());
}
static <A> List<A> synchroList(List<A> l) {
return Collections.synchronizedList(l);
}
static List<String> dropPunctuation_keep = litlist("*", "<", ">");
static List<String> dropPunctuation(List<String> tok) {
tok = new ArrayList<String>(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i-1, tok.get(i-1) + tok.get(i+1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
// start multi-port if none exists in current VM.
static void startMultiPort() {
List mp = getMultiPorts();
if (mp != null && mp.isEmpty())
callMain(hotwire("#1001672"));
}
static <A> A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static <A> A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y));
return y;
}
static List<String> nlTok(String s) {
return javaTokPlusPeriod(s);
}
static boolean match(String pat, String s) {
return match3(pat, s);
}
static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static void cleanUp(Object c) {
if (c instanceof List) { cleanUp((List) c); return; }
if (!(c instanceof Class)) return;
try { /* pcall 1*/
// revoke license
callOpt(c, "licensed_off");
// call custom cleanUp() function
try { /* pcall 1*/ callOpt(c, "cleanMeUp"); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
// remove all virtual bots (does this work?)
List androids = (List) getOpt(c, "record_list");
List ports = getMultiPorts();
if (androids != null)
for (Object port : ports)
for (Object android : androids)
callOpt(android, "dispose"); // heck we'll dispose anything
// sub-cleanup
List<WeakReference> classes = (List<WeakReference>) ( getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) try { /* pcall 1*/
cleanUp(cc.get());
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
}
static void cleanUp(List l) {
for (Object c : l)
cleanUp(c);
l.clear();
}
static String standardCredentials() {
String user = trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
String pass = trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static byte[] loadBinaryPage(String url) {
try {
return loadBinaryPage(new URL(url).openConnection());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
public static void copyFile(File src, File dest) { try {
mkdirsForFile(dest);
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = new FileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void copyStream(InputStream in, OutputStream out) { try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String hideCredentials(String url) {
return url.replaceAll("&_pass=[^&]*", "&_pass=<hidden>");
}
}Began life as a copy of #1004182
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: | #1007390 |
| Snippet name: | x30 for Android (backup before multiport) |
| Eternal ID of this version: | #1007390/1 |
| Text MD5: | 910bdce1b6093dded261f02f06aac8d3 |
| Author: | stefan |
| Category: | javax / android |
| Type: | JavaX source code (Android) |
| Public (visible to everyone): | Yes |
| Archived (hidden from active list): | No |
| Created/modified: | 2017-03-21 11:49:34 |
| Source code size: | 165766 bytes / 5160 lines |
| Pitched / IR pitched: | No / No |
| Views / Downloads: | 823 / 775 |
| Referenced in: | [show references] |