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 {
public static void main(String[] args) throws Exception {
htmlBot("HTML Time Bot.");
}
static String html() {
return "
Hello!Hello! :) The time is: " + now();
}
static void htmlBot(String name) {
Android3 a = new Android3(name);
a.responder = new Responder() {
String answer(String s, List history) {
if (match3("get fresh html", s))
return quote(unnull((String) callOpt(getMainClass(), "html")));
return null;
}
};
makeAndroid(a);
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
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 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 Class getMainClass() { try {
return Class.forName("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
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
}
// class Matches
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;
List tokpat = parse3(pat), toks = parse3(s);
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 int makeAndroid(String greeting) {
return makeAndroid3(greeting).port;
}
static void makeAndroid(Android3 a) {
makeAndroid3(a);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Class include(String progID) {
Class c = hotwire(progID);
setOpt(c, "programID", getProgramID());
return c;
}
static int l(Object[] array) {
return array == null ? 0 : array.length;
}
static int l(List list) {
return list == null ? 0 : list.size();
}
static int l(String s) {
return s == null ? 0 : s.length();
}
static abstract class DialogIO {
abstract boolean isStillConnected();
abstract String readLineNoBlock();
abstract boolean waitForLine();
abstract void sendLine(String line);
abstract boolean isLocalConnection();
abstract Socket getSocket();
abstract void close();
int getPort() { return getSocket().getPort(); }
boolean helloRead;
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;
}
}
static abstract class DialogHandler {
abstract void run(DialogIO io);
} // Dialog classes
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;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server == null) return;
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
}
static abstract class Responder {
abstract String answer(String s, List 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 history) {
return callStaticAnswerMethod(s, history);
}
};
if (a.useMultiPort) {
a.vport = addToMultiPort(a.greeting, a.responder);
if (a.vport == 1)
makeAndroid3_handleConsole(a);
return a;
}
print(a.greeting);
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 history = new ArrayList();
String line;
while ((line = readLine()) != null) {
if ("bye".equals(line)) {
print("> bye stranger");
history = new ArrayList();
} 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 history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(s);
if ("bye".equals(line)) {
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 history, Android3 a) {
String answer;
try {
answer = makeAndroid3_fallback(line, history, a.responder.answer(line, history));
} catch (Throwable e) {
e = getInnerException(e);
e.printStackTrace();
answer = e.toString();
}
if (!a.incomingSilent)
print("> " + shorten(answer, 500));
return answer;
}
static String makeAndroid3_fallback(String s, List 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 List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
// 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;
return type.isInstance(arg);
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List pat, List tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList(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 pat, List tok) {
List result = new ArrayList();
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 ("*".equals(p))
result.add(t);
else if (!p.equalsIgnoreCase(t))
return null;
}
return result.toArray(new String[result.size()]);
}
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 answer;
}
static String callStaticAnswerMethod(String s, List history) {
String answer = (String) callOpt(getMainClass(), "answer", s, history);
if (answer == null)
answer = (String) callOpt(getMainClass(), "answer", s);
return answer;
}
static String getInjectionID() {
return (String) call(getJavaX(), "getInjectionID", getMainClass());
}
static Object addToMultiPort_responder;
static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List 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.isEmpty())
fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
return (Long) call(port, "addResponder", botName, new Object() {
public String answer(String s, List history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
});
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static List