import javax.imageio.*; import java.awt.image.*; import java.awt.event.*; import java.awt.*; import java.security.NoSuchAlgorithmException; import java.security.MessageDigest; import java.lang.reflect.*; import java.net.*; import java.io.*; 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.*; // The online bot LOVES to be online. public class main { // -1, 0, +1 static AtomicInteger online = new AtomicInteger(); static AtomicLong nextCheck = new AtomicLong(); static String lastProblem; public static void main(String[] args) throws Exception { makeAndroid("Online bot! " + getStatus(), new StringFunc() { public String get(String s) { try { return answer(s) ; } catch (Exception _e) { throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } } }); while (true) { check(); long seconds = online.get() > 0 ? 60 : 2; nextCheck.set(now() + seconds*1000); sleep(Math.max(nextCheck.get()-now(), 0)); } } // We should add a timeout I guess? Although, if actually offline, // it doesn't block, so it's probably ok unless the net or the // server is currently very slow. static synchronized void check() { int oldValue = online.get(); Throwable problem = checkIfHttpServerIsOnline("tinybrain.de"); int value = problem == null ? 1 : -1; if (problem == null) lastProblem = null; else if (!problem.toString().equals(lastProblem)) { print(problem); lastProblem = problem.toString(); } online.set(value); if (value != oldValue) print(getStatus()); } static synchronized String answer(String s) { if (match3("are we online?", s)) return getStatus(); if (match3("check again", s)) { print("Checking..."); check(); return getStatus(); } return null; } static String getStatus() { int i = online.get(); long checkSeconds = (nextCheck.get()-now())/1000; String checkTime = checkSeconds >= 0 ? "(Next check in " + checkSeconds + " seconds.)" : ""; if (i < 0) return "We are: OFFLINE. " + checkTime; else if (i > 0) return "We are: ONLINE. " + checkTime; else return "Online status check in progress."; } // null = online, Throwable = offline public static Throwable checkIfHttpServerIsOnline(String serverName) { try { String url = serverName.startsWith("http") ? serverName : "http://" + serverName + "/"; //HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); int responseCode = con.getResponseCode(); //print("Response code for " + url + ": " + responseCode); // If we came this far, assume server is online. return null; //return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { return e; } } static class Matches { String[] m; } static boolean match3(String pat, String s) { return match3(pat, s, null); } static boolean match3(String pat, String s, Matches matches) { 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 List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static abstract class DialogIO { abstract boolean isStillConnected(); abstract String readLineNoBlock(); abstract boolean waitForLine(); abstract void sendLine(String line); abstract boolean isLocalConnection(); abstract Socket getSocket(); } static abstract class DialogHandler { abstract void run(DialogIO io); } // Dialog classes static int makeAndroid(final String greeting, final StringFunc f) { print(greeting); int port = startDialogServerOnPortAbove(5000, makeAndroid_makeDialogHandler(greeting, f)); print("You may also type on this console."); Thread _t_0 = new Thread() { public void run() { try { String line; while ((line = readLine()) != null) { if ("bye".equals(line)) print("! bye stranger"); else makeAndroid_getAnswer(line, f); // prints answer on console too } } catch (Exception _e) { throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } } }; _t_0.start(); return port; } static DialogHandler makeAndroid_makeDialogHandler(final String greeting, final StringFunc f) { return new DialogHandler() { public void run(final DialogIO io) { String dialogID = randomID(8); io.sendLine(greeting + " / Your ID: " + dialogID); while (io.isStillConnected()) { if (io.waitForLine()) { final String line = io.readLineNoBlock(); String s = dialogID + " at " + now() + ": " + quote(line); print(s); if ("bye".equals(line)) { io.sendLine("bye stranger"); return; } String answer = makeAndroid_getAnswer(line, f); io.sendLine(answer == null ? "null" : answer); //appendToLog(logFile, s); } } }}; } static String makeAndroid_getAnswer(String line, StringFunc f) { String answer; try { answer = makeAndroid_fallback(f.get(line)); } catch (Throwable e) { e.printStackTrace(); answer = e.toString(); } print("> " + answer); return answer; } static String makeAndroid_fallback(String answer) { return answer == null ? "?" : answer; } static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static void sleep(long ms) { try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static void sleep() { try { synchronized(main.class) { main.class.wait(); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static void print() { System.out.println(); } static void print(Object o) { System.out.println(o); } static void print(long i) { System.out.println(i); } static AtomicInteger dialogServer_clients = new AtomicInteger(); static int startDialogServerOnPortAbove(int port, DialogHandler handler) { while (!startDialogServerIfPortAvailable(port, handler)) ++port; return port; } static void startDialogServer(int port, DialogHandler handler) { if (!startDialogServerIfPortAvailable(port, handler)) fail("Can't start dialog server on port " + port); } // true on server set up, false on port not available // now uses "thread" and not "daemon" (keeps VM alive!) static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) { 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; Thread _t_1 = new Thread() { public void run() { try { while (true) { try { final Socket s = _serverSocket.accept(); print("connect - clients: " + dialogServer_clients.incrementAndGet()); Thread _t_2 = new Thread() { public void run() { try { 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() { String line; boolean buff; Socket getSocket() { return s; } // local means localhost - todo: test boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } boolean isStillConnected() { return !(buff || s.isClosed()); } String readLineNoBlock() { String l = line; line = null; return l; } boolean waitForLine() { try { if (line != null) return true; //print("Readline"); line = in.readLine(); //print("Readline done: " + line); if (line == null) buff = true; return line != null; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} }; try { handler.run(io); } finally { s.close(); } } finally { print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining"); } } catch (Exception _e) { throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } } }; _t_2.start(); } catch (SocketTimeoutException e) { } } } catch (Exception _e) { throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } } }; _t_1.start(); print("Dialog server on port " + port + " started."); return true; } static BufferedReader readLine_reader; static String readLine() { try { if (readLine_reader == null) readLine_reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); String s = readLine_reader.readLine(); if (s != null) print(s); return s; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String randomID(int length) { return makeRandomID(length); } static List dropPunctuation(List tok) { tok = new ArrayList(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)) && !"*".equals(t)) { tok.set(i-1, tok.get(i-1) + tok.get(i+1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } // 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, "*"); int expand = 0; while (pat.size() < tok.size()) { ++expand; 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()]); } // javaTok extended with "..." token. static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); 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) { ++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))); 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 (s.substring(j, Math.min(j+3, l)).equals("...")) j += 3; else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static String quote(String s) { if (s == null) return "null"; return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\""; } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(String msg) { throw new RuntimeException(msg); } 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); } } interface StringFunc { String get(String s); }