c, final Object... args) {
return swingConstruct(c, args);
}
static public void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.addActionListener(actionListener(action));";
}
});
}
}
static public void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
b.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addActionListener(actionListener(action));";
}
});
}
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean containsNewLines(String s) {
return containsNewLine(s);
}
static public String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode(text), "\n", " ") + "
";
}
static public long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static public File localSnippetFile(long snippetID) {
return localSnippetsDir(snippetID + ".text");
}
static public File localSnippetFile(String snippetID) {
return localSnippetFile(parseSnippetID(snippetID));
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public String getFileInfoField(File f, String field) {
return getOneLineFileInfoField(f, field);
}
static public File dropExtension(File f) {
return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
}
static public String dropExtension(String s) {
return takeFirst(s, smartLastIndexOf(s, '.'));
}
static public File javaxCachesDir_dir;
static public File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static public File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
static public IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static public boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static public String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
static public String muricaCredentialsQuery() {
return htmlQuery(muricaCredentials());
}
static public boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
static public String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
static public boolean saveTextFileIfChanged(File f, String contents) {
return saveTextFileIfDifferent(f, contents);
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static public void assertFalse(Object o) {
if (!(eq(o, false)))
throw fail(str(o));
}
static public boolean assertFalse(boolean b) {
if (b)
throw fail("oops");
return b;
}
static public boolean assertFalse(String msg, boolean b) {
if (b)
throw fail(msg);
return b;
}
static public boolean _inCore() {
return false;
}
static public List hotwire_copyOver_after = synchroList();
static public void hotwire_copyOver(Class c) {
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot", getMainBot());
setOpt(c, "creator_class", new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
static public LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public JTextField jTextField() {
return jTextField("");
}
static public JTextField jTextField(final String text) {
return swing(new F0() {
public JTextField get() {
try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu...";
}
});
}
static public JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static public JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null)
return tf;
tf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
tf.selectAll();
callF(action);
} catch (Throwable __e) {
messageBox(__e);
}
}
});
return tf;
}
static public JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null)
return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static public JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static public JComboBox onEnter(final JComboBox cb, final Object action) {
{
swing(new Runnable() {
public void run() {
try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() {
public void run() {
try {
cb.hidePopup();
callF(action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.hidePopup(); callF(action);";
}
}));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g...";
}
});
}
return cb;
}
static public JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
static public JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static public ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __0 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__0);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public boolean containsNewLine(String s) {
return contains(s, '\n');
}
static public List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public String htmlencode(Object o) {
return htmlencode(str(o));
}
static public 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 == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else
out.append(c);
}
return out.toString();
}
static public File localSnippetsDir() {
return javaxDataDir("Personal Programs");
}
static public File localSnippetsDir(String sub) {
return newFile(localSnippetsDir(), sub);
}
static public String getOneLineFileInfoField(File f, String field) {
File infoFile = associatedInfosFile(f);
List lines = lines(loadTextFile(infoFile));
return firstStartingWithIC_drop(lines, field + ": ");
}
static public File fileInSameDir(File f, String newName) {
return newFile(parentFile(f), newName);
}
static public List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static public List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static public String takeFirst(int n, String s) {
return substring(s, 0, n);
}
static public String takeFirst(String s, int n) {
return substring(s, 0, n);
}
static public List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public int smartLastIndexOf(String s, char c) {
if (s == null)
return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
static public A proxy(Class intrface, final Object target) {
if (target == null)
return null;
if (isInstance(intrface, target))
return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return call(target, method.getName(), unnull(args));
}
});
}
static public A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static public String htmlQuery(Map params) {
return empty(params) ? "" : "?" + makePostData(params);
}
static public String htmlQuery(Object... data) {
return empty(data) ? "" : "?" + makePostData(data);
}
static public Object[] muricaCredentials() {
String pass = muricaPassword();
return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
}
static public boolean saveTextFileIfDifferent(File f, String contents) {
if (eq(loadTextFile(f), contents))
return false;
{
saveTextFile(f, contents);
return true;
}
}
static public String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
static public String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static public String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
static public void setOptIfNotNull(Object o, String field, Object value) {
if (value != null)
setOpt(o, field, value);
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(ref.get().getText());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(ref.get().getText())";
}
});
componentPopupMenuItem(tf, "Paste", new Runnable() {
public void run() {
try {
ref.get().paste();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ref.get().paste()";
}
});
return tf;
}
static public A jenableUndoRedo(final A textcomp) {
{
swing(new Runnable() {
public void run() {
try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {
public void run() {
try {
if (undo.canUndo())
undo.undo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canUndo()) undo.undo()";
}
}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {
public void run() {
try {
if (undo.canRedo())
undo.redo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canRedo()) undo.redo()";
}
}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)...";
}
});
}
return textcomp;
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() {
public void run() {
try {
pcallF(action, getSelectedItem(list));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(action, getSelectedItem(list))";
}
};
}
static public AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static public ThreadLocal> holdInstance_l = new ThreadLocal();
static public AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public File associatedInfosFile(File f) {
return replaceExtension(f, ".infos");
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String firstStartingWithIC_drop(Collection l, final String prefix) {
for (String s : unnull(l)) if (swic(s, prefix))
return substring(s, l(prefix));
return null;
}
static public String firstStartingWithIC_drop(String prefix, Collection l) {
return firstStartingWithIC_drop(l, prefix);
}
static public File parentFile(File f) {
return dirOfFile(f);
}
static public List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static public List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
static volatile public boolean muricaPassword_pretendNotAuthed = false;
static public String muricaPassword() {
if (muricaPassword_pretendNotAuthed)
return null;
return trim(loadTextFile(muricaPasswordFile()));
}
static public A componentPopupMenuItem(A c, final String name, final Object action) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action);";
}
});
return c;
}
static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, menuItem);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, menuItem);";
}
});
}
static public String copyTextToClipboard(Object _text) {
String text = str(_text);
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
static public Set vm_generalWeakSet(Object name) {
synchronized (get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static public void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
static public A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
static public File replaceExtension(File f, String extOld, String extNew) {
return newFile(replaceExtension(f2s(f), extOld, extNew));
}
static public File replaceExtension(File f, String extNew) {
return replaceExtension(f, fileExtension(f), extNew);
}
static public String replaceExtension(String s, String extOld, String extNew) {
s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
return s + addPrefixOptIfNempty(".", extNew);
}
static public String replaceExtension(String name, String extNew) {
return replaceExtension(name, fileExtension(name), extNew);
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public File dirOfFile(File f) {
return f == null ? null : f.getParentFile();
}
static public File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
static public void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public Set newWeakHashSet() {
return synchroWeakHashSet();
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public String fileExtension(File f) {
if (f == null)
return null;
return fileExtension(f.getName());
}
static public String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
static public String dropSuffixIC(String suffix, String s) {
return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public String addPrefixOptIfNempty(String prefix, String s) {
return addPrefixIfNotEmpty2(prefix, s);
}
static public CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
static public boolean jmenuItem_newThreads = false;
static public JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static public JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() {
public JMenuItem get() {
try {
Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
JMenuItem mi = new JMenuItem(p.a);
if (startsWith(text, "[disabled] "))
disableMenuItem(mi);
if (p.b != 0)
mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
return mi;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM...";
}
});
}
static public MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static public B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static public A liftLast(List l) {
if (empty(l))
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
static public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static public String addPrefixIfNotEmpty2(String prefix, String s) {
return empty(s) ? "" : addPrefix(prefix, s);
}
static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
static public CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static public CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
static public BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static public JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static public Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1)))
return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1));
return pair(s, 0);
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public JMenuItem disableMenuItem(final JMenuItem mi) {
if (mi != null) {
swing(new Runnable() {
public void run() {
try {
mi.setEnabled(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mi.setEnabled(false);";
}
});
}
return mi;
}
static public ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __0 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __0 = holdInstance(instanceToHold); try {\r\n callF(runnable...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static public List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static public void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
static public void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
static public String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
static public BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
static public String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
static public A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static public FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static public FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
static public int gzInputStream_defaultBufferSize = 65536;
static public GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static public List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
static public interface IResourceLoader {
public String loadSnippet(String snippetID);
public String getTranspiled(String snippetID);
public int getSnippetType(String snippetID);
public String getSnippetTitle(String snippetID);
public File loadLibrary(String snippetID);
public File pathToJavaXJar();
public File getSnippetJar(String snippetID, String transpiledSrc);
}
static abstract public class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
static public class Pair implements Comparable> {
public A a;
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null)
return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0)
return i;
return ((Comparable) b).compareTo(p.b);
}
}
static public File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static public int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static public File loadBinarySnippet(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public File loadImageAsFile(String snippetIDOrURL) {
try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL))
throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0)
return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
static public File loadDataSnippetToFile(String snippetID) {
try {
snippetID = fsI(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean loadBufferedImage_useImageCache = true;
static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
try {
ping();
if (snippetIDOrURLOrFile == null)
return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedImage loadBufferedImage(File file) {
try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static public File imageSnippetCacheFile(String snippetID) {
File dir = imageSnippetsCacheDir();
if (!loadBufferedImage_useImageCache)
return null;
return new File(dir, parseSnippetID(snippetID) + ".png");
}
static public String snippetImageURL_noHttps(String snippetID) {
return snippetImageURL_noHttps(snippetID, "png");
}
static public String snippetImageURL_noHttps(String snippetID, String contentType) {
return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
}
static public ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
static public byte[] loadBinaryPage(String url) {
try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] loadBinaryPage(URLConnection con) {
try {
Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
setHeaders(con);
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] loadBinaryPage_noHeaders(URLConnection con) {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] saveBinaryFile(String fileName, byte[] contents) {
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
vmBus_send("wroteFile", file);
return contents;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] saveBinaryFile(File fileName, byte[] contents) {
return saveBinaryFile(fileName.getPath(), contents);
}
static public File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static public String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1100000 && id < 1200000)
return imageServerURL() + id;
if (id >= 1200000 && id < 1300000) {
String pw = muricaPassword();
if (empty(pw))
throw fail("Please set 'murica password by running #1008829");
return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw;
}
return fileServerURL() + "/" + id;
}
static public A addAndReturn(Collection c, A a) {
if (c != null)
c.add(a);
return a;
}
static public void loadBinaryPageToFile(String url, File file) {
try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void loadBinaryPageToFile(URLConnection con, File file) {
try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
try {
InputStream inputStream = con.getInputStream();
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
copyStreamWithPrints(inputStream, buf, pat);
inputStream.close();
buf.close();
file.delete();
renameFile_assertTrue(ftemp, file);
} finally {
if (buf != null)
buf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public URLConnection openConnection(String url) {
try {
return openConnection(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public URLConnection openConnection(URL url) {
try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List allToString(Iterable c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public BufferedImage imageIO_readURL(String url) {
try {
if (startsWith(url, "https:"))
disableCertificateValidation();
return ImageIO.read(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
static public boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
static public File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
static public String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
static public String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
static public String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
static public String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static public String snippetImageURL(String snippetID, String contentType) {
if (isURL(snippetID))
return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (isImageServerSnippet(id))
url = imageServerLink(id);
else
url = "https://www.botcompany.de:8443/img/" + id;
return url;
}
static public int loadPage_defaultTimeout = 60000;
static public ThreadLocal loadPage_charset = new ThreadLocal();
static public boolean loadPage_allowGzip = true, loadPage_debug;
static public boolean loadPage_anonymous = false;
static public int loadPage_verboseness = 100000;
static public int loadPage_retries = 1;
static public ThreadLocal loadPage_silent = new ThreadLocal();
static volatile public int loadPage_forcedTimeout;
static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static public ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (url.getProtocol().equals("https"))
disableCertificateValidation();
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static public String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static public String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
Long limit = optPar(loadPage_sizeLimit);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
}
static public String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
static public URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static public A println(A a) {
return print(a);
}
static public String fileServerURL() {
return "https://botcompany.de/files";
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
try {
byte[] buf = new byte[65536];
int total = 0;
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
if ((total + n) / 100000 > total / 100000)
print(pat.replace("{*}", str(roundDownTo(total, 100000))));
total += n;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void renameFile_assertTrue(File a, File b) {
try {
if (!a.exists())
throw fail("Source file not found: " + f2s(a));
if (b.exists())
throw fail("Target file exists: " + f2s(b));
mkdirsForFile(b);
if (!a.renameTo(b))
throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static volatile public boolean disableCertificateValidation_attempted = false;
static public void disableCertificateValidation() {
try {
if (disableCertificateValidation_attempted)
return;
disableCertificateValidation_attempted = true;
try {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static public String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static public boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static final public boolean loadPageThroughProxy_enabled = false;
static public String loadPageThroughProxy(String url) {
return null;
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public A printWithTime(A a) {
return printWithTime("", a);
}
static public A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static public Map vm_generalSubMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
UnknownHostException lastException = null;
for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
try {
if (con instanceof HttpURLConnection)
if (((HttpURLConnection) con).getResponseCode() == 500)
throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
return con.getInputStream();
} catch (UnknownHostException e) {
lastException = e;
print("Retrying because of: " + e);
continue;
}
}
throw lastException;
}
static public String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static public String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static public Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
if (con.getConnectTimeout() == 0) {
con.setConnectTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout)
print("Warning: URL connect timeout not set by JDK.");
}
if (con.getReadTimeout() == 0) {
con.setReadTimeout(toInt(timeout));
if (con.getReadTimeout() != timeout)
print("Warning: URL read timeout not set by JDK.");
}
return con;
}
static public int roundDownTo(int x, int n) {
return x / n * n;
}
static public long roundDownTo(long x, long n) {
return x / n * n;
}
static public boolean possibleMD5(String s) {
return isMD5(s);
}
static volatile public Object isAllowed_function;
static volatile public boolean isAllowed_all = true;
static public boolean isAllowed(String askingMethod, Object... args) {
Object f = vm_generalMap_get("isAllowed_function");
if (f != null && !isTrue(callF(f, askingMethod, args)))
return false;
return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
static public long round(double d) {
return Math.round(d);
}
static public String hmsWithColons() {
return hmsWithColons(now());
}
static public String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public String joinNemptiesWithColonSpace(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColonSpace(Collection strings) {
return joinNempties(": ", strings);
}
static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
try {
if (conn instanceof HttpURLConnection)
return stream2string(((HttpURLConnection) conn).getErrorStream());
return null;
} catch (Throwable __e) {
return null;
}
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
static public Map compileRegexp_cache = syncMRUCache(10);
static public java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null) {
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
}
return p;
}
static public boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static public String joinNempties(String sep, String... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Collection strings) {
return joinStrings(sep, strings);
}
static public String stream2string(InputStream in) {
return utf8streamToString(in);
}
static public Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
static public boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
} else
return false;
}
return true;
}
static public String joinStrings(String sep, String... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static public String joinStrings(String sep, Collection strings) {
StringBuilder buf = new StringBuilder();
for (String s : unnull(strings)) if (nempty(s)) {
if (nempty(buf))
buf.append(sep);
buf.append(s);
}
return str(buf);
}
static public String utf8streamToString(InputStream in) {
return readerToString(utf8bufferedReader(in));
}
static public String readerToString(Reader r) {
try {
try {
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
}
return buf.toString();
} finally {
r.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public class MRUCache extends LinkedHashMap {
public int maxSize = 10;
public MRUCache() {
}
public MRUCache(int maxSize) {
this.maxSize = maxSize;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
public Object _serialize() {
return ll(maxSize, cloneLinkedHashMap(this));
}
static public MRUCache _deserialize(List l) {
MRUCache m = new MRUCache();
m.maxSize = (int) first(l);
m.putAll((LinkedHashMap) second(l));
return m;
}
}
static public LinkedHashMap cloneLinkedHashMap(Map map) {
return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public char second(String s) {
return charAt(s, 1);
}
static public char charAt(String s, int i) {
return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}
}