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

2004
LINES

< > BotCompany Repo | #3000389 // Temp program by #1001628

JavaX source code - run with: x30.jar

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 javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
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.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
public class main {
public static void main(String[] args) throws Exception {

    for (JFrame f : allFrames()) {
      List<JList> lists = findAll(f, JList.class);
      if (l(lists) == 2) {
        print("Yes! " + f.getTitle());
        sendToLocalBot(5005,"please receive *", weakref(f));
      }
    }
  
}

static List<JFrame> allFrames() {
  return listAllFrames();
}
static <A> List<A> findAll(JFrame f, Class<A> theClass) {
  List<A> l = new ArrayList<A>();
  scanForComponents(f, theClass, l);
  return l;
}
static String weakref(Object o) {
  return (String) call(getJavaX(), "weakref", o);
}
static String sendToLocalBot(String bot, String text, Object... args) {
  text = format3(text, args);
  
  DialogIO channel = findBot(bot);
  if (channel == null)
    fail(quote(bot) + " not found");
  try {
    channel.readLine();
    print(bot + "> " + shorten(text, 80));
    channel.sendLine(text);
    String s = channel.readLine();
    print(bot + "< " + shorten(s, 80));
    return s;
  } catch (Throwable e) {
    e.printStackTrace();
    return null;
  } finally {
    channel.close();
  }
}

static String sendToLocalBot(int port, String text, Object... args) {
  text = format3(text, args);
  DialogIO channel = talkTo(port);
  try {
    channel.readLine();
    print(port + "> " + shorten(text, 80));
    channel.sendLine(text);
    String s = channel.readLine();
    print(port + "< " + shorten(s, 80));
    return s;
  } catch (Throwable e) {
    e.printStackTrace();
    return null;
  } finally {
    if (channel != null)
      channel.close();
  }
}
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 volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;

static void print() {
  print("");
}

// slightly overblown signature to return original object...
static <A> A print(A o) {
  String s = String.valueOf(o) + "\n";
  StringBuffer loc = local_log;
  StringBuffer buf = print_log;
  int loc_max = print_log_max;
  if (buf != loc && buf != null) {
    print_append(buf, s, print_log_max);
    loc_max = local_log_max;
  }
  if (loc != null) 
    print_append(loc, s, loc_max);
  System.out.print(s);
  return o;
}

static void print(long l) {
  print(String.valueOf(l));
}

static void print(char c) {
  print(String.valueOf(c));
}

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
}

  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 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); }}
  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));
  }
  

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 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 <A> void scanForComponents(Component c, Class<A> theClass, List<A> l) {
  if (theClass.isInstance(c))
    l.add((A) c);
  if (c instanceof Container)
  for (Component comp : ((Container) c).getComponents())
    scanForComponents(comp, theClass, l);
}
static List<JFrame> listAllFrames() {
  List<JFrame> l = new ArrayList<JFrame>();
  for (Frame f : Frame.getFrames())
    if (f instanceof JFrame)
      l.add((JFrame) f);
  return l;
}
  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 String quote(char c) {
    return quote("" + c);
  }

static Class __javax;

static Class getJavaX() {
  return __javax;
}
static Map<String, Integer> findBot_cache = new TreeMap<String, Integer>();
static int findBot_timeout = 5000;

static DialogIO findBot(String searchPattern) {
  // first split off sub-bot suffix
  String subBot = null;
  int i = searchPattern.indexOf('/');
  if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) {
    subBot = searchPattern.substring(i+1);
    searchPattern = searchPattern.substring(0, i);
    if (!isInteger(searchPattern))
      searchPattern = "Multi-Port at " + searchPattern + ".";
  }
  
  // assume it's a port if it's an integer
  if (isInteger(searchPattern))
    return talkToSubBot(subBot, talkTo(parseInt(searchPattern)));
    
  if (eq(searchPattern, "remote"))
    return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999));
    
  Integer port = findBot_cache.get(searchPattern);
  if (port != null) try {
    DialogIO io = talkTo("localhost", port);
    io.waitForLine(/*findBot_timeout*/); // TODO: implement
    String line = io.readLineNoBlock();
    if (indexOfIgnoreCase(line, searchPattern) == 0) {
      call(io, "pushback", line); // put hello string back in
      return talkToSubBot(subBot, io);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  
  List<ProgramScan.Program> bots = quickBotScan();
  
  // find top-level bots
  for (ProgramScan.Program p : bots) {
    if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { // strict matching - start of hello string only, but case-insensitive
      findBot_cache.put(searchPattern, p.port);
      return talkToSubBot(subBot, talkTo("localhost", p.port));
    }
  }
  
  // find sub-bots
  for (ProgramScan.Program p : bots) {
    String botName = firstPartOfHelloString(p.helloString);
    boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM.");
    boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM;
        
    if (shouldRecurse) try {
      Map<Number, String> subBots = (Map) unstructure(sendToLocalBot(p.port, "list bots"));
      for (Number vport : subBots.keySet()) {
        String name = subBots.get(vport);
        if (startsWithIgnoreCase(name, searchPattern))
          return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
      }
    } catch (Exception e) { e.printStackTrace(); }
  }
        
  return null;
}

static int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}
// 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 boolean isIdentifier(String s) {
  return isJavaIdentifier(s);
}
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));
        return isLongConstant(t) ? (Object) parseLong(t) : (Object) parseInt(t);
      }
      
      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())));
        fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
      }
      i += 2;
    }
  }
  
  return new X().parse();
}

