import java.math.*;
import javax.imageio.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.*;
import java.security.spec.*;
import java.security.*;
import java.lang.management.*;
import java.lang.ref.*;
import java.lang.reflect.*;
import java.net.*;
import java.io.*;
import javax.swing.table.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.List;
import java.util.zip.*;
import java.util.*;
public class main {
// a persistent map using a clever combination of persisting and logging
// (well, only logging as of now)
// Note: don't put in static initializer (programID not set yet)
static class PersistentMap extends AbstractMap {
Map m = new TreeMap();
File file;
PersistentMap(String fileName) {
this(getProgramFile(fileName));
}
PersistentMap(String progID, String fileName) {
this(getProgramFile(progID, fileName));
}
PersistentMap(File file) {
this.file = file;
for (String s : scanLog(file)) try {
List l = (List) ( unstructure(s));
if (eq(l.get(0), "add"))
m.put((A) l.get(1), (B) l.get(2));
else if (eq(l.get(0), "remove"))
m.remove((A) l.get(1));
else
print("Unknown command in log: " + l.get(0));
} catch (Throwable __e) { printStackTrace(__e); }
}
// just delegates
public int size() {
return m.size();
}
public B get(Object a) {
return m.get(a);
}
// TODO: calling remove() in the iterator will have unpersisted
// effects.
public Set> entrySet() {
return m.entrySet();
}
// delegates with logging
public B put(A a, B b) {
B result = m.put(a, b);
logQuoted(file, structure(litlist("add", a, b)));
return result;
}
public B remove(Object a) {
B result = m.remove(a);
logQuoted(file, structure(litlist("remove", a)));
return result;
}
}
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)); }
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)); }
}
static List turingTests = new ArrayList();
public static void main(String[] args) throws Exception {
load("turingTests");
}
synchronized static String answer(String s) {
Matches m = new Matches();
if (match("turing score", s, m)) return getTuringScore();
if (match("turing tests", s, m)) return structure(turingTests);
if (match("tests running", s, m)) return structure(testsRunning); // TODO: solve the sync problem
String _a_0 = manageSnippetList(s, "turing test", "turingTests"); if (!empty(_a_0)) return _a_0;
if (match("run turing test *", s, m)) {
String id = m.fsi(0);
if (!turingTests.contains(id))
return "Not a turing test: " + id;
runTestAsync(id);
String url = mainURL() + "1002408?id=" + parseSnippetID(id);
return "Test " + shortSnippetLink(id) + " running. Check result here: " + url;
}
return null;
}
static String html(String subUri, Map params) {
List keepFields = litlist();
String protocolID = params.get("id");
String html = htag("p", "Eleutheria's current Turing score: " + htag("b", getTuringScore()));
html += htag("p", "Tests running: " + structure(testsRunning));
if (isSnippetID(protocolID)) {
String protocol = loadTextFile(getProgramFile(protocolID, "protocol-" + urlencode(getTuringScore_eleuURL)));
html += tag("h3", "Protocol of " + quote(getSnippetTitle(protocolID)) + " (" + formatSnippetID(protocolID) + ")") +
sourceCodeToHTML(protocol);
}
html += tag("h3", "Tests");
html += "";
for (String id : turingTests)
html += tag("li",
tag("a", formatSnippetID(id) + " - " + getSnippetTitle(id), "href", selfLink(params, keepFields, "id", "" + parseSnippetID(id))) + " " +
tag("a", "[source]", "href", "http://tinybrain.de/" + parseSnippetID(id)));
html += "
";
return html;
}
static String snippetLink(String id) {
return tag("a", formatSnippetID(id) + " - " + getSnippetTitle(id), "href", "http://tinybrain.de/" + parseSnippetID(id));
}
static String getTuringScore_eleuURL = "http://bots.tinybrain.de/1002076/raw";
static String getTuringScore() {
long s = 0, n = 0;
int tests = 0;
for (String testID : turingTests) try {
PersistentMap scores = new PersistentMap(testID, "turing-scores.map");
Object score = scores.get(getTuringScore_eleuURL);
if (score == null) continue;
s += (long) get(score, "score");
n += (long) get(score, "n");
++tests;
} catch (Throwable __e) { printStackTrace(__e); }
String result = s + " of " + n + " points (" + n(tests, "test");
int notRun = l(turingTests)-tests;
if (notRun > 0)
result += ", " + notRun + " not run yet";
return result + ")";
}
static List testsRunning = synchroList();
static void runTestAsync(final String testID) {
Runnable code = new Runnable() {
public void run() { try {
testsRunning.add(testID);
try {
Class test = main.hotwire(testID);
setOpt(test, "mainBot", getMainBot()); // let test know that we are in Eleu process (allows for faster testing)
callMain(test);
} finally {
testsRunning.remove(testID);
}
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}};
Object processManager = getBot("#1002558");
if (processManager == null)
new Thread(code).start();
else
call(processManager, "start", "Turing Test " + testID, code);
}
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 String htag(String tag, String contents, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
for (int i = 0; i < l(params); i += 2) {
Object val = get(params, i+1);
if (val != null) {
String s = str(val);
if (!empty(s))
buf.append(" " + get(params, i) + "=" + htmlQuote(s));
}
}
buf.append(">" + contents + "" + tag + ">");
return str(buf);
}
// the usual convenience shortcut for StringBuilder instead of string...
static String htag(String tag, StringBuilder contents, Object... params) {
return htag(tag, str(contents), params);
}
// same with StringBuffer
static String htag(String tag, StringBuffer contents, Object... params) {
return htag(tag, str(contents), params);
}
static void callMain(Object c, String... args) {
callOpt(c, "main", new Object[] {args});
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) fail("0 is not a snippet ID");
return id;
}
static String quote(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
}
static String quote(long l) {
return quote("" + l);
}
static void load(String varName) {
readLocally(varName);
}
static void load(String progID, String varName) {
readLocally(progID, varName);
}
static String shortSnippetLink(String id) {
return parseSnippetID(id) + ".tinybrain.de";
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
// get purpose 1: access a list/array (safer version of x.get(y))
static A get(List l, int idx) {
return idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// get purpose 2: access a field by reflection
static Object get(Object o, String field) {
if (o instanceof Class) return get((Class) o, 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());
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static Object getBot(String botID) {
return call(getMainBot(), "getBot", botID);
}
static String tag(String tag, String contents, Object... params) {
return htag(tag, contents, params);
}
static String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static File getProgramFile(String progID, String fileName) {
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), 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();
}
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 synchronized String manageSnippetList(String s, String name, String varName) {
List list = (List) get(main.class, varName);
Matches m = new Matches();
if (match("list " + plural(name), s))
return structure(list);
if (match("how many " + plural(name), s))
return str(l(list));
if (webAuthed() || litlist("yes", "partially").contains(isTrustedUser())) {
if (match("add " + name + " *", s, m)) {
String id = m.fsi(0);
list.add(id);
save(varName);
return "OK, " + name + " " + id + " added. List size now: " + l(list);
}
if (match("remove " + name + " *", s, m)) {
String id = m.fsi(0);
int idx = list.indexOf(id);
if (idx < 0) return id + " is not a " + name;
list.remove(idx);
save(varName);
return "OK, " + name + " " + id + " removed. List size now: " + l(list);
}
}
return null;
}
static String structure(Object o) {
return structure(o, 0);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static String structure(Object o, int stringSizeLimit) {
if (o == null) return "null";
String name = o.getClass().getName();
StringBuilder buf = new StringBuilder();
if (o instanceof Collection) { // TODO: store the type (e.g. HashSet/TreeSet)
for (Object x : (Collection) o) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure(x, stringSizeLimit));
}
return "[" + buf + "]";
}
if (o instanceof Map) {
for (Object e : ((Map) o).entrySet()) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure(((Map.Entry) e).getKey(), stringSizeLimit));
buf.append("=");
buf.append(structure(((Map.Entry) e).getValue(), stringSizeLimit));
}
return (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(Array.get(o, i), stringSizeLimit));
}
return "array{" + buf + "}";
}
if (o instanceof String)
return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
if (o instanceof Class)
return "class(" + quote(((Class) o).getName()) + ")";
if (o instanceof Throwable)
return "exception(" + quote(((Throwable) o).getMessage()) + ")";
if (o instanceof BigInteger)
return "bigint(" + o + ")";
if (o instanceof Double)
return "d(" + quote(str(o)) + ")";
if (o instanceof Long)
return o + "L";
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax."))
return String.valueOf(o);
String shortName = o.getClass().getName().replaceAll("^main\\$", "");
int numFields = 0;
String fieldName = "";
if (shortName.equals("DynamicObject")) {
shortName = (String) get(o, "className");
Map 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(value, stringSizeLimit));
}
++numFields;
}
} else {
// regular class
// TODO: go to superclasses too
Field[] fields = o.getClass().getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
Object value;
try {
field.setAccessible(true);
value = field.get(o);
} catch (Exception e) {
value = "?";
}
fieldName = field.getName();
// put special cases here...
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure(value, stringSizeLimit));
}
++numFields;
}
}
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 s;
}
static String n(long l, String name) {
return l + " " + (l == 1 ? name : getPlural(name));
}
static String selfLink(Map params, List keepFields, String... newValues) {
Map map = new TreeMap();
for (String key : keepFields) {
String val = params.get(key);
if (val != null)
map.put(key, val);
}
for (int i = 0; i+1 < l(newValues); i += 2) {
String key = get(newValues, i);
String val = get(newValues, i+1);
if (empty(key)) continue;
if (empty(val))
map.remove(key);
else
map.put(key, val);
}
return getActualURI() + htmlQuery(map);
}
// 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 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;
}
static String sourceCodeToHTML(String src) {
return "" + htmlencode(src) + "
";
}
// works for String, StringBuffer, StringBuilder
static String sourceCodeToHTML(Object o) {
return sourceCodeToHTML(str(o));
}
// best guess for our main URL (with trailing /)
// should improve (return actual server name!)
static String mainURL() {
int port = webServerPort();
return "http://" + myBestIP() + (port == 80 ? "" : ":" + port) + "/";
}
static String htmlQuery(Map params) {
return params.isEmpty() ? "" : "?" + makePostData(params);
}
static String htmlQuery(Object... data) {
return htmlQuery(litmap(data));
}
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 String shorten(String s, int max) {
if (s == null) return "";
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
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;
}
// 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 String getPlural(String s) {
return s + "s";
}
static String str(Object o) {
return String.valueOf(o);
}
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));
}
static RuntimeException fail(String msg, Object... args) {
throw new RuntimeException(format(msg, args));
}
static String getActualURI() {
return (String) call(getMainBot(), "getActualURI");
}
static String myBestIP() {
return first(getMyIPs());
}
static String plural(String s) {
return containsIgnoreCase(litlist("sheep", "fish"), s) ? s : getPlural(s);
}
static String htmlQuote(String s) {
return "\"" + htmlencode(s) + "\"";
}
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 String programID;
static String getProgramID() {
return programID;
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
return or((String) getOpt(c, "programID"), "?");
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static void save(String varName) {
saveLocally(varName);
}
static void save(String progID, String varName) {
saveLocally(progID, varName);
}
static String isTrustedUser() {
return (String) call(getBot("#1002430"), "isTrustedUser");
}
static void readLocally(String varNames) {
readLocally(programID(), varNames);
}
// read a string variable from standard storage
// does not overwrite variable contents if there is no file
static synchronized void readLocally(String progID, String varNames) {
for (String variableName : codeTokensOnly(javaTok(varNames))) {
File textFile = new File(programDir(progID), variableName + ".text");
File structureFile = new File(programDir(progID), variableName + ".structure");
String value = loadTextFile(textFile);
if (value != null)
set(main.class, variableName, value);
else {
value = loadTextFile(structureFile);
if (value != null)
readLocally_set(main.class, variableName, unstructure(value));
}
}
}
static void readLocally_set(Class c, String varName, Object value) {
Object oldValue = get(c, varName);
if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
// Assume it's a synchroList.
value = synchroList((List) value);
}
set(c, varName, value);
}
static int webServerPort() {
Object port = getOpt(getMainBot(), "webServerPort");
return port == null ? 0 : (int) port;
}
static boolean webAuthed() {
return eq(Boolean.TRUE, callOpt(getBot("#1002590"), "currentHttpRequestAuthorized"));
}
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 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);
}
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: " + url.toExternalForm());
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//Log.info("Content-Type: " + contentType);
String charset = loadPage_guessCharset(contentType);
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
//Log.info("Chars read: " + buf.length());
buf.append((char) ch);
}
return buf.toString();
}
static String loadPage_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";
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
// automagically encode a whole map (keys+values)
static Map htmlencode(Map o) {
HashMap bla = new HashMap();
for (Object key : keys(o)) {
Object value = o.get(key);
bla.put(htmlencode(key), htmlencode(value));
}
return bla;
}
static String htmlencode(Object o) {
return htmlencode(string(o));
}
static String htmlencode(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
// 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 toks, Matches matches) {
List tokpat = parse3(pat);
return match3(tokpat,toks,matches);
}
static boolean match3(List tokpat, List 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 String makePostData(Map