static boolean unstructure_debug;
static DialogIO talkToSubBot(final long vport, final DialogIO io) {
  return talkToSubBot(String.valueOf(vport), io);
}

static DialogIO talkToSubBot(final String subBot, final DialogIO io) {
  if (subBot == null) return io;
  
  return new DialogIO() {
    // delegate all but sendLine
    boolean isStillConnected() { return io.isStillConnected(); }
    String readLineImpl() { return io.readLineImpl(); }
    boolean isLocalConnection() { return io.isLocalConnection(); }
    Socket getSocket() { return io.getSocket(); }
    void close() { io.close(); }

    void sendLine(String line) {
      io.sendLine(format3("please forward to bot *: *", subBot, line));
    }
  };
}
static boolean startsWithIgnoreCase(String a, String b) {
  return a != null && a.regionMatches(true, 0, b, 0, b.length());
}
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;
}
// works on lists and strings and null

static int indexOfIgnoreCase(Object a, Object b) {
  if (a == null) return -1;
  if (a instanceof String) {
     Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
     if (m.find()) return m.start(); else return -1;
  }
  if (a instanceof List) {
    for (int i = 0; i < ((List) a).size(); i++) {
      Object o = ((List) a).get(i);
      if (o != null && ((String) o).equalsIgnoreCase((String) b))
        return i;
    }
    return -1;
  }
  throw fail("Unknown type: " + a);
}
static boolean isInteger(String s) {
  return s != null && Pattern.matches("\\-?\\d+", s);
}
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);
  
  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 String firstPartOfHelloString(String s) {
  int i = s.lastIndexOf('/');
  return i < 0 ? s : rtrim(s.substring(0, i));
}
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 boolean isNonNegativeInteger(String s) {
  return s != null && Pattern.matches("\\d+", s);
}
  static String format(String pat, Object... args) {
    return format3(pat, args);
  }

  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);
  }


  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;
  }
static List<ProgramScan.Program> quickBotScan() {
  return ProgramScan.quickBotScan();
}

static List<ProgramScan.Program> quickBotScan(int[] preferredPorts) {
  return ProgramScan.quickBotScan(preferredPorts);
}

static List<ProgramScan.Program> quickBotScan(String searchPattern) {
  List<ProgramScan.Program> l = new ArrayList<ProgramScan.Program>();
  for (ProgramScan.Program p : ProgramScan.quickBotScan())
    if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
      l.add(p);
  return l;
}

// 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 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 quoteCharacter(char c) {
  if (c == '\'') return "'\\''";
  if (c == '\\') return "'\\\\'";
  return "'" + c + "'";
}

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 <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);
}
// 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());
}
static boolean isLongConstant(String s) {
  if (!s.endsWith("L")) return false;
  s = s.substring(0, l(s)-1);
  return isInteger(s);
}
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 String str(Object o) {
  return String.valueOf(o);
}
static double parseDouble(String s) {
  return Double.parseDouble(s);
}
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 Object nuObject(Class c, Object... args) { try {
 
  Constructor m = nuObject_findConstructor(c, args);
  m.setAccessible(true);
  return 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;
  }
static Object newObject(Class c, Object... args) {
  return nuObject(c, args);
}

static Object newObject(String className, Object... args) {
  return nuObject(className, args);
}

  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
  }
static Class mc() {
  return getMainClass();
}
// 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 boolean isTrue(Object o) {
  return booleanValue(o);
}
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 char unquoteCharacter(String s) {
  assertTrue(s.startsWith("'") && s.length() > 1);
  return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
public static String rtrim(String s) {
  int i = s.length();
  while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0)
    --i;
  return i < s.length() ? s.substring(0, i) : s;
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}
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 call(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;
}
// 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 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); }}
static boolean booleanValue(Object o) {
  return eq(true, o);
}
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 String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static <A> ArrayList<A> litlist(A... a) {
  return new ArrayList<A>(Arrays.asList(a));
}
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 void assertTrue(Object o) {
  assertEquals(true, o);
}
  
static boolean assertTrue(String msg, boolean b) {
  if (!b)
    fail(msg);
  return b;
}

static boolean assertTrue(boolean b) {
  if (!b)
    fail("oops");
  return b;
}
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 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 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 Object getBot(String botID) {
  return callOpt(getMainBot(), "getBot", botID);
}


static String classNameToVM(String name) {
  return name.replace(".", "$");
}
static void assertEquals(Object x, Object y) {
  assertEquals(null, x, y);
}

static void assertEquals(String msg, Object x, Object y) {
  if (!(x == null ? y == null : x.equals(y)))
    fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y));
}
  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 Object mainBot;

static Object getMainBot() {
  return mainBot;
}
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 ProgramScan {
  static int threads = isWindows() ? 500 : 10;
  static int timeout = 5000; // hmm...
  static String ip = "127.0.0.1";
  static int quickScanFrom = 10000, quickScanTo = 10999;
  static int maxNumberOfBotPorts = 100;
  static boolean verbose;
  
  static class Program {
    int port;
    String helloString;
    
    Program(int port, String helloString) {
  this.helloString = helloString;
  this.port = port;}
  }
  
  static List<Program> scan() { try {
 
    return scan(1, 65535);
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
  
  static List<Program> scan(int fromPort, int toPort) {
    return scan(fromPort, toPort, new int[0]);
  }
  
  static List<Program> scan(int fromPort, int toPort, int[] preferredPorts) { try {
 
    Set<Integer> preferredPortsSet = new HashSet<Integer>(asList(preferredPorts));
    String name = toPort < 10000 ? "bot" : "program";
    final ExecutorService es = Executors.newFixedThreadPool(threads);
    if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads.");
    startTiming();
    List<Future<Program>> futures = new ArrayList<Future<Program>>();
    for (int port : preferredPorts)
      futures.add(checkPort(es, ip, port, timeout));
    for (int port = fromPort; port <= toPort; port++)
      if (!preferredPortsSet.contains(port))
        futures.add(checkPort(es, ip, port, timeout));
    es.shutdown();
    List<Program> programs = new ArrayList<Program>();
    for (final Future<Program> f : futures) {
      Program p = f.get();
      if (p != null)
        programs.add(p);
    }
    stopTiming();
    if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip);
    return programs;
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

  static Future<Program> checkPort(final ExecutorService es, final String ip, final int port, final int timeout) {
    return es.submit(new Callable<Program>() {
        @Override public Program call() {
          try {
            Socket socket = new Socket();
            socket.setSoTimeout(timeout);
            socket.connect(new InetSocketAddress(ip, port), timeout);
            if (verbose) print("Connected to " + ip + ":" + port);
            BufferedReader in = new BufferedReader(
              new InputStreamReader(socket.getInputStream(), "UTF-8"));
            String hello = or(in.readLine(), "?");
            socket.close();
            return new Program(port, hello);
          } catch (Exception ex) {
            return null;
          }
        }
     });
  }
  
  static List<Program> quickScan() {
    return scan(quickScanFrom, quickScanTo);
  }
  
  static List<Program> quickBotScan() {
    return quickBotScan(new int[0]);
  }
  
  static List<Program> quickBotScan(int[] preferredPorts) {
    return scan(4990, 5000+maxNumberOfBotPorts-1, preferredPorts);
  }
}

  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)
        fail();
      line = l;
      helloRead = false;
    }
  }
  
  static abstract class DialogHandler {
    abstract void run(DialogIO io);
  }

static long startTiming_startTime;
static void startTiming() {
  startTiming_startTime = now();
}

static void stopTiming() {
  long end = now();
  print("Time: " + (end-startTiming_startTime) + " ms");
}
public static boolean isWindows() {
  return System.getProperty("os.name").contains("Windows");
}
static <A> A or(A a, A b) {
  return a != null ? a : b;
}
static String firstToUpper(String s) {
  if (s.length() == 0) return s;
  return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static BufferedReader readLine_reader;

static String readLine() {
  return (String) call(getJavaX(), "readLine");
}
static <A> ArrayList<A> asList(A[] a) {
  return new ArrayList<A>(Arrays.asList(a));
}

static ArrayList<Integer> asList(int[] a) {
  ArrayList<Integer> l = new ArrayList();
  for (int i : a) l.add(i);
  return l;
}

static <A> ArrayList<A> asList(Collection<A> s) {
  return s == null ? new ArrayList() 
    : s instanceof ArrayList ? (ArrayList) s : new ArrayList(s);
}

static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

}

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #3000389
Snippet name: Temp program by #1001628
Eternal ID of this version: #3000389/1
Text MD5: 56a4d6e854f19b18e87a1840ad817b6b
Author: someone
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-07-17 23:46:08
Source code size: 57407 bytes / 2004 lines
Pitched / IR pitched: No / No
Views / Downloads: 530 / 498
Referenced in: [show references]