diff --git a/.travis.yml b/.travis.yml
index 4b0e919..ee17f98 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,9 @@
language: java
+dist: trusty
+
jdk:
- - oraclejdk7
+ - openjdk7
- oraclejdk8
before_install:
@@ -32,7 +34,7 @@ env:
- secure: UG+b1tEgc8xv9x4r//2OAIK1RrYv6n209KTTFMMwcnAa7DI8HaP8nljRa5/VhDhuKHdlVrYH/tI90v7UVBs0GDVNwK5V17Io0fMm3FUGZekSthTCqqno5wAGa9r6a6mMLtSaSmIFeIKi0+0d2ZwplRuhj/dtEYjjBBj+kK8g4nE=
- secure: St/fecUDInFBCRriYqgp2F8PU9/SooorgxD9Mrs+b0EsC7AbtSsQXvdIv2Lp6xzdQ0VSXPcLIhULPOYrmBKnGQ/NjXTIZXxnroyQxxnI6xyEWIZwiHRY/bKRJDRbQTxD9NL32szKiDSwnw7pu6llF4D64UqQvziq4Gm6VohU75M=
- secure: bD15GVZWowiknbfLavh8CxSh0GsnF5kT4kZ6ggCuUDGyj0mzqf7dNRnchQIKkCG0WRYyTrFN4pEiygeywWsipEeAVv9Xhx3cuUZmzeQaR5KCWabSwJ8gK6jZd1YhcWmM9vrdPHobZr65MP0y/8mu/Fovgky9dY7KDf4G3SebNrM=
- - PARABOT_VERSION=2.6.6.6
+ - PARABOT_VERSION=2.6.8
cache:
directories:
@@ -56,7 +58,7 @@ deploy:
branch:
- master
- development
- jdk: 'oraclejdk7'
+ jdk: 'openjdk7'
- provider: script
script: "cp ./.travis/.travis.settings.xml $HOME/.m2/settings.xml && mvn package javadoc:javadoc deploy site:deploy"
@@ -65,4 +67,4 @@ deploy:
repo: Parabot/Parabot
branch:
- master
- jdk: 'oraclejdk7'
\ No newline at end of file
+ jdk: 'openjdk7'
\ No newline at end of file
diff --git a/README.md b/README.md
index 41f5398..8f46946 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
# Parabot
-Parabot V2.6.3.
+Parabot V2.6.8.
#### Links
diff --git a/pom.xml b/pom.xml
index fe8ef79..7a4d27a 100755
--- a/pom.xml
+++ b/pom.xml
@@ -6,7 +6,7 @@
org.parabot
client
- 2.6.6.6
+ 2.6.8
jar
diff --git a/src/main/java/org/parabot/core/Configuration.java b/src/main/java/org/parabot/core/Configuration.java
index 39e9b03..6217c67 100644
--- a/src/main/java/org/parabot/core/Configuration.java
+++ b/src/main/java/org/parabot/core/Configuration.java
@@ -8,20 +8,20 @@ import org.parabot.environment.api.utils.Version;
* @author Everel
*/
public class Configuration extends org.parabot.api.Configuration {
- public static final String LOGIN_SERVER = "http://bdn.parabot.org/api/v2/users/login";
- public static final String GET_SCRIPTS = "http://bdn.parabot.org/api/get.php?action=scripts_scripts&server=";
- public static final String GET_SCRIPT = "http://bdn.parabot.org/api/get.php?action=scripts_script&id=";
- public static final String GET_SERVER_PROVIDERS = "http://bdn.parabot.org/api/get.php?action=server_providers";
- public static final String GET_SERVER_PROVIDER = "http://v3.bdn.parabot.org/api/bot/download/provider?nightly=%s&server=%s";
+ public static final String LOGIN_SERVER = "http://bdn.parabot.org/api/v2/users/login";
+ public static final String GET_SCRIPTS = "http://bdn.parabot.org/api/get.php?action=scripts_scripts&server=";
+ public static final String GET_SCRIPT = "http://bdn.parabot.org/api/get.php?action=scripts_script&id=";
+ public static final String GET_SERVER_PROVIDERS = "http://bdn.parabot.org/api/get.php?action=server_providers";
+ public static final String GET_SERVER_PROVIDER = "http://v3.bdn.parabot.org/api/bot/download/provider?nightly=%s&server=%s";
public static final String GET_SERVER_PROVIDER_INFO = "http://bdn.parabot.org/api/get.php?action=server_information&name=";
- public static final String GET_SERVER_SETTINGS = "http://bdn.parabot.org/api/get.php?action=get_settings";
- public static final String GET_BOT_VERSION = "http://bdn.parabot.org/api/v2/bot/version";
- public static final String API_DOWNLOAD_BOT = "http://v3.bdn.parabot.org/api/bot/download/client";
- public static final String DOWNLOAD_BOT = "http://bdn.parabot.org/versions/";
- public static final String REGISTRATION_PAGE = "https://www.parabot.org/community/register/";
- public static final String GET_RANDOMS = "http://v3.bdn.parabot.org/api/bot/download/randoms";
- public static final String DATA_API = "http://bdn.parabot.org/api/v2/data/";
- public static final String ITEM_API = DATA_API + "items/";
+ public static final String GET_SERVER_SETTINGS = "http://bdn.parabot.org/api/get.php?action=get_settings";
+ public static final String GET_BOT_VERSION = "http://bdn.parabot.org/api/v2/bot/version";
+ public static final String API_DOWNLOAD_BOT = "http://v3.bdn.parabot.org/api/bot/download/client";
+ public static final String DOWNLOAD_BOT = "http://bdn.parabot.org/versions/";
+ public static final String REGISTRATION_PAGE = "https://www.parabot.org/community/register/";
+ public static final String GET_RANDOMS = "http://v3.bdn.parabot.org/api/bot/download/randoms";
+ public static final String DATA_API = "http://bdn.parabot.org/api/v2/data/";
+ public static final String ITEM_API = DATA_API + "items/";
public static final Version BOT_VERSION = ProjectProperties.getProjectVersion();
}
diff --git a/src/main/java/org/parabot/core/Context.java b/src/main/java/org/parabot/core/Context.java
index 3aa335d..943d051 100644
--- a/src/main/java/org/parabot/core/Context.java
+++ b/src/main/java/org/parabot/core/Context.java
@@ -33,32 +33,32 @@ import java.util.TimerTask;
*/
public class Context {
public static final HashMap threadGroups = new HashMap();
- private static ArrayList paintables = new ArrayList();
-
- private static Context instance;
- private static String username;
+ private static ArrayList paintables = new ArrayList();
- private ASMClassLoader classLoader;
- private ClassPath classPath;
- private ServerProvider serverProvider;
- private Applet gameApplet;
- private HookParser hookParser;
- private Script runningScript;
- private RandomHandler randomHandler;
- private Object clientInstance;
- private PaintDebugger paintDebugger;
- private Mouse mouse;
- private Keyboard keyboard;
- private PBKeyListener pbKeyListener;
+ private static Context instance;
+ private static String username;
+
+ private ASMClassLoader classLoader;
+ private ClassPath classPath;
+ private ServerProvider serverProvider;
+ private Applet gameApplet;
+ private HookParser hookParser;
+ private Script runningScript;
+ private RandomHandler randomHandler;
+ private Object clientInstance;
+ private PaintDebugger paintDebugger;
+ private Mouse mouse;
+ private Keyboard keyboard;
+ private PBKeyListener pbKeyListener;
private ServerProviderInfo providerInfo;
- private JSONParser jsonParser;
+ private JSONParser jsonParser;
private PrintStream defaultOut;
private PrintStream defaultErr = System.err;
private Context(final ServerProvider serverProvider) {
threadGroups.put(Thread.currentThread().getThreadGroup(), this);
-
+
System.setProperty("sun.java.command", "");
this.serverProvider = serverProvider;
this.paintDebugger = new PaintDebugger();
@@ -75,9 +75,17 @@ public class Context {
public static Context getInstance(ServerProvider serverProvider) {
return instance == null ? instance = new Context(serverProvider) : instance;
}
-
+
public static Context getInstance() {
- return getInstance(null);
+ return getInstance(null);
+ }
+
+ public static String getUsername() {
+ return username;
+ }
+
+ public static void setUsername(String username) {
+ Context.username = username;
}
/**
@@ -88,12 +96,12 @@ public class Context {
}
/**
- * Sets the hook parser
+ * Gets the mouse
*
- * @param hookParser
+ * @return mouse
*/
- public void setHookParser(final HookParser hookParser) {
- this.hookParser = hookParser;
+ public Mouse getMouse() {
+ return mouse;
}
/**
@@ -106,15 +114,14 @@ public class Context {
}
/**
- * Gets the mouse
+ * Gets the keyboard
*
- * @return mouse
+ * @return keyboard
*/
- public Mouse getMouse() {
- return mouse;
+ public Keyboard getKeyboard() {
+ return keyboard;
}
-
/**
* Sets the keyboard
*
@@ -124,15 +131,6 @@ public class Context {
this.keyboard = keyboard;
}
- /**
- * Gets the keyboard
- *
- * @return keyboard
- */
- public Keyboard getKeyboard() {
- return keyboard;
- }
-
/**
* ClassPath
*
@@ -160,51 +158,28 @@ public class Context {
return gameApplet;
}
- /**
- * Loads the game
- */
- public void load() {
- Core.verbose(TranslationHelper.translate("PARSING_SERVER_JAR"));
- serverProvider.init();
- serverProvider.parseJar();
- Core.verbose(TranslationHelper.translate("DONE"));
- Core.verbose(TranslationHelper.translate("INJECTING_HOOKS"));
- serverProvider.injectHooks();
- Core.verbose(TranslationHelper.translate("DONE"));
- Core.verbose(TranslationHelper.translate("FETCHING_GAME_APPLET"));
- if(Core.shouldDump()) {
- Core.verbose(TranslationHelper.translate("DUMPING_INJECTED_CLIENT"));
- classPath.dump(new File(Directories.getWorkspace(), "dump.jar"));
- Core.verbose(TranslationHelper.translate("DONE"));
- }
- Applet applet = serverProvider.fetchApplet();
- // if applet is null the server provider will call setApplet itself
- if(applet != null) {
- setApplet(applet);
- }
- }
-
/**
* Sets the bot target applet
+ *
* @param applet
*/
public void setApplet(final Applet applet) {
- gameApplet = applet;
-
- if (getClient() == null) {
+ gameApplet = applet;
+
+ if (getClient() == null) {
setClientInstance(gameApplet);
}
Core.verbose(TranslationHelper.translate("APPLET_FETCHED"));
-
- final GamePanel panel = GamePanel.getInstance();
+
+ final GamePanel panel = GamePanel.getInstance();
final Dimension appletSize = serverProvider.getGameDimensions();
-
+
panel.setPreferredSize(appletSize);
serverProvider.addMenuItems(BotUI.getInstance().getJMenuBar());
BotUI.getInstance().pack();
BotUI.getInstance().validate();
-
+
panel.removeComponents();
gameApplet.setSize(appletSize);
panel.add(gameApplet);
@@ -220,7 +195,7 @@ public class Context {
gameApplet.setBounds(0, 0, appletSize.width, appletSize.height);
}
}, 1000);
-
+
Core.verbose(TranslationHelper.translate("INIT_MOUSE"));
serverProvider.initMouse();
Core.verbose(TranslationHelper.translate("DONE"));
@@ -231,12 +206,36 @@ public class Context {
Core.verbose(TranslationHelper.translate("INIT_KEY_LISTENER"));
this.pbKeyListener = new PBKeyListener();
applet.addKeyListener(this.pbKeyListener);
-
+
BotDialog.getInstance().validate();
System.setOut(this.defaultOut);
System.setErr(this.defaultErr);
}
+ /**
+ * Loads the game
+ */
+ public void load() {
+ Core.verbose(TranslationHelper.translate("PARSING_SERVER_JAR"));
+ serverProvider.init();
+ serverProvider.parseJar();
+ Core.verbose(TranslationHelper.translate("DONE"));
+ Core.verbose(TranslationHelper.translate("INJECTING_HOOKS"));
+ serverProvider.injectHooks();
+ Core.verbose(TranslationHelper.translate("DONE"));
+ Core.verbose(TranslationHelper.translate("FETCHING_GAME_APPLET"));
+ if (Core.shouldDump()) {
+ Core.verbose(TranslationHelper.translate("DUMPING_INJECTED_CLIENT"));
+ classPath.dump(new File(Directories.getWorkspace(), "dump.jar"));
+ Core.verbose(TranslationHelper.translate("DONE"));
+ }
+ Applet applet = serverProvider.fetchApplet();
+ // if applet is null the server provider will call setApplet itself
+ if (applet != null) {
+ setApplet(applet);
+ }
+ }
+
/**
* Gets the server prodiver belonging to this context
*
@@ -245,24 +244,24 @@ public class Context {
public ServerProvider getServerProvider() {
return serverProvider;
}
-
+
/**
- *
* Sets provider info of this context
- *
+ *
* @param providerInfo
*/
public void setProviderInfo(ServerProviderInfo providerInfo) {
- this.providerInfo = providerInfo;
+ this.providerInfo = providerInfo;
}
-
+
/**
* Gets ServerProvider info
* Can be null if this is not a public server provider
+ *
* @return info about this provider
*/
public ServerProviderInfo getServerProviderInfo() {
- return this.providerInfo;
+ return this.providerInfo;
}
/**
@@ -329,12 +328,12 @@ public class Context {
}
/**
- * Sets the current running script, if a script stops it will call this method with a null argument
+ * Sets the hook parser
*
- * @param script
+ * @param hookParser
*/
- public void setRunningScript(final Script script) {
- this.runningScript = script;
+ public void setHookParser(final HookParser hookParser) {
+ this.hookParser = hookParser;
}
/**
@@ -345,21 +344,23 @@ public class Context {
public Script getRunningScript() {
return this.runningScript;
}
-
+
+ /**
+ * Sets the current running script, if a script stops it will call this method with a null argument
+ *
+ * @param script
+ */
+ public void setRunningScript(final Script script) {
+ this.runningScript = script;
+ }
+
/**
* Gets the random handler
+ *
* @return random handler
*/
public RandomHandler getRandomHandler() {
- return this.randomHandler;
- }
-
- public static String getUsername() {
- return username;
- }
-
- public static void setUsername(String username) {
- Context.username = username;
+ return this.randomHandler;
}
public JSONParser getJsonParser() {
diff --git a/src/main/java/org/parabot/core/ProjectProperties.java b/src/main/java/org/parabot/core/ProjectProperties.java
index d905a29..a9f44d9 100644
--- a/src/main/java/org/parabot/core/ProjectProperties.java
+++ b/src/main/java/org/parabot/core/ProjectProperties.java
@@ -18,6 +18,14 @@ public class ProjectProperties {
setProperties();
}
+ public static Version getProjectVersion() {
+ return new Version(getInstance().getCached().getProperty("application.version"));
+ }
+
+ public static ProjectProperties getInstance() {
+ return instance == null ? instance = new ProjectProperties() : instance;
+ }
+
private void setProperties() {
InputStream input;
try {
@@ -35,12 +43,4 @@ public class ProjectProperties {
private Properties getCached() {
return cached;
}
-
- public static Version getProjectVersion() {
- return new Version(getInstance().getCached().getProperty("application.version"));
- }
-
- public static ProjectProperties getInstance() {
- return instance == null ? instance = new ProjectProperties() : instance;
- }
}
diff --git a/src/main/java/org/parabot/core/asm/ASMClassLoader.java b/src/main/java/org/parabot/core/asm/ASMClassLoader.java
index ee0478d..7039488 100644
--- a/src/main/java/org/parabot/core/asm/ASMClassLoader.java
+++ b/src/main/java/org/parabot/core/asm/ASMClassLoader.java
@@ -1,6 +1,5 @@
package org.parabot.core.asm;
-
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.classpath.ClassPath;
@@ -16,92 +15,90 @@ import java.util.HashMap;
import java.util.Map;
/**
- *
* Makes classnodes into runnable classes
- *
+ *
* @author Everel
* @author Matt
- *
*/
public class ASMClassLoader extends ClassLoader {
- private Map> classCache;
- public ClassPath classPath;
-
- public ASMClassLoader(final ClassPath classPath) {
- this.classCache = new HashMap>();
- this.classPath = classPath;
- }
+ public ClassPath classPath;
+ private Map> classCache;
- @Override
- protected URL findResource(String name) {
- if (getSystemResource(name) == null) {
- if (classPath.resources.containsKey(name)) {
- try {
- return classPath.resources.get(name).toURI().toURL();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- return null;
- }
- } else {
- return null;
- }
- }
- return getSystemResource(name);
- }
+ public ASMClassLoader(final ClassPath classPath) {
+ this.classCache = new HashMap>();
+ this.classPath = classPath;
+ }
- @Override
- public Class> loadClass(String name) throws ClassNotFoundException {
- return findClass(name);
- }
+ @Override
+ protected URL findResource(String name) {
+ if (getSystemResource(name) == null) {
+ if (classPath.resources.containsKey(name)) {
+ try {
+ return classPath.resources.get(name).toURI().toURL();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ return null;
+ }
+ } else {
+ return null;
+ }
+ }
+ return getSystemResource(name);
+ }
- @Override
- protected Class> findClass(String name) throws ClassNotFoundException {
- try {
- return getSystemClassLoader().loadClass(name);
- } catch (Exception ignored) {
-
- }
- String key = name.replace('.', '/');
- if (classCache.containsKey(key)) {
- return classCache.get(key);
- }
- ClassNode node = classPath.classes.get(key);
- if (node != null) {
- classPath.classes.remove(key);
- Class> c = nodeToClass(node);
- classCache.put(key, c);
- return c;
- }
- return getSystemClassLoader().loadClass(name);
- }
+ @Override
+ public Class> loadClass(String name) throws ClassNotFoundException {
+ return findClass(name);
+ }
- private final Class> nodeToClass(ClassNode node) {
- if (super.findLoadedClass(node.name) != null) {
- return findLoadedClass(node.name);
- }
- ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- node.accept(cw);
- byte[] b = cw.toByteArray();
- return defineClass(node.name.replace('/', '.'), b, 0, b.length,
- getDomain());
- }
+ @Override
+ protected Class> findClass(String name) throws ClassNotFoundException {
+ try {
+ return getSystemClassLoader().loadClass(name);
+ } catch (Exception ignored) {
- private final ProtectionDomain getDomain() {
- CodeSource code = null;
- try {
- code = new CodeSource(new URL("http://www.url.com/"), (Certificate[]) null);
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return new ProtectionDomain(code, getPermissions());
- }
+ }
+ String key = name.replace('.', '/');
+ if (classCache.containsKey(key)) {
+ return classCache.get(key);
+ }
+ ClassNode node = classPath.classes.get(key);
+ if (node != null) {
+ classPath.classes.remove(key);
+ Class> c = nodeToClass(node);
+ classCache.put(key, c);
+ return c;
+ }
+ return getSystemClassLoader().loadClass(name);
+ }
- private final Permissions getPermissions() {
- Permissions permissions = new Permissions();
- permissions.add(new AllPermission());
- return permissions;
- }
+ private final Class> nodeToClass(ClassNode node) {
+ if (super.findLoadedClass(node.name) != null) {
+ return findLoadedClass(node.name);
+ }
+ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+ node.accept(cw);
+ byte[] b = cw.toByteArray();
+ return defineClass(node.name.replace('/', '.'), b, 0, b.length,
+ getDomain());
+ }
+
+ private final ProtectionDomain getDomain() {
+ CodeSource code = null;
+ try {
+ code = new CodeSource(new URL("http://www.url.com/"), (Certificate[]) null);
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ return new ProtectionDomain(code, getPermissions());
+ }
+
+ private final Permissions getPermissions() {
+ Permissions permissions = new Permissions();
+ permissions.add(new AllPermission());
+ return permissions;
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/ASMUtils.java b/src/main/java/org/parabot/core/asm/ASMUtils.java
index 300374a..5cc0128 100644
--- a/src/main/java/org/parabot/core/asm/ASMUtils.java
+++ b/src/main/java/org/parabot/core/asm/ASMUtils.java
@@ -9,151 +9,150 @@ import org.parabot.core.Context;
import java.lang.reflect.Modifier;
/**
- *
* A collection of various asm util methods
- *
+ *
* @author Everel
- *
*/
public class ASMUtils implements Opcodes {
- public static FieldNode getField(ClassNode node, String fieldName) {
- for (final Object fieldNode : node.fields) {
- FieldNode fieldNodeObject = (FieldNode) fieldNode;
- if (fieldNodeObject.name.equals(fieldName)) {
- return fieldNodeObject;
- }
- }
- return null;
- }
-
- public static FieldNode getField(ClassNode node, String fieldName, String desc) {
- if(desc == null) {
- return getField(node, fieldName);
- }
- for (final Object fieldNode : node.fields) {
- FieldNode fieldNodeObject = (FieldNode) fieldNode;
- if (fieldNodeObject.name.equals(fieldName) && fieldNodeObject.desc.equals(desc)) {
- return fieldNodeObject;
- }
- }
- return null;
- }
+ public static FieldNode getField(ClassNode node, String fieldName) {
+ for (final Object fieldNode : node.fields) {
+ FieldNode fieldNodeObject = (FieldNode) fieldNode;
+ if (fieldNodeObject.name.equals(fieldName)) {
+ return fieldNodeObject;
+ }
+ }
+ return null;
+ }
- public static ClassNode getClass(String className) {
- Context context = Context.getInstance();
- for (ClassNode node : context.getClassPath().classes.values()) {
- if (node.name.equals(className)) {
- return node;
- }
- }
- return null;
- }
+ public static FieldNode getField(ClassNode node, String fieldName, String desc) {
+ if (desc == null) {
+ return getField(node, fieldName);
+ }
+ for (final Object fieldNode : node.fields) {
+ FieldNode fieldNodeObject = (FieldNode) fieldNode;
+ if (fieldNodeObject.name.equals(fieldName) && fieldNodeObject.desc.equals(desc)) {
+ return fieldNodeObject;
+ }
+ }
+ return null;
+ }
- public static MethodNode getMethod(final String className,
- final String methodName, final String methodDesc) {
- return getMethod(getClass(className), methodName, methodDesc);
- }
+ public static ClassNode getClass(String className) {
+ Context context = Context.getInstance();
+ for (ClassNode node : context.getClassPath().classes.values()) {
+ if (node.name.equals(className)) {
+ return node;
+ }
+ }
+ return null;
+ }
- public static MethodNode getMethod(final ClassNode location,
- final String methodName, final String methodDesc) {
- for (Object mn : location.methods) {
- MethodNode methodNode = (MethodNode) mn;
- if (methodNode.name.equals(methodName) && methodNode.desc.equals(methodDesc)) {
- return methodNode;
- }
- }
- return null;
- }
+ public static MethodNode getMethod(final String className,
+ final String methodName, final String methodDesc) {
+ return getMethod(getClass(className), methodName, methodDesc);
+ }
- /**
- * Return right opcode for desc
- *
- * @param desc
- * @return return opcode
- */
- public static int getReturnOpcode(String desc) {
- desc = desc.substring(desc.indexOf("L") + 1);
- if (desc.length() > 1) {
- return ARETURN;
- }
- final char c = desc.charAt(0);
- switch (c) {
- case 'I':
- case 'Z':
- case 'B':
- case 'S':
- case 'C':
- return IRETURN;
- case 'J':
- return LRETURN;
- case 'F':
- return FRETURN;
- case 'D':
- return DRETURN;
- case 'V': // void, method desc
- return RETURN;
- }
- throw new RuntimeException("Wrong desc type: " + c);
- }
+ public static MethodNode getMethod(final ClassNode location,
+ final String methodName, final String methodDesc) {
+ for (Object mn : location.methods) {
+ MethodNode methodNode = (MethodNode) mn;
+ if (methodNode.name.equals(methodName) && methodNode.desc.equals(methodDesc)) {
+ return methodNode;
+ }
+ }
+ return null;
+ }
- public static int getLoadOpcode(String desc) {
- desc = desc.substring(desc.indexOf("L") + 1);
- if (desc.length() > 1) {
- return ALOAD;
- }
- final char c = desc.charAt(0);
- switch (c) {
- case 'I':
- case 'Z':
- case 'B':
- case 'S':
- case 'C':
- return ILOAD;
- case 'J':
- return LLOAD;
- case 'F':
- return FLOAD;
- case 'D':
- return DLOAD;
- }
- throw new RuntimeException("eek " + c);
- }
-
- public static void makePublic(ClassNode node) {
- if (!Modifier.isPublic(node.access)) {
- if (Modifier.isPrivate(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PRIVATE);
- }
- if (Modifier.isProtected(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PROTECTED);
- }
- node.access = node.access | Opcodes.ACC_PUBLIC;
- }
- }
-
- public static void makePublic(MethodNode node) {
- if (!Modifier.isPublic(node.access)) {
- if (Modifier.isPrivate(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PRIVATE);
- }
- if (Modifier.isProtected(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PROTECTED);
- }
- node.access = node.access | Opcodes.ACC_PUBLIC;
- }
- }
-
- public static void makePublic(FieldNode node) {
- if (!Modifier.isPublic(node.access)) {
- if (Modifier.isPrivate(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PRIVATE);
- }
- if (Modifier.isProtected(node.access)) {
- node.access = node.access & (~Opcodes.ACC_PROTECTED);
- }
- node.access = node.access | Opcodes.ACC_PUBLIC;
- }
- }
+ /**
+ * Return right opcode for desc
+ *
+ * @param desc
+ *
+ * @return return opcode
+ */
+ public static int getReturnOpcode(String desc) {
+ desc = desc.substring(desc.indexOf("L") + 1);
+ if (desc.length() > 1) {
+ return ARETURN;
+ }
+ final char c = desc.charAt(0);
+ switch (c) {
+ case 'I':
+ case 'Z':
+ case 'B':
+ case 'S':
+ case 'C':
+ return IRETURN;
+ case 'J':
+ return LRETURN;
+ case 'F':
+ return FRETURN;
+ case 'D':
+ return DRETURN;
+ case 'V': // void, method desc
+ return RETURN;
+ }
+ throw new RuntimeException("Wrong desc type: " + c);
+ }
+
+ public static int getLoadOpcode(String desc) {
+ desc = desc.substring(desc.indexOf("L") + 1);
+ if (desc.length() > 1) {
+ return ALOAD;
+ }
+ final char c = desc.charAt(0);
+ switch (c) {
+ case 'I':
+ case 'Z':
+ case 'B':
+ case 'S':
+ case 'C':
+ return ILOAD;
+ case 'J':
+ return LLOAD;
+ case 'F':
+ return FLOAD;
+ case 'D':
+ return DLOAD;
+ }
+ throw new RuntimeException("eek " + c);
+ }
+
+ public static void makePublic(ClassNode node) {
+ if (!Modifier.isPublic(node.access)) {
+ if (Modifier.isPrivate(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PRIVATE);
+ }
+ if (Modifier.isProtected(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PROTECTED);
+ }
+ node.access = node.access | Opcodes.ACC_PUBLIC;
+ }
+ }
+
+ public static void makePublic(MethodNode node) {
+ if (!Modifier.isPublic(node.access)) {
+ if (Modifier.isPrivate(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PRIVATE);
+ }
+ if (Modifier.isProtected(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PROTECTED);
+ }
+ node.access = node.access | Opcodes.ACC_PUBLIC;
+ }
+ }
+
+ public static void makePublic(FieldNode node) {
+ if (!Modifier.isPublic(node.access)) {
+ if (Modifier.isPrivate(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PRIVATE);
+ }
+ if (Modifier.isProtected(node.access)) {
+ node.access = node.access & (~Opcodes.ACC_PROTECTED);
+ }
+ node.access = node.access | Opcodes.ACC_PUBLIC;
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/ClassRemapper.java b/src/main/java/org/parabot/core/asm/ClassRemapper.java
index f35b604..ff8cb56 100644
--- a/src/main/java/org/parabot/core/asm/ClassRemapper.java
+++ b/src/main/java/org/parabot/core/asm/ClassRemapper.java
@@ -5,19 +5,20 @@ import org.objectweb.asm.commons.Remapper;
import java.util.HashMap;
public class ClassRemapper extends Remapper {
- private static HashMap remapNames = new HashMap();
- static {
- remapNames.put("java/net/Socket", "org/parabot/core/network/proxy/ProxySocket");
- remapNames.put("java/net/NetworkInterface", "org/parabot/core/network/NetworkInterface");
- }
+ private static HashMap remapNames = new HashMap();
- @Override
- public String map(String str) {
- String s = remapNames.get(str);
- if (s != null) {
- return s;
- } else {
- return str;
- }
- }
+ static {
+ remapNames.put("java/net/Socket", "org/parabot/core/network/proxy/ProxySocket");
+ remapNames.put("java/net/NetworkInterface", "org/parabot/core/network/NetworkInterface");
+ }
+
+ @Override
+ public String map(String str) {
+ String s = remapNames.get(str);
+ if (s != null) {
+ return s;
+ } else {
+ return str;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/asm/RedirectClassAdapter.java b/src/main/java/org/parabot/core/asm/RedirectClassAdapter.java
index 03cbb66..9ecebad 100644
--- a/src/main/java/org/parabot/core/asm/RedirectClassAdapter.java
+++ b/src/main/java/org/parabot/core/asm/RedirectClassAdapter.java
@@ -16,124 +16,126 @@ import java.util.Map;
public class RedirectClassAdapter extends ClassVisitor implements Opcodes {
- private static final Map> redirects = new HashMap>();
+ private static final Map> redirects = new HashMap>();
+ private static PrintStream str_out, class_out;
- private String className;
-
- private static PrintStream str_out, class_out;
-
- static {
- redirects.put("java/awt/Toolkit", ToolkitRedirect.class);
- redirects.put("java/lang/Class", ClassRedirect.class);
+ static {
+ redirects.put("java/awt/Toolkit", ToolkitRedirect.class);
+ redirects.put("java/lang/Class", ClassRedirect.class);
// redirects.put("java/lang/ClassLoader", ClassLoaderRedirect.class);
- redirects.put("java/lang/Runtime", RuntimeRedirect.class);
- redirects.put("java/lang/Thread", ThreadRedirect.class);
- redirects.put("java/lang/StackTraceElement",
- StackTraceElementRedirect.class);
- redirects.put("java/lang/ProcessBuilder", ProcessBuilderRedirect.class);
- redirects.put("java/lang/System", SystemRedirect.class);
- }
+ redirects.put("java/lang/Runtime", RuntimeRedirect.class);
+ redirects.put("java/lang/Thread", ThreadRedirect.class);
+ redirects.put("java/lang/StackTraceElement",
+ StackTraceElementRedirect.class);
+ redirects.put("java/lang/ProcessBuilder", ProcessBuilderRedirect.class);
+ redirects.put("java/lang/System", SystemRedirect.class);
+ }
- public RedirectClassAdapter(ClassVisitor cv) {
- super(ASM5, cv);
- if (str_out == null && Core.shouldDump())
- try {
- str_out = new PrintStream(new FileOutputStream(new File(Directories.getWorkspace(),"strings.txt")));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- if(class_out == null && Core.shouldDump())
- try {
- class_out = new PrintStream(new FileOutputStream(new File(Directories.getWorkspace(),"classes.txt")));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
+ private String className;
- @Override
- public void visit(int version, int access, String name, String signature,
- String superName, String[] interfaces) {
- this.className = name;
- super.visit(version, access, name, signature, superName, interfaces);
- if(class_out != null) {
- class_out.println(className + " References:");
- }
- }
+ public RedirectClassAdapter(ClassVisitor cv) {
+ super(ASM5, cv);
+ if (str_out == null && Core.shouldDump()) {
+ try {
+ str_out = new PrintStream(new FileOutputStream(new File(Directories.getWorkspace(), "strings.txt")));
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+ if (class_out == null && Core.shouldDump()) {
+ try {
+ class_out = new PrintStream(new FileOutputStream(new File(Directories.getWorkspace(), "classes.txt")));
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+ }
- @Override
- public void visitEnd(){
- super.visitEnd();
- if(class_out != null){
- class_out.println();
- class_out.println();
- }
- }
+ public static SecurityException createSecurityException() {
+ Exception e = new Exception();
+ StackTraceElement[] elements = e.getStackTrace();
+ return new SecurityException("Unsafe operation blocked. Op:"
+ + elements[1].getMethodName());
+ }
- @Override
- public MethodVisitor visitMethod(int access, String name, String desc,
- String signature, String[] exceptions) {
- return new ReflectionMethodVisitor(name, desc, super.visitMethod(
- access, name, desc, signature, exceptions));
- }
+ @Override
+ public void visit(int version, int access, String name, String signature,
+ String superName, String[] interfaces) {
+ this.className = name;
+ super.visit(version, access, name, signature, superName, interfaces);
+ if (class_out != null) {
+ class_out.println(className + " References:");
+ }
+ }
- private class ReflectionMethodVisitor extends MethodVisitor {
+ @Override
+ public void visitEnd() {
+ super.visitEnd();
+ if (class_out != null) {
+ class_out.println();
+ class_out.println();
+ }
+ }
- public ReflectionMethodVisitor(String name, String desc,
- MethodVisitor mv) {
- super(ASM5, mv);
- }
+ @Override
+ public MethodVisitor visitMethod(int access, String name, String desc,
+ String signature, String[] exceptions) {
+ return new ReflectionMethodVisitor(name, desc, super.visitMethod(
+ access, name, desc, signature, exceptions));
+ }
- @Override
- public void visitLdcInsn(Object o) {
- if (o instanceof String && str_out != null) {
- str_out.println(className + " " + o);
- }
- super.visitLdcInsn(o);
- }
+ private class ReflectionMethodVisitor extends MethodVisitor {
- @Override
- public void visitMethodInsn(int opcode, String owner, String name,
- String desc, boolean itf) {
- if (Core.isSecure()) {
- if (redirects.containsKey(owner) && !name.equals("")
- && !name.equals("")) {
- if (opcode != INVOKESTATIC) {
- desc = "(L" + owner + ";" + desc.substring(1);
- }
- opcode = INVOKESTATIC;
- owner = redirects.get(owner).getName()
- .replaceAll("\\.", "/");
- }
- }
+ public ReflectionMethodVisitor(String name, String desc,
+ MethodVisitor mv) {
+ super(ASM5, mv);
+ }
- if(class_out != null) {
- class_out.println(owner);
- }
+ @Override
+ public void visitLdcInsn(Object o) {
+ if (o instanceof String && str_out != null) {
+ str_out.println(className + " " + o);
+ }
+ super.visitLdcInsn(o);
+ }
- super.visitMethodInsn(opcode, owner, name, desc, itf);
- }
+ @Override
+ public void visitMethodInsn(int opcode, String owner, String name,
+ String desc, boolean itf) {
+ if (Core.isSecure()) {
+ if (redirects.containsKey(owner) && !name.equals("")
+ && !name.equals("")) {
+ if (opcode != INVOKESTATIC) {
+ desc = "(L" + owner + ";" + desc.substring(1);
+ }
+ opcode = INVOKESTATIC;
+ owner = redirects.get(owner).getName()
+ .replaceAll("\\.", "/");
+ }
+ }
- @Override
- public void visitFieldInsn(int opcode, String owner, String name,
- String desc){
- if (Core.isSecure() && (opcode == GETSTATIC || opcode == PUTSTATIC)) {
- if (redirects.containsKey(owner)) {
- owner = redirects.get(owner).getName()
- .replaceAll("\\.", "/");
- }
- }
- if(class_out != null)
- class_out.println(owner);
- super.visitFieldInsn(opcode, owner, name, desc);
- }
+ if (class_out != null) {
+ class_out.println(owner);
+ }
- }
+ super.visitMethodInsn(opcode, owner, name, desc, itf);
+ }
- public static SecurityException createSecurityException() {
- Exception e = new Exception();
- StackTraceElement[] elements = e.getStackTrace();
- return new SecurityException("Unsafe operation blocked. Op:"
- + elements[1].getMethodName());
- }
+ @Override
+ public void visitFieldInsn(int opcode, String owner, String name,
+ String desc) {
+ if (Core.isSecure() && (opcode == GETSTATIC || opcode == PUTSTATIC)) {
+ if (redirects.containsKey(owner)) {
+ owner = redirects.get(owner).getName()
+ .replaceAll("\\.", "/");
+ }
+ }
+ if (class_out != null) {
+ class_out.println(owner);
+ }
+ super.visitFieldInsn(opcode, owner, name, desc);
+ }
+
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/adapters/AddCallbackAdapter.java b/src/main/java/org/parabot/core/asm/adapters/AddCallbackAdapter.java
index 2159b7e..1384452 100644
--- a/src/main/java/org/parabot/core/asm/adapters/AddCallbackAdapter.java
+++ b/src/main/java/org/parabot/core/asm/adapters/AddCallbackAdapter.java
@@ -1,98 +1,89 @@
package org.parabot.core.asm.adapters;
-import java.lang.reflect.Modifier;
-
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
-import org.objectweb.asm.tree.AbstractInsnNode;
-import org.objectweb.asm.tree.InsnList;
-import org.objectweb.asm.tree.InsnNode;
-import org.objectweb.asm.tree.JumpInsnNode;
-import org.objectweb.asm.tree.LabelNode;
-import org.objectweb.asm.tree.MethodInsnNode;
-import org.objectweb.asm.tree.MethodNode;
-import org.objectweb.asm.tree.VarInsnNode;
+import org.objectweb.asm.tree.*;
import org.parabot.core.asm.ASMUtils;
import org.parabot.core.asm.interfaces.Injectable;
+import java.lang.reflect.Modifier;
+
/**
- *
* Injects a callback, invokes a given static method
- *
+ *
* @author Everel
- *
*/
public class AddCallbackAdapter implements Injectable, Opcodes {
- private MethodNode method;
- private String invokeClass;
- private String invokeMethod;
- private String desc;
- private int[] args;
- private boolean conditional;
+ private MethodNode method;
+ private String invokeClass;
+ private String invokeMethod;
+ private String desc;
+ private int[] args;
+ private boolean conditional;
- public AddCallbackAdapter(final MethodNode method,
- final String invokeClass, final String invokeMethod,
- final String desc, final int[] args, final boolean conditional) {
- this.method = method;
- this.invokeClass = invokeClass;
- this.invokeMethod = invokeMethod;
- this.desc = desc;
- this.args = args;
- this.conditional = conditional;
- }
+ public AddCallbackAdapter(final MethodNode method,
+ final String invokeClass, final String invokeMethod,
+ final String desc, final int[] args, final boolean conditional) {
+ this.method = method;
+ this.invokeClass = invokeClass;
+ this.invokeMethod = invokeMethod;
+ this.desc = desc;
+ this.args = args;
+ this.conditional = conditional;
+ }
- @Override
- public void inject() {
- final Type[] types = Type.getArgumentTypes(this.method.desc);
- InsnList inject = new InsnList();
- Label l0 = new Label();
- inject.add(new LabelNode(l0));
- int offset = 0;
- for (int arg : args) {
- if(Modifier.isStatic(method.access)) {
- int loadOpcode = ASMUtils.getLoadOpcode(types[arg]
- .getDescriptor());
- inject.add(new VarInsnNode(loadOpcode, arg + offset));
- if(loadOpcode == Opcodes.LLOAD) {
- offset++;
- }
- } else {
- inject.add(new VarInsnNode(ASMUtils.getLoadOpcode(types[arg]
- .getDescriptor()), arg + 1));
- }
- }
- inject.add(new MethodInsnNode(INVOKESTATIC,
- this.invokeClass, this.invokeMethod,
- this.desc));
- if(this.conditional) {
- LabelNode ln = new LabelNode(new Label());
- inject.add(new JumpInsnNode(IFEQ, ln));
- if(Type.getReturnType(method.desc).equals(Type.BOOLEAN_TYPE)) {
- inject.add(new InsnNode(ICONST_1));
- inject.add(new InsnNode(IRETURN));
+ @Override
+ public void inject() {
+ final Type[] types = Type.getArgumentTypes(this.method.desc);
+ InsnList inject = new InsnList();
+ Label l0 = new Label();
+ inject.add(new LabelNode(l0));
+ int offset = 0;
+ for (int arg : args) {
+ if (Modifier.isStatic(method.access)) {
+ int loadOpcode = ASMUtils.getLoadOpcode(types[arg]
+ .getDescriptor());
+ inject.add(new VarInsnNode(loadOpcode, arg + offset));
+ if (loadOpcode == Opcodes.LLOAD) {
+ offset++;
+ }
} else {
- inject.add(new InsnNode(RETURN));
+ inject.add(new VarInsnNode(ASMUtils.getLoadOpcode(types[arg]
+ .getDescriptor()), arg + 1));
+ }
+ }
+ inject.add(new MethodInsnNode(INVOKESTATIC,
+ this.invokeClass, this.invokeMethod,
+ this.desc));
+ if (this.conditional) {
+ LabelNode ln = new LabelNode(new Label());
+ inject.add(new JumpInsnNode(IFEQ, ln));
+ if (Type.getReturnType(method.desc).equals(Type.BOOLEAN_TYPE)) {
+ inject.add(new InsnNode(ICONST_1));
+ inject.add(new InsnNode(IRETURN));
+ } else {
+ inject.add(new InsnNode(RETURN));
}
inject.add(ln);
- }
-
- if(method.name.startsWith("<") && !Modifier.isStatic(method.access)) {
- // find target
- AbstractInsnNode target = null;
- for(AbstractInsnNode node : this.method.instructions.toArray()) {
- if(node.getOpcode() == Opcodes.INVOKESPECIAL) {
- target = node;
- break;
- }
- }
-
- if(target != null) {
- this.method.instructions.insert(target, inject);
- }
- } else {
- this.method.instructions.insert(inject);
- }
- }
+ }
+
+ if (method.name.startsWith("<") && !Modifier.isStatic(method.access)) {
+ // find target
+ AbstractInsnNode target = null;
+ for (AbstractInsnNode node : this.method.instructions.toArray()) {
+ if (node.getOpcode() == Opcodes.INVOKESPECIAL) {
+ target = node;
+ break;
+ }
+ }
+
+ if (target != null) {
+ this.method.instructions.insert(target, inject);
+ }
+ } else {
+ this.method.instructions.insert(inject);
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/adapters/AddDebugAdapter.java b/src/main/java/org/parabot/core/asm/adapters/AddDebugAdapter.java
index ec4d68d..e6c14f7 100644
--- a/src/main/java/org/parabot/core/asm/adapters/AddDebugAdapter.java
+++ b/src/main/java/org/parabot/core/asm/adapters/AddDebugAdapter.java
@@ -2,42 +2,37 @@ package org.parabot.core.asm.adapters;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.tree.ClassNode;
-import org.objectweb.asm.tree.InsnList;
-import org.objectweb.asm.tree.LabelNode;
-import org.objectweb.asm.tree.LdcInsnNode;
-import org.objectweb.asm.tree.MethodInsnNode;
-import org.objectweb.asm.tree.MethodNode;
+import org.objectweb.asm.tree.*;
public class AddDebugAdapter {
- private ClassNode owner;
- private MethodNode mn;
-
- public AddDebugAdapter(ClassNode owner, MethodNode mn) {
- this.owner = owner;
- this.mn = mn;
- }
-
- public AddDebugAdapter(MethodNode mn) {
- this.mn = mn;
- }
-
- public void inject() {
- InsnList inject = new InsnList();
- Label l0 = new Label();
- inject.add(new LabelNode(l0));
-
- String callString = owner.name + "." + mn.name + " " + mn.desc;
- LdcInsnNode ldc = new LdcInsnNode(callString);
-
- MethodInsnNode methodNode = new MethodInsnNode(Opcodes.INVOKESTATIC, "org/parabot/core/Core", "debug",
- "(Ljava/lang/String;)V");
-
- inject.add(ldc);
- inject.add(methodNode);
-
- mn.instructions.insert(inject);
-
- }
+ private ClassNode owner;
+ private MethodNode mn;
+
+ public AddDebugAdapter(ClassNode owner, MethodNode mn) {
+ this.owner = owner;
+ this.mn = mn;
+ }
+
+ public AddDebugAdapter(MethodNode mn) {
+ this.mn = mn;
+ }
+
+ public void inject() {
+ InsnList inject = new InsnList();
+ Label l0 = new Label();
+ inject.add(new LabelNode(l0));
+
+ String callString = owner.name + "." + mn.name + " " + mn.desc;
+ LdcInsnNode ldc = new LdcInsnNode(callString);
+
+ MethodInsnNode methodNode = new MethodInsnNode(Opcodes.INVOKESTATIC, "org/parabot/core/Core", "debug",
+ "(Ljava/lang/String;)V");
+
+ inject.add(ldc);
+ inject.add(methodNode);
+
+ mn.instructions.insert(inject);
+
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/adapters/AddGetterAdapter.java b/src/main/java/org/parabot/core/asm/adapters/AddGetterAdapter.java
index 7ee094a..1823cb4 100644
--- a/src/main/java/org/parabot/core/asm/adapters/AddGetterAdapter.java
+++ b/src/main/java/org/parabot/core/asm/adapters/AddGetterAdapter.java
@@ -1,7 +1,5 @@
package org.parabot.core.asm.adapters;
-import java.lang.reflect.Modifier;
-
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
@@ -11,174 +9,166 @@ import org.parabot.core.Core;
import org.parabot.core.asm.ASMUtils;
import org.parabot.core.asm.interfaces.Injectable;
+import java.lang.reflect.Modifier;
+
/**
* Adds a method into a Classnode which returns a field
- *
+ *
* @author Everel
- *
*/
public class AddGetterAdapter implements Opcodes, Injectable {
- private ClassNode into;
- private ClassNode fieldLocation;
- private FieldNode fieldNode;
- private String methodName;
- private String returnDesc;
- private boolean staticField;
- private boolean staticMethod;
- private long multiplier;
+ private ClassNode into;
+ private ClassNode fieldLocation;
+ private FieldNode fieldNode;
+ private String methodName;
+ private String returnDesc;
+ private boolean staticField;
+ private boolean staticMethod;
+ private long multiplier;
- /**
- *
- * @param into
- * - classnode to inject getter method in
- * @param fieldLocation
- * - classnode where field is located
- * @param fieldNode
- * - field name to get
- * @param methodName
- * - method name of getter
- * @param returnDesc
- * - return type of method, can be null for default return
- * @param staticMethod
- * - pass true if you want the method to be static
- * @param multiplier
- * - if this field requires a multipli
- */
- public AddGetterAdapter(final ClassNode into,
- final ClassNode fieldLocation, final FieldNode fieldNode,
- final String methodName, final String returnDesc,
- final boolean staticMethod, final long multiplier) {
- this.into = into;
- this.fieldLocation = fieldLocation;
- this.fieldNode = fieldNode;
- this.methodName = methodName;
- this.returnDesc = returnDesc == null ? fieldNode.desc : returnDesc;
- this.staticField = Modifier.isStatic(fieldNode.access);
- this.staticMethod = staticMethod;
- this.multiplier = multiplier;
- }
+ /**
+ * @param into - classnode to inject getter method in
+ * @param fieldLocation - classnode where field is located
+ * @param fieldNode - field name to get
+ * @param methodName - method name of getter
+ * @param returnDesc - return type of method, can be null for default return
+ * @param staticMethod - pass true if you want the method to be static
+ * @param multiplier - if this field requires a multipli
+ */
+ public AddGetterAdapter(final ClassNode into,
+ final ClassNode fieldLocation, final FieldNode fieldNode,
+ final String methodName, final String returnDesc,
+ final boolean staticMethod, final long multiplier) {
+ this.into = into;
+ this.fieldLocation = fieldLocation;
+ this.fieldNode = fieldNode;
+ this.methodName = methodName;
+ this.returnDesc = returnDesc == null ? fieldNode.desc : returnDesc;
+ this.staticField = Modifier.isStatic(fieldNode.access);
+ this.staticMethod = staticMethod;
+ this.multiplier = multiplier;
+ }
- /**
- *
- * @param fieldLocation
- * @param fieldNode
- * @param methodName
- */
- public AddGetterAdapter(final ClassNode fieldLocation,
- final FieldNode fieldNode, final String methodName) {
- this.into = fieldLocation;
- this.fieldLocation = fieldLocation;
- this.fieldNode = fieldNode;
- this.methodName = methodName;
- this.returnDesc = fieldNode.desc;
- this.staticField = Modifier.isStatic(fieldNode.access);
- this.staticMethod = false;
- }
+ /**
+ * @param fieldLocation
+ * @param fieldNode
+ * @param methodName
+ */
+ public AddGetterAdapter(final ClassNode fieldLocation,
+ final FieldNode fieldNode, final String methodName) {
+ this.into = fieldLocation;
+ this.fieldLocation = fieldLocation;
+ this.fieldNode = fieldNode;
+ this.methodName = methodName;
+ this.returnDesc = fieldNode.desc;
+ this.staticField = Modifier.isStatic(fieldNode.access);
+ this.staticMethod = false;
+ }
- /**
- * Validates if this getter can be injected, if not a runtime exception is
- * thrown
- */
- public void validate() {
- if (methodName == null) {
- throw new RuntimeException("Null method name");
- }
- if (into == null) {
- final StringBuilder sb = new StringBuilder();
- sb.append("Into ClassNode is null, at : ").append(methodName)
- .append("()");
- throw new RuntimeException(sb.toString());
- }
- if (fieldNode == null) {
- final StringBuilder sb = new StringBuilder();
- sb.append("FieldLocation ClassNode is null, at : ")
- .append(methodName).append("()");
- throw new RuntimeException(sb.toString());
- }
- if (fieldNode == null) {
- final StringBuilder sb = new StringBuilder();
- sb.append("FieldNode is null, at : ").append(methodName)
- .append("()");
- throw new RuntimeException(sb.toString());
- }
- for (final Object methodNode : into.methods) {
- MethodNode methodNodeObject = (MethodNode) methodNode;
- if (methodNodeObject.name.equals(methodName)) {
- final Type[] args = Type.getArgumentTypes(methodNodeObject.desc);
- if (args != null && args.length != 0) {
- continue;
- }
- final StringBuilder sb = new StringBuilder();
- sb.append("Duplicated method detected. ").append(methodName)
- .append("() in ").append(into.name);
- throw new RuntimeException(sb.toString());
- }
- }
- }
+ /**
+ * Validates if this getter can be injected, if not a runtime exception is
+ * thrown
+ */
+ public void validate() {
+ if (methodName == null) {
+ throw new RuntimeException("Null method name");
+ }
+ if (into == null) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("Into ClassNode is null, at : ").append(methodName)
+ .append("()");
+ throw new RuntimeException(sb.toString());
+ }
+ if (fieldNode == null) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("FieldLocation ClassNode is null, at : ")
+ .append(methodName).append("()");
+ throw new RuntimeException(sb.toString());
+ }
+ if (fieldNode == null) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("FieldNode is null, at : ").append(methodName)
+ .append("()");
+ throw new RuntimeException(sb.toString());
+ }
+ for (final Object methodNode : into.methods) {
+ MethodNode methodNodeObject = (MethodNode) methodNode;
+ if (methodNodeObject.name.equals(methodName)) {
+ final Type[] args = Type.getArgumentTypes(methodNodeObject.desc);
+ if (args != null && args.length != 0) {
+ continue;
+ }
+ final StringBuilder sb = new StringBuilder();
+ sb.append("Duplicated method detected. ").append(methodName)
+ .append("() in ").append(into.name);
+ throw new RuntimeException(sb.toString());
+ }
+ }
+ }
- /**
- * Injects this the method getter
- */
- @Override
- public void inject() {
- Core.verbose("Injecting: " + this.toString());
+ /**
+ * Injects this the method getter
+ */
+ @Override
+ public void inject() {
+ Core.verbose("Injecting: " + this.toString());
- MethodNode method = new MethodNode(ACC_PUBLIC
- | (staticMethod ? ACC_STATIC : 0), methodName, "()"
- + returnDesc, null, null);
- if (!staticField) {
- method.visitVarInsn(ALOAD, 0);
- }
- if(staticField) {
- ASMUtils.makePublic(fieldNode);
- }
- method.visitFieldInsn(staticField ? GETSTATIC : GETFIELD,
- fieldLocation.name, fieldNode.name, fieldNode.desc);
- if (!fieldNode.desc.equals(returnDesc)) {
- if (returnDesc.contains("L")) {
- if (!returnDesc.contains("[")) {
- method.visitTypeInsn(CHECKCAST,
- returnDesc.replaceFirst("L", "")
- .replaceAll(";", ""));
- } else {
- method.visitTypeInsn(CHECKCAST, returnDesc);
- }
- }
- }
+ MethodNode method = new MethodNode(ACC_PUBLIC
+ | (staticMethod ? ACC_STATIC : 0), methodName, "()"
+ + returnDesc, null, null);
+ if (!staticField) {
+ method.visitVarInsn(ALOAD, 0);
+ }
+ if (staticField) {
+ ASMUtils.makePublic(fieldNode);
+ }
+ method.visitFieldInsn(staticField ? GETSTATIC : GETFIELD,
+ fieldLocation.name, fieldNode.name, fieldNode.desc);
+ if (!fieldNode.desc.equals(returnDesc)) {
+ if (returnDesc.contains("L")) {
+ if (!returnDesc.contains("[")) {
+ method.visitTypeInsn(CHECKCAST,
+ returnDesc.replaceFirst("L", "")
+ .replaceAll(";", ""));
+ } else {
+ method.visitTypeInsn(CHECKCAST, returnDesc);
+ }
+ }
+ }
- if (multiplier != 0) {
- if (fieldNode.desc.equals("I") || fieldNode.desc.equals("S")) {
- method.visitInsn(I2L);
- }
- method.visitLdcInsn(new Long(multiplier));
- method.visitInsn(LMUL);
- if (returnDesc.equals("I") || returnDesc.equals("S")) {
- method.visitInsn(L2I);
- }
- if (returnDesc.equals("S")) {
- method.visitInsn(I2S);
- }
- } else if (fieldNode.desc.equals("J") && returnDesc.equals("I")) {
- method.visitInsn(L2I);
- } else if (fieldNode.desc.equals("I") && returnDesc.equals("J")) {
- method.visitInsn(I2L);
- }
+ if (multiplier != 0) {
+ if (fieldNode.desc.equals("I") || fieldNode.desc.equals("S")) {
+ method.visitInsn(I2L);
+ }
+ method.visitLdcInsn(new Long(multiplier));
+ method.visitInsn(LMUL);
+ if (returnDesc.equals("I") || returnDesc.equals("S")) {
+ method.visitInsn(L2I);
+ }
+ if (returnDesc.equals("S")) {
+ method.visitInsn(I2S);
+ }
+ } else if (fieldNode.desc.equals("J") && returnDesc.equals("I")) {
+ method.visitInsn(L2I);
+ } else if (fieldNode.desc.equals("I") && returnDesc.equals("J")) {
+ method.visitInsn(I2L);
+ }
- method.visitInsn(ASMUtils.getReturnOpcode(returnDesc));
- method.visitMaxs(1, 1);
- into.methods.add(method);
- }
+ method.visitInsn(ASMUtils.getReturnOpcode(returnDesc));
+ method.visitMaxs(1, 1);
+ into.methods.add(method);
+ }
- @Override
- public String toString() {
- return new StringBuilder("[Injectable: getter, into classname: ")
- .append(into.name).append(", field classname: ")
- .append(fieldLocation.name).append(", field name: ")
- .append(fieldNode.name).append(", field desc: ")
- .append(fieldNode.desc).append(", method name: ")
- .append(methodName).append(", return desc: ")
- .append(returnDesc).append(", static method: ")
- .append(staticMethod).append(", static field: ")
- .append(staticField).append("]").toString();
- }
+ @Override
+ public String toString() {
+ return new StringBuilder("[Injectable: getter, into classname: ")
+ .append(into.name).append(", field classname: ")
+ .append(fieldLocation.name).append(", field name: ")
+ .append(fieldNode.name).append(", field desc: ")
+ .append(fieldNode.desc).append(", method name: ")
+ .append(methodName).append(", return desc: ")
+ .append(returnDesc).append(", static method: ")
+ .append(staticMethod).append(", static field: ")
+ .append(staticField).append("]").toString();
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/asm/adapters/AddInterfaceAdapter.java b/src/main/java/org/parabot/core/asm/adapters/AddInterfaceAdapter.java
index a444cdb..d87c071 100644
--- a/src/main/java/org/parabot/core/asm/adapters/AddInterfaceAdapter.java
+++ b/src/main/java/org/parabot/core/asm/adapters/AddInterfaceAdapter.java
@@ -7,55 +7,53 @@ import org.parabot.core.asm.ASMUtils;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class appends an interface to a class
- *
+ *
* @author Everel
- *
*/
public class AddInterfaceAdapter implements Injectable {
- private static String accessorPackage;
-
- private ClassNode node;
- private String interfaceClass;
+ private static String accessorPackage;
- public AddInterfaceAdapter(ClassNode node, String interfaceClass) {
- this.node = node;
- this.interfaceClass = interfaceClass;
- }
+ private ClassNode node;
+ private String interfaceClass;
- public AddInterfaceAdapter(String className, String interfaceClass) {
- this.node = ASMUtils.getClass(className);
- this.interfaceClass = interfaceClass;
- }
+ public AddInterfaceAdapter(ClassNode node, String interfaceClass) {
+ this.node = node;
+ this.interfaceClass = interfaceClass;
+ }
- public static void setAccessorPackage(String packageName) {
- accessorPackage = packageName;
- }
+ public AddInterfaceAdapter(String className, String interfaceClass) {
+ this.node = ASMUtils.getClass(className);
+ this.interfaceClass = interfaceClass;
+ }
- public static String getAccessorPackage() {
- return accessorPackage;
- }
+ public static String getAccessorPackage() {
+ return accessorPackage;
+ }
- @Override
- public void inject() {
- Core.verbose("Injecting: " + this.toString());
- addInterface(node, accessorPackage + interfaceClass);
- }
+ public static void setAccessorPackage(String packageName) {
+ accessorPackage = packageName;
+ }
- protected static void addInterface(ClassNode node, String i) {
- ASMUtils.makePublic(node);
- for(Object mn : node.methods) {
- MethodNode methodNode = (MethodNode) mn;
- if(methodNode.name.startsWith(" 0;
- if (!isStatic) {
- method.visitVarInsn(ALOAD, 0);
- }
- if (desc.equals("I")) {
- method.visitVarInsn(ILOAD, 1);
- } else if (desc.equals("J")) {
- method.visitVarInsn(Opcodes.LLOAD, 1);
- } else {
- method.visitVarInsn(ALOAD, 1);
- }
- method.visitFieldInsn(isStatic ? PUTSTATIC : PUTFIELD,
- fieldLocation.name, field.name, field.desc);
- method.visitInsn(RETURN);
- method.visitMaxs(2, 2);
- into.methods.add(method);
- }
+ private static void addSetter(ClassNode fieldLocation, ClassNode into,
+ FieldNode field, String name, String desc, boolean methodStatic) {
+ if (desc.contains("L") && !desc.endsWith("Ljava/lang/String;")) {
+ desc = "Ljava/lang/Object;";
+ }
+ MethodNode method = new MethodNode(ACC_PUBLIC
+ | (methodStatic ? ACC_STATIC : 0), name, "(" + desc + ")V",
+ null, null);
+ boolean isStatic = (field.access & ACC_STATIC) > 0;
+ if (!isStatic) {
+ method.visitVarInsn(ALOAD, 0);
+ }
+ if (desc.equals("I")) {
+ method.visitVarInsn(ILOAD, 1);
+ } else if (desc.equals("J")) {
+ method.visitVarInsn(Opcodes.LLOAD, 1);
+ } else {
+ method.visitVarInsn(ALOAD, 1);
+ }
+ method.visitFieldInsn(isStatic ? PUTSTATIC : PUTFIELD,
+ fieldLocation.name, field.name, field.desc);
+ method.visitInsn(RETURN);
+ method.visitMaxs(2, 2);
+ into.methods.add(method);
+ }
- /**
- * Injects the setter
- */
- @Override
- public void inject() {
- Core.verbose("Injecting: " + this.toString());
- addSetter(fieldLocation, into, field, name, desc, methodStatic);
- }
+ /**
+ * Injects the setter
+ */
+ @Override
+ public void inject() {
+ Core.verbose("Injecting: " + this.toString());
+ addSetter(fieldLocation, into, field, name, desc, methodStatic);
+ }
- @Override
- public String toString() {
- return new StringBuilder("[Injectable: setter, into classname: ")
- .append(into.name).append(", field classname: ")
- .append(fieldLocation.name).append(", field name: ")
- .append(field.name).append(", field desc: ").append(field.desc)
- .append(", method name: ").append(name)
- .append(", method desc: ").append(desc)
- .append(", static method: ").append(methodStatic).append("]")
- .toString();
- }
+ @Override
+ public String toString() {
+ return new StringBuilder("[Injectable: setter, into classname: ")
+ .append(into.name).append(", field classname: ")
+ .append(fieldLocation.name).append(", field name: ")
+ .append(field.name).append(", field desc: ").append(field.desc)
+ .append(", method name: ").append(name)
+ .append(", method desc: ").append(desc)
+ .append(", static method: ").append(methodStatic).append("]")
+ .toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/adapters/AddSuperAdapter.java b/src/main/java/org/parabot/core/asm/adapters/AddSuperAdapter.java
index 68b8aef..7caef8a 100644
--- a/src/main/java/org/parabot/core/asm/adapters/AddSuperAdapter.java
+++ b/src/main/java/org/parabot/core/asm/adapters/AddSuperAdapter.java
@@ -1,7 +1,5 @@
package org.parabot.core.asm.adapters;
-import java.util.ListIterator;
-
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
@@ -11,60 +9,60 @@ import org.parabot.core.Core;
import org.parabot.core.asm.ASMUtils;
import org.parabot.core.asm.interfaces.Injectable;
+import java.util.ListIterator;
+
/**
- *
* This class is used for changing the super class of a class
- *
- * @author Everel
*
+ * @author Everel
*/
public class AddSuperAdapter implements Injectable {
- private ClassNode node;
- private String superClass;
+ private ClassNode node;
+ private String superClass;
- public AddSuperAdapter(final ClassNode node, final String superClass) {
- this.node = node;
- this.superClass = superClass;
- }
+ public AddSuperAdapter(final ClassNode node, final String superClass) {
+ this.node = node;
+ this.superClass = superClass;
+ }
- public AddSuperAdapter(final String className, final String superClass) {
- this.node = ASMUtils.getClass(className);
- this.superClass = superClass;
- }
+ public AddSuperAdapter(final String className, final String superClass) {
+ this.node = ASMUtils.getClass(className);
+ this.superClass = superClass;
+ }
- @Override
- public void inject() {
- Core.verbose("Injecting: " + this.toString());
- setSuper(node, superClass);
- }
+ private static final void setSuper(final ClassNode node,
+ final String superClass) {
+ ListIterator> mli = node.methods.listIterator();
+ while (mli.hasNext()) {
+ MethodNode mn = (MethodNode) mli.next();
+ if (mn.name.equals("")) {
+ ListIterator> ili = mn.instructions.iterator();
+ while (ili.hasNext()) {
+ AbstractInsnNode ain = (AbstractInsnNode) ili.next();
+ if (ain.getOpcode() == Opcodes.INVOKESPECIAL) {
+ MethodInsnNode min = (MethodInsnNode) ain;
+ if (!min.owner.equals(node.name)) {
+ min.owner = superClass;
+ }
+ break;
+ }
+ }
+ }
+ }
+ node.superName = superClass;
+ }
- private static final void setSuper(final ClassNode node,
- final String superClass) {
- ListIterator> mli = node.methods.listIterator();
- while (mli.hasNext()) {
- MethodNode mn = (MethodNode) mli.next();
- if (mn.name.equals("")) {
- ListIterator> ili = mn.instructions.iterator();
- while (ili.hasNext()) {
- AbstractInsnNode ain = (AbstractInsnNode) ili.next();
- if (ain.getOpcode() == Opcodes.INVOKESPECIAL) {
- MethodInsnNode min = (MethodInsnNode) ain;
- if(!min.owner.equals(node.name)) {
- min.owner = superClass;
- }
- break;
- }
- }
- }
- }
- node.superName = superClass;
- }
+ @Override
+ public void inject() {
+ Core.verbose("Injecting: " + this.toString());
+ setSuper(node, superClass);
+ }
- @Override
- public String toString() {
- return new StringBuilder("[Injectable: super, class name: ")
- .append(node.name).append(", super: ").append(superClass)
- .append("]").toString();
- }
+ @Override
+ public String toString() {
+ return new StringBuilder("[Injectable: super, class name: ")
+ .append(node.name).append(", super: ").append(superClass)
+ .append("]").toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/hooks/HookFile.java b/src/main/java/org/parabot/core/asm/hooks/HookFile.java
index 52a22ed..05fa6f6 100644
--- a/src/main/java/org/parabot/core/asm/hooks/HookFile.java
+++ b/src/main/java/org/parabot/core/asm/hooks/HookFile.java
@@ -1,50 +1,50 @@
package org.parabot.core.asm.hooks;
-import java.io.File;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-
import org.parabot.core.parsers.hooks.HookParser;
import org.parabot.core.parsers.hooks.JSONHookParser;
import org.parabot.core.parsers.hooks.XMLHookParser;
import org.parabot.environment.api.utils.WebUtil;
+import java.io.File;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
public class HookFile {
- public static final int TYPE_XML = 0;
- public static final int TYPE_JSON = 1;
-
- private URL url;
- private int type;
-
- public HookFile(File file, int type) throws MalformedURLException {
- this(file.toURI().toURL(), type);
- }
-
- public HookFile(URL url, int type) {
- setType(type);
- this.url = url;
- }
-
- private void setType(int type) {
- if(type < 0 || type > 1) {
- throw new IllegalArgumentException("This type does not exist");
- }
- this.type = type;
- }
-
- public InputStream getInputStream() {
- return WebUtil.getInputStream(url);
- }
-
- public HookParser getParser() {
- switch(type) {
- case TYPE_XML:
- return new XMLHookParser(this);
- case TYPE_JSON:
- return new JSONHookParser(this);
- }
- return null;
- }
+ public static final int TYPE_XML = 0;
+ public static final int TYPE_JSON = 1;
+
+ private URL url;
+ private int type;
+
+ public HookFile(File file, int type) throws MalformedURLException {
+ this(file.toURI().toURL(), type);
+ }
+
+ public HookFile(URL url, int type) {
+ setType(type);
+ this.url = url;
+ }
+
+ private void setType(int type) {
+ if (type < 0 || type > 1) {
+ throw new IllegalArgumentException("This type does not exist");
+ }
+ this.type = type;
+ }
+
+ public InputStream getInputStream() {
+ return WebUtil.getInputStream(url);
+ }
+
+ public HookParser getParser() {
+ switch (type) {
+ case TYPE_XML:
+ return new XMLHookParser(this);
+ case TYPE_JSON:
+ return new JSONHookParser(this);
+ }
+ return null;
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/interfaces/Injectable.java b/src/main/java/org/parabot/core/asm/interfaces/Injectable.java
index f899369..3f6e3ad 100644
--- a/src/main/java/org/parabot/core/asm/interfaces/Injectable.java
+++ b/src/main/java/org/parabot/core/asm/interfaces/Injectable.java
@@ -2,14 +2,14 @@ package org.parabot.core.asm.interfaces;
/**
* Injectable
- * @author Everel
*
+ * @author Everel
*/
public interface Injectable {
-
- /**
- * Injects bytecode into a class
- */
- public void inject();
+
+ /**
+ * Injects bytecode into a class
+ */
+ public void inject();
}
diff --git a/src/main/java/org/parabot/core/asm/redirect/ClassLoaderRedirect.java b/src/main/java/org/parabot/core/asm/redirect/ClassLoaderRedirect.java
index 54bc5d5..96b33e0 100644
--- a/src/main/java/org/parabot/core/asm/redirect/ClassLoaderRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/ClassLoaderRedirect.java
@@ -12,13 +12,13 @@ public class ClassLoaderRedirect extends ClassLoader {
static int count = 0;
- public static Class>loadClass(ClassLoader c,String name){
- throw RedirectClassAdapter.createSecurityException();
- }
+ public static Class> loadClass(ClassLoader c, String name) {
+ throw RedirectClassAdapter.createSecurityException();
+ }
- public static ClassLoader getParent(ClassLoader c){
- throw RedirectClassAdapter.createSecurityException();
- }
+ public static ClassLoader getParent(ClassLoader c) {
+ throw RedirectClassAdapter.createSecurityException();
+ }
public static URL getResource(ClassLoader classLoader, String name) {
Core.verbose("#getResource requested for ClassLoaderRedirect (" + name + ")");
diff --git a/src/main/java/org/parabot/core/asm/redirect/ClassRedirect.java b/src/main/java/org/parabot/core/asm/redirect/ClassRedirect.java
index 4e0be58..dde1499 100644
--- a/src/main/java/org/parabot/core/asm/redirect/ClassRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/ClassRedirect.java
@@ -8,9 +8,22 @@ import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
public class ClassRedirect {
+ public static ProtectionDomain getProtectionDomain(final Class> clazz) {
+ System.err.println(clazz.getName() + " getProtectionDomain request granted.");
+
+ return AccessController.doPrivileged(new PrivilegedAction() {
+ public ProtectionDomain run() {
+ return clazz.getProtectionDomain();
+ }
+ });
+ }
+
public static Object newInstance(Class> c) throws IllegalAccessException, InstantiationException {
if (validStack()) {
return c.newInstance();
@@ -136,8 +149,9 @@ public class ClassRedirect {
private static boolean validStack() {
Exception e = new Exception();
for (StackTraceElement elem : e.getStackTrace()) {
- if (elem.getClassName().equals(Script.class.getName()))
+ if (elem.getClassName().equals(Script.class.getName())) {
return true;
+ }
}
return false;
}
diff --git a/src/main/java/org/parabot/core/asm/redirect/FileRedirect.java b/src/main/java/org/parabot/core/asm/redirect/FileRedirect.java
index 3ce697a..0737c84 100644
--- a/src/main/java/org/parabot/core/asm/redirect/FileRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/FileRedirect.java
@@ -9,7 +9,7 @@ import java.util.ArrayList;
/**
* @author JKetelaar
*/
-public class FileRedirect extends File{
+public class FileRedirect extends File {
private static ArrayList cachedFiles = new ArrayList<>();
@@ -35,57 +35,57 @@ public class FileRedirect extends File{
sout(uri.toString());
}
- public static boolean exists(File file){
+ public static boolean exists(File file) {
sout(file.toString());
return file.exists();
}
- public static boolean isFile(File file){
+ public static boolean isFile(File file) {
sout(file.toString());
return file.isFile();
}
- public static long length(File file){
+ public static long length(File file) {
sout(file.toString());
return file.length();
}
- public static boolean mkdirs(File file){
+ public static boolean mkdirs(File file) {
sout(file.toString());
return file.mkdirs();
}
- public static boolean mkdir(File file){
+ public static boolean mkdir(File file) {
sout(file.toString());
return file.mkdir();
}
- public static boolean isDirectory(File file){
+ public static boolean isDirectory(File file) {
sout(file.toString());
return file.isDirectory();
}
- public static String getAbsolutePath(File file){
+ public static String getAbsolutePath(File file) {
sout(file.toString());
return file.getAbsolutePath();
}
- public static File getAbsoluteFile(File file){
+ public static File getAbsoluteFile(File file) {
sout(file.toString());
return file.getAbsoluteFile();
}
- public static File[] listFiles(File file){
+ public static File[] listFiles(File file) {
sout(file.toString());
return file.listFiles();
}
- public static String getName(File file){
+ public static String getName(File file) {
sout(file.getName());
return file.getName();
}
- private static void sout(String s){
+ private static void sout(String s) {
if (!cachedFiles.contains(s)) {
Core.verbose("Server requested file: " + s);
cachedFiles.add(s);
diff --git a/src/main/java/org/parabot/core/asm/redirect/PacketCallback.java b/src/main/java/org/parabot/core/asm/redirect/PacketCallback.java
index 88795d9..40a11c5 100644
--- a/src/main/java/org/parabot/core/asm/redirect/PacketCallback.java
+++ b/src/main/java/org/parabot/core/asm/redirect/PacketCallback.java
@@ -1,9 +1,9 @@
package org.parabot.core.asm.redirect;
public class PacketCallback {
-
- public static void onPacket(String methodName,int value){
- System.out.println(methodName + "(" + value + ")");
- }
+
+ public static void onPacket(String methodName, int value) {
+ System.out.println(methodName + "(" + value + ")");
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/redirect/SystemRedirect.java b/src/main/java/org/parabot/core/asm/redirect/SystemRedirect.java
index e8ce836..d00fc1f 100644
--- a/src/main/java/org/parabot/core/asm/redirect/SystemRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/SystemRedirect.java
@@ -1,7 +1,6 @@
package org.parabot.core.asm.redirect;
import org.parabot.core.Core;
-import org.parabot.core.Directories;
import java.io.InputStream;
import java.io.PrintStream;
@@ -10,7 +9,7 @@ public class SystemRedirect {
public static PrintStream out = System.out;
public static PrintStream err = System.err;
- public static InputStream in = System.in;
+ public static InputStream in = System.in;
public static long currentTimeMillis() {
return System.currentTimeMillis();
diff --git a/src/main/java/org/parabot/core/asm/redirect/ThreadRedirect.java b/src/main/java/org/parabot/core/asm/redirect/ThreadRedirect.java
index 0c60ec3..c40d4d2 100644
--- a/src/main/java/org/parabot/core/asm/redirect/ThreadRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/ThreadRedirect.java
@@ -1,66 +1,64 @@
package org.parabot.core.asm.redirect;
-import org.parabot.core.Core;
import org.parabot.core.asm.RedirectClassAdapter;
public class ThreadRedirect {
- private static int count = 0;
+ private static int count = 0;
- public static void start(Thread t){
- t.start();
- }
+ public static void start(Thread t) {
+ t.start();
+ }
- public static void setPriority(Thread t,int i){
- t.setPriority(i);
- }
+ public static void setPriority(Thread t, int i) {
+ t.setPriority(i);
+ }
- public static void setDaemon(Thread t,boolean b){
- t.setDaemon(b);
- }
+ public static void setDaemon(Thread t, boolean b) {
+ t.setDaemon(b);
+ }
- public static void interrupt(Thread t){
- t.interrupt();
- }
+ public static void interrupt(Thread t) {
+ t.interrupt();
+ }
- public static Thread currentThread(){
- return null;
- }
+ public static Thread currentThread() {
+ return new Thread();
+ }
- public static void join(Thread t) throws InterruptedException{
- t.join();
- }
+ public static void join(Thread t) throws InterruptedException {
+ t.join();
+ }
- public static void join(Thread t,long l) throws InterruptedException{
- t.join(l);
- }
+ public static void join(Thread t, long l) throws InterruptedException {
+ t.join(l);
+ }
- public static void join(Thread t, long l,int i) throws InterruptedException{
- t.join(l, i);
- }
+ public static void join(Thread t, long l, int i) throws InterruptedException {
+ t.join(l, i);
+ }
- public static ClassLoader getContextClassLoader(Thread t){
- return null;
- }
+ public static ClassLoader getContextClassLoader(Thread t) {
+ return null;
+ }
- public static ThreadGroup getThreadGroup(Thread t){
- throw RedirectClassAdapter.createSecurityException();
- }
+ public static ThreadGroup getThreadGroup(Thread t) {
+ throw RedirectClassAdapter.createSecurityException();
+ }
- public static void setName(Thread t, String name){
- t.setName(name);
- }
+ public static void setName(Thread t, String name) {
+ t.setName(name);
+ }
- public static String getName(Thread t){
- return t.getName();
- }
+ public static String getName(Thread t) {
+ return t.getName();
+ }
- public static void sleep(long time) throws InterruptedException{
- Thread.sleep(time);
- }
+ public static void sleep(long time) throws InterruptedException {
+ Thread.sleep(time);
+ }
-
- public static void setUncaughtExceptionHandler(Thread t, Thread.UncaughtExceptionHandler handler){
- t.setUncaughtExceptionHandler(handler);
- }
+ public static void setUncaughtExceptionHandler(Thread t, Thread.UncaughtExceptionHandler handler) {
+ t.setUncaughtExceptionHandler(handler);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/redirect/ToolkitRedirect.java b/src/main/java/org/parabot/core/asm/redirect/ToolkitRedirect.java
index 1bafabc..45f1326 100644
--- a/src/main/java/org/parabot/core/asm/redirect/ToolkitRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/ToolkitRedirect.java
@@ -5,69 +5,74 @@ import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.image.ImageProducer;
import java.io.IOException;
import java.net.URL;
public class ToolkitRedirect {
- private static final Clipboard clipboard = new Clipboard("default");
+ private static final Clipboard clipboard = new Clipboard("default");
- static{
- clipboard.setContents(new Transferable() {
- @Override
- public DataFlavor[] getTransferDataFlavors() {
- return new DataFlavor[0];
- }
+ static {
+ clipboard.setContents(new Transferable() {
+ @Override
+ public DataFlavor[] getTransferDataFlavors() {
+ return new DataFlavor[0];
+ }
- @Override
- public boolean isDataFlavorSupported(DataFlavor flavor) {
- return false;
- }
+ @Override
+ public boolean isDataFlavorSupported(DataFlavor flavor) {
+ return false;
+ }
- @Override
- public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
- throw new UnsupportedFlavorException(flavor);
- }
- }, null);
- }
+ @Override
+ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
+ throw new UnsupportedFlavorException(flavor);
+ }
+ }, null);
+ }
- public static Toolkit getDefaultToolkit(){
- return Toolkit.getDefaultToolkit();
- }
-
- public static Dimension getScreenSize(Toolkit t){
- return new Dimension(0,0);
- }
+ public static Toolkit getDefaultToolkit() {
+ return Toolkit.getDefaultToolkit();
+ }
- public static Image createImage(Toolkit t,byte[] b){
- return null;
- }
+ public static Dimension getScreenSize(Toolkit t) {
+ return new Dimension(0, 0);
+ }
- public static Image createImage(Toolkit t, String s){
- return null;
- }
-
- public static Image getImage(Toolkit t,URL u){
- return t.getImage(u);
- }
-
- public static Image getImage(Toolkit t,String str){
- return t.getImage(str);
- }
+ public static Image createImage(Toolkit t, byte[] b) {
+ return t.createImage(b);
+ }
- public static Cursor createCustomCursor(Toolkit t, Image i, Point p, String s){
- return Cursor.getDefaultCursor();
- }
+ public static Image createImage(Toolkit t, String s) {
+ return t.createImage(s);
+ }
- public static Clipboard getSystemClipboard(Toolkit toolkit){
- return clipboard;
- }
+ public static Image createImage(Toolkit t, ImageProducer i) {
+ return t.createImage(i);
+ }
- public static void sync(Toolkit toolkit){
- toolkit.sync();
- }
+ public static Image getImage(Toolkit t, URL u) {
+ return t.getImage(u);
+ }
- public static void sync(){
- Toolkit.getDefaultToolkit().sync();
- }
+ public static Image getImage(Toolkit t, String str) {
+ return t.getImage(str);
+ }
+
+ public static Cursor createCustomCursor(Toolkit t, Image i, Point p, String s) {
+ return Cursor.getDefaultCursor();
+ }
+
+ public static Clipboard getSystemClipboard(Toolkit toolkit) {
+ return clipboard;
+ }
+
+ public static void sync(Toolkit toolkit) {
+ toolkit.sync();
+ }
+
+ public static void sync() {
+ Toolkit.getDefaultToolkit().sync();
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/redirect/URLRedirect.java b/src/main/java/org/parabot/core/asm/redirect/URLRedirect.java
index c4de84f..217653b 100644
--- a/src/main/java/org/parabot/core/asm/redirect/URLRedirect.java
+++ b/src/main/java/org/parabot/core/asm/redirect/URLRedirect.java
@@ -3,6 +3,6 @@ package org.parabot.core.asm.redirect;
/**
* @author JKetelaar
*/
-public class URLRedirect{
-
+public class URLRedirect {
+
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Callback.java b/src/main/java/org/parabot/core/asm/wrappers/Callback.java
index 17602ee..039b41c 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Callback.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Callback.java
@@ -6,47 +6,45 @@ import org.parabot.core.asm.adapters.AddCallbackAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class is used for injecting a callback into a methodnode
- *
- * @author Everel
*
+ * @author Everel
*/
public class Callback implements Injectable {
- private MethodNode method;
- private String invokeClass;
- private String invokeMethod;
- private String desc;
- private int[] args;
- private boolean conditional;
-
- public Callback(final String className, final String methodName,
- final String methodDesc, final String callbackClass,
- final String callbackMethod, final String callbackDesc, String args, final boolean conditional) {
- this.method = ASMUtils.getMethod(className, methodName, methodDesc);
- this.invokeClass = callbackClass;
- this.invokeMethod = callbackMethod;
- this.desc = callbackDesc;
- this.conditional = conditional;
- if (args.contains(",")) {
- final String[] strArgs = args.split(",");
- this.args = new int[strArgs.length];
- for (int i = 0; i < this.args.length; i++) {
- this.args[i] = Integer.parseInt(strArgs[i]);
- }
- } else {
- this.args = new int[] { Integer.parseInt(args) };
- }
- }
+ private MethodNode method;
+ private String invokeClass;
+ private String invokeMethod;
+ private String desc;
+ private int[] args;
+ private boolean conditional;
- @Override
- public void inject() {
- getAdapter().inject();
- }
+ public Callback(final String className, final String methodName,
+ final String methodDesc, final String callbackClass,
+ final String callbackMethod, final String callbackDesc, String args, final boolean conditional) {
+ this.method = ASMUtils.getMethod(className, methodName, methodDesc);
+ this.invokeClass = callbackClass;
+ this.invokeMethod = callbackMethod;
+ this.desc = callbackDesc;
+ this.conditional = conditional;
+ if (args.contains(",")) {
+ final String[] strArgs = args.split(",");
+ this.args = new int[strArgs.length];
+ for (int i = 0; i < this.args.length; i++) {
+ this.args[i] = Integer.parseInt(strArgs[i]);
+ }
+ } else {
+ this.args = new int[]{ Integer.parseInt(args) };
+ }
+ }
- public AddCallbackAdapter getAdapter() {
- return new AddCallbackAdapter(this.method, this.invokeClass,
- this.invokeMethod, this.desc, this.args, this.conditional);
- }
+ @Override
+ public void inject() {
+ getAdapter().inject();
+ }
+
+ public AddCallbackAdapter getAdapter() {
+ return new AddCallbackAdapter(this.method, this.invokeClass,
+ this.invokeMethod, this.desc, this.args, this.conditional);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Getter.java b/src/main/java/org/parabot/core/asm/wrappers/Getter.java
index a83ec3b..f11d12f 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Getter.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Getter.java
@@ -8,75 +8,73 @@ import org.parabot.core.asm.adapters.AddGetterAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class injects a getter which gets a specific field
- *
- * @author Everel
*
+ * @author Everel
*/
public class Getter implements Injectable {
- private ClassNode into;
- private ClassNode fieldLocation;
- private FieldNode fieldNode;
- private String methodName;
- private String returnDesc;
- private boolean staticMethod;
- private long multiplier;
-
- /**
- *
- * @param into - classnode to inject getter method in
- * @param fieldLocation - classnode where field is located
- * @param fieldNode - field name to get
- * @param methodName - method name of getter
- * @param returnDesc - return type of method, can be null for default return
- * @param staticMethod - pass true if you want the method to be static
- * @param multiplier - if there is one, otherwise 0L
- * @param fieldDesc - desc of the field, null if there are no duplicate field names
- */
- public Getter(final String into, final String fieldLocation, final String fieldNode,
- final String methodName, final String returnDesc, final boolean staticMethod, final long multiplier,
- final String fieldDesc) {
- this.into = ASMUtils.getClass(into);
- this.fieldLocation = ASMUtils.getClass(fieldLocation);
- this.fieldNode = ASMUtils.getField(ASMUtils.getClass(fieldLocation), fieldNode, fieldDesc);
- this.methodName = methodName;
- this.returnDesc = returnDesc == null ? this.fieldNode.desc : returnDesc;
- this.staticMethod = staticMethod;
- this.multiplier = multiplier;
- Core.verbose(methodName + "[" + fieldLocation + "." + fieldNode + "]");
- }
-
- /**
- *
- * @param fieldLocation
- * @param fieldNode
- * @param methodName
- */
- public Getter(final String fieldLocation, final String fieldNode, final String methodName) {
- this.into = ASMUtils.getClass(fieldLocation);
- this.fieldLocation = this.into;
- this.fieldNode = ASMUtils.getField(this.into, fieldNode);
- this.methodName = methodName;
- this.returnDesc = this.fieldNode.desc;
- this.staticMethod = false;
- }
-
- /**
- * Short route for getAdaptar().inject();
- * @see AddGetterAdapter#inject
- */
- @Override
- public void inject() {
+ private ClassNode into;
+ private ClassNode fieldLocation;
+ private FieldNode fieldNode;
+ private String methodName;
+ private String returnDesc;
+ private boolean staticMethod;
+ private long multiplier;
+
+ /**
+ * @param into - classnode to inject getter method in
+ * @param fieldLocation - classnode where field is located
+ * @param fieldNode - field name to get
+ * @param methodName - method name of getter
+ * @param returnDesc - return type of method, can be null for default return
+ * @param staticMethod - pass true if you want the method to be static
+ * @param multiplier - if there is one, otherwise 0L
+ * @param fieldDesc - desc of the field, null if there are no duplicate field names
+ */
+ public Getter(final String into, final String fieldLocation, final String fieldNode,
+ final String methodName, final String returnDesc, final boolean staticMethod, final long multiplier,
+ final String fieldDesc) {
+ this.into = ASMUtils.getClass(into);
+ this.fieldLocation = ASMUtils.getClass(fieldLocation);
+ this.fieldNode = ASMUtils.getField(ASMUtils.getClass(fieldLocation), fieldNode, fieldDesc);
+ this.methodName = methodName;
+ this.returnDesc = returnDesc == null ? this.fieldNode.desc : returnDesc;
+ this.staticMethod = staticMethod;
+ this.multiplier = multiplier;
+ Core.verbose(methodName + "[" + fieldLocation + "." + fieldNode + "]");
+ }
+
+ /**
+ * @param fieldLocation
+ * @param fieldNode
+ * @param methodName
+ */
+ public Getter(final String fieldLocation, final String fieldNode, final String methodName) {
+ this.into = ASMUtils.getClass(fieldLocation);
+ this.fieldLocation = this.into;
+ this.fieldNode = ASMUtils.getField(this.into, fieldNode);
+ this.methodName = methodName;
+ this.returnDesc = this.fieldNode.desc;
+ this.staticMethod = false;
+ }
+
+ /**
+ * Short route for getAdaptar().inject();
+ *
+ * @see AddGetterAdapter#inject
+ */
+ @Override
+ public void inject() {
getAdapter().inject();
- }
-
- /**
- * Gets the AddGetterAdapter
- * @return AddGetterAdapter
- */
- public AddGetterAdapter getAdapter() {
- return new AddGetterAdapter(into, fieldLocation, fieldNode, methodName, returnDesc, staticMethod, multiplier);
- }
+ }
+
+ /**
+ * Gets the AddGetterAdapter
+ *
+ * @return AddGetterAdapter
+ */
+ public AddGetterAdapter getAdapter() {
+ return new AddGetterAdapter(into, fieldLocation, fieldNode, methodName, returnDesc, staticMethod, multiplier);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Interface.java b/src/main/java/org/parabot/core/asm/wrappers/Interface.java
index 073f25e..78766a5 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Interface.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Interface.java
@@ -4,41 +4,40 @@ import org.parabot.core.asm.adapters.AddInterfaceAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class appends an interface to a class
- *
- * @author Everel
*
+ * @author Everel
*/
public class Interface implements Injectable {
- private String className;
- private String interfaceClass;
-
- public Interface(String className, String interfaceClass) {
- this.className = className;
- this.interfaceClass = interfaceClass;
- }
-
- /**
- * Adds the interface to the class
- * Short route for getAdapter#inject();
- */
- @Override
- public void inject() {
- getAdapter().inject();
- }
-
- /**
- * Gets the add interface adapter
- * @return AddInterface adapter
- */
- public AddInterfaceAdapter getAdapter() {
- return new AddInterfaceAdapter(className, interfaceClass);
- }
-
- @Override
- public String toString() {
- return String.format("%s implements %s%s", className, AddInterfaceAdapter.getAccessorPackage().replaceAll("/", "."), interfaceClass);
- }
+ private String className;
+ private String interfaceClass;
+
+ public Interface(String className, String interfaceClass) {
+ this.className = className;
+ this.interfaceClass = interfaceClass;
+ }
+
+ /**
+ * Adds the interface to the class
+ * Short route for getAdapter#inject();
+ */
+ @Override
+ public void inject() {
+ getAdapter().inject();
+ }
+
+ /**
+ * Gets the add interface adapter
+ *
+ * @return AddInterface adapter
+ */
+ public AddInterfaceAdapter getAdapter() {
+ return new AddInterfaceAdapter(className, interfaceClass);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s implements %s%s", className, AddInterfaceAdapter.getAccessorPackage().replaceAll("/", "."), interfaceClass);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Invoker.java b/src/main/java/org/parabot/core/asm/wrappers/Invoker.java
index 2f99736..328e073 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Invoker.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Invoker.java
@@ -1,5 +1,6 @@
package org.parabot.core.asm.wrappers;
+import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.parabot.core.asm.ASMUtils;
@@ -7,77 +8,75 @@ import org.parabot.core.asm.adapters.AddInvokerAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class is used for injecting an invoker into a methodnode
- *
- * @author Everel
*
+ * @author Everel
*/
public class Invoker implements Injectable {
- private ClassNode into;
- private ClassNode methodLocation;
- private MethodNode mn;
- private String argsDesc;
- private String returnDesc;
- private String methodName;
- private boolean isInterface;
- private String instanceCast;
- private String argsCheckCastDesc;
-
- private String mName;
- private String mDesc;
+ private ClassNode into;
+ private ClassNode methodLocation;
+ private MethodNode mn;
+ private String argsDesc;
+ private String returnDesc;
+ private String methodName;
+ private boolean isInterface;
+ private String instanceCast;
+ private String argsCheckCastDesc;
- public Invoker(String methodLoc, String invMethName, String argsDesc,
- String returnDesc, String methodName) {
- this(methodLoc, methodLoc, invMethName, argsDesc, returnDesc,
- methodName, false, null, null);
- }
+ private String mName;
+ private String mDesc;
- public Invoker(String into, String methodLoc, String invMethName,
- String argsDesc, String returnDesc, String methodName, boolean isInterface, String instanceCast, String argsCheckCastDesc) {
- this.into = ASMUtils.getClass(into);
- this.methodLocation = ASMUtils.getClass(methodLoc);
- this.mn = getMethod(this.methodLocation, invMethName, argsDesc);
- this.returnDesc = returnDesc;
- this.methodName = methodName;
- this.argsDesc = argsDesc;
- this.isInterface = isInterface;
- this.instanceCast = instanceCast;
-
- this.mName = invMethName;
- this.mDesc = argsDesc + returnDesc;
- this.argsCheckCastDesc = argsCheckCastDesc;
- }
+ public Invoker(String methodLoc, String invMethName, String argsDesc,
+ String returnDesc, String methodName) {
+ this(methodLoc, methodLoc, invMethName, argsDesc, returnDesc,
+ methodName, false, null, null);
+ }
- private static MethodNode getMethod(ClassNode into, String name, String desc) {
- for (Object m : into.methods) {
- MethodNode methodNode = (MethodNode) m;
- String s = methodNode.desc.substring(0, methodNode.desc.indexOf(')') + 1);
- if (methodNode.name.equals(name) && s.equals(desc)) {
- return methodNode;
+ public Invoker(String into, String methodLoc, String invMethName,
+ String argsDesc, String returnDesc, String methodName, boolean isInterface, String instanceCast, String argsCheckCastDesc) {
+ this.into = ASMUtils.getClass(into);
+ this.methodLocation = ASMUtils.getClass(methodLoc);
+ this.mn = getMethod(this.methodLocation, invMethName, argsDesc, returnDesc);
+ this.returnDesc = returnDesc;
+ this.methodName = methodName;
+ this.argsDesc = argsDesc;
+ this.isInterface = isInterface;
+ this.instanceCast = instanceCast;
+
+ this.mName = invMethName;
+ this.mDesc = argsDesc + returnDesc;
+ this.argsCheckCastDesc = argsCheckCastDesc;
+ }
+
+ private static MethodNode getMethod(ClassNode into, String name, String argsDesc, String returnDesc) {
+ for (Object method : into.methods) {
+ MethodNode m = (MethodNode) method;
+ if (m.name.equals(name) && m.desc.substring(0, m.desc.indexOf(')') + 1).equals(argsDesc)
+ && (returnDesc == null || Type.getType(m.desc).getReturnType().getDescriptor().equals(returnDesc))) {
+ return m;
}
}
return null;
- }
+ }
- /**
- * Short route for getAdaptar().inject();
- *
- * @see AddInvokerAdapter#inject
- */
- @Override
- public void inject() {
- getAdapter().inject();
- }
+ /**
+ * Short route for getAdaptar().inject();
+ *
+ * @see AddInvokerAdapter#inject
+ */
+ @Override
+ public void inject() {
+ getAdapter().inject();
+ }
- /**
- * Gets the AddInvokerAdapter
- *
- * @return AddInvokerAdapter
- */
- public AddInvokerAdapter getAdapter() {
- return new AddInvokerAdapter(this.methodLocation, this.into, this.mn, this.mName, this.mDesc,
- this.argsDesc, this.returnDesc, this.methodName, this.isInterface, this.instanceCast, this.argsCheckCastDesc);
- }
+ /**
+ * Gets the AddInvokerAdapter
+ *
+ * @return AddInvokerAdapter
+ */
+ public AddInvokerAdapter getAdapter() {
+ return new AddInvokerAdapter(this.methodLocation, this.into, this.mn, this.mName, this.mDesc,
+ this.argsDesc, this.returnDesc, this.methodName, this.isInterface, this.instanceCast, this.argsCheckCastDesc);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Setter.java b/src/main/java/org/parabot/core/asm/wrappers/Setter.java
index fb8901f..99b4074 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Setter.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Setter.java
@@ -7,49 +7,49 @@ import org.parabot.core.asm.adapters.AddSetterAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
- *
* This class is used for injecting a setter for a specific field
- *
- * @author Everel
*
+ * @author Everel
*/
public class Setter implements Injectable {
- private ClassNode fieldLocation;
- private ClassNode into;
- private FieldNode field;
- private String name;
- private String desc;
- private boolean methodStatic;
-
- public Setter(final String fieldLocation, String into, final String fieldName, final String methodName, final String desc, final boolean methodStatic, final String fieldDesc) {
- this.fieldLocation = ASMUtils.getClass(fieldLocation);
- into = (into == null) ? fieldLocation : into;
- this.into = ASMUtils.getClass(into);
- this.field = ASMUtils.getField(this.fieldLocation, fieldName, fieldDesc);
- this.name = methodName;
- this.desc = (desc == null) ? this.field.desc : desc;
- this.methodStatic = methodStatic;
- }
-
- public Setter(final String fieldLocation, final String fieldName, final String methodName) {
- this(fieldLocation, null, fieldName, methodName, null, false, null);
- }
-
- /**
- * Short route for getAdaptar().inject();
- * @see AddSetterAdapter#inject
- */
- @Override
- public void inject() {
- getAdapter().inject();
- }
-
- /**
- * Gets the AddGetterAdapter
- * @return AddGetterAdapter
- */
- public AddSetterAdapter getAdapter() {
- return new AddSetterAdapter(fieldLocation, into, field, name, desc, methodStatic);
- }
+ private ClassNode fieldLocation;
+ private ClassNode into;
+ private FieldNode field;
+ private String name;
+ private String desc;
+ private boolean methodStatic;
+
+ public Setter(final String fieldLocation, String into, final String fieldName, final String methodName, final String desc, final boolean methodStatic, final String fieldDesc) {
+ this.fieldLocation = ASMUtils.getClass(fieldLocation);
+ into = (into == null) ? fieldLocation : into;
+ this.into = ASMUtils.getClass(into);
+ this.field = ASMUtils.getField(this.fieldLocation, fieldName, fieldDesc);
+ this.name = methodName;
+ this.desc = (desc == null) ? this.field.desc : desc;
+ this.methodStatic = methodStatic;
+ }
+
+ public Setter(final String fieldLocation, final String fieldName, final String methodName) {
+ this(fieldLocation, null, fieldName, methodName, null, false, null);
+ }
+
+ /**
+ * Short route for getAdaptar().inject();
+ *
+ * @see AddSetterAdapter#inject
+ */
+ @Override
+ public void inject() {
+ getAdapter().inject();
+ }
+
+ /**
+ * Gets the AddGetterAdapter
+ *
+ * @return AddGetterAdapter
+ */
+ public AddSetterAdapter getAdapter() {
+ return new AddSetterAdapter(fieldLocation, into, field, name, desc, methodStatic);
+ }
}
diff --git a/src/main/java/org/parabot/core/asm/wrappers/Super.java b/src/main/java/org/parabot/core/asm/wrappers/Super.java
index 73a17e7..4b7cc56 100644
--- a/src/main/java/org/parabot/core/asm/wrappers/Super.java
+++ b/src/main/java/org/parabot/core/asm/wrappers/Super.java
@@ -2,33 +2,32 @@ package org.parabot.core.asm.wrappers;
import org.parabot.core.asm.adapters.AddSuperAdapter;
import org.parabot.core.asm.interfaces.Injectable;
+
/**
- *
* This class is used for changing the super class of a class
- *
- * @author Everel
*
+ * @author Everel
*/
public class Super implements Injectable {
- private String className;
- private String superClassName;
-
- public Super(String className, String superClassName) {
- this.className = className;
- this.superClassName = superClassName;
- }
+ private String className;
+ private String superClassName;
- /**
- * Adds a superclass to a class
- * Short route for getAdapter().inject
- */
- @Override
- public void inject() {
- getAdapter().inject();
- }
-
- public AddSuperAdapter getAdapter() {
- return new AddSuperAdapter(className, superClassName);
- }
+ public Super(String className, String superClassName) {
+ this.className = className;
+ this.superClassName = superClassName;
+ }
+
+ /**
+ * Adds a superclass to a class
+ * Short route for getAdapter().inject
+ */
+ @Override
+ public void inject() {
+ getAdapter().inject();
+ }
+
+ public AddSuperAdapter getAdapter() {
+ return new AddSuperAdapter(className, superClassName);
+ }
}
diff --git a/src/main/java/org/parabot/core/build/BuildPath.java b/src/main/java/org/parabot/core/build/BuildPath.java
index 5ca4971..8908d14 100644
--- a/src/main/java/org/parabot/core/build/BuildPath.java
+++ b/src/main/java/org/parabot/core/build/BuildPath.java
@@ -1,11 +1,9 @@
package org.parabot.core.build;
/**
- *
* Class used for adding urls to the buildpath
- *
- * @author Everel
*
+ * @author Everel
*/
public class BuildPath extends org.parabot.api.io.build.BuildPath {
diff --git a/src/main/java/org/parabot/core/classpath/ClassPath.java b/src/main/java/org/parabot/core/classpath/ClassPath.java
index 5a9459f..8f81263 100644
--- a/src/main/java/org/parabot/core/classpath/ClassPath.java
+++ b/src/main/java/org/parabot/core/classpath/ClassPath.java
@@ -1,12 +1,17 @@
package org.parabot.core.classpath;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.commons.RemappingClassAdapter;
+import org.objectweb.asm.tree.ClassNode;
+import org.parabot.core.Directories;
+import org.parabot.core.asm.ClassRemapper;
+import org.parabot.core.asm.RedirectClassAdapter;
+import org.parabot.core.build.BuildPath;
+import org.parabot.core.io.SizeInputStream;
+import org.parabot.core.ui.components.VerboseLoader;
+
+import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
@@ -20,292 +25,281 @@ import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassWriter;
-import org.objectweb.asm.commons.RemappingClassAdapter;
-import org.objectweb.asm.tree.ClassNode;
-import org.parabot.core.Directories;
-import org.parabot.core.asm.ClassRemapper;
-import org.parabot.core.asm.RedirectClassAdapter;
-import org.parabot.core.build.BuildPath;
-import org.parabot.core.io.SizeInputStream;
-import org.parabot.core.ui.components.VerboseLoader;
-
/**
* Manages, parses and dumps class files & jars
- *
+ *
* @author Everel
* @author Matt
*/
public class ClassPath {
- public final ArrayList classNames;
- public final HashMap classes;
- public final Map resources;
- public URL lastParsed;
- private ClassRemapper classRemapper;
- private boolean isJar;
- private boolean parseJar;
- private ArrayList jarFiles;
+ public final ArrayList classNames;
+ public final HashMap classes;
+ public final Map resources;
+ public URL lastParsed;
+ private ClassRemapper classRemapper;
+ private boolean isJar;
+ private boolean parseJar;
+ private ArrayList jarFiles;
+ public ClassPath() {
+ this(false);
+ }
- public ClassPath() {
- this(false);
- }
+ public ClassPath(final boolean isJar) {
+ this.classNames = new ArrayList();
+ this.classes = new HashMap();
+ this.resources = new HashMap();
+ this.classRemapper = new ClassRemapper();
+ this.parseJar = true;
+ this.jarFiles = new ArrayList();
+ this.isJar = isJar;
+ }
- public ClassPath(final boolean isJar) {
- this.classNames = new ArrayList();
- this.classes = new HashMap();
- this.resources = new HashMap();
- this.classRemapper = new ClassRemapper();
- this.parseJar = true;
- this.jarFiles = new ArrayList();
- this.isJar = isJar;
- }
+ public void addJar(final File file) {
+ try {
+ addJar(file.toURI().toURL());
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ }
- public void addJar(final File file) {
- try {
- addJar(file.toURI().toURL());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
+ public void addJar(final URL url) {
+ this.lastParsed = url;
+ try {
+ addJar(url.openConnection());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
- public void addJar(final URL url) {
- this.lastParsed = url;
- try {
- addJar(url.openConnection());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Adds a jar to this classpath
+ *
+ * @param connection
+ */
+ public void addJar(final URLConnection connection) {
+ try {
+ final int size = connection.getContentLength();
+ final SizeInputStream sizeInputStream = new SizeInputStream(
+ connection.getInputStream(), size, VerboseLoader.get());
+ final ZipInputStream zin = new ZipInputStream(sizeInputStream);
+ ZipEntry e;
+ while ((e = zin.getNextEntry()) != null) {
+ if (e.isDirectory()) {
+ continue;
+ }
+ if (e.getName().endsWith(".class")) {
+ loadClass(zin);
+ } else {
+ loadResource(e.getName(), zin);
+ }
+ VerboseLoader.setState("Downloading: " + e.getName());
+ }
+ zin.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ VerboseLoader.get().onProgressUpdate(100);
+ }
- /**
- * Adds a jar to this classpath
- *
- * @param connection
- */
- public void addJar(final URLConnection connection) {
- try {
- final int size = connection.getContentLength();
- final SizeInputStream sizeInputStream = new SizeInputStream(
- connection.getInputStream(), size, VerboseLoader.get());
- final ZipInputStream zin = new ZipInputStream(sizeInputStream);
- ZipEntry e;
- while ((e = zin.getNextEntry()) != null) {
- if (e.isDirectory())
- continue;
- if (e.getName().endsWith(".class")) {
- loadClass(zin);
- } else {
- loadResource(e.getName(), zin);
- }
- VerboseLoader.setState("Downloading: " + e.getName());
- }
- zin.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- VerboseLoader.get().onProgressUpdate(100);
- }
+ /**
+ * Adds a jar to this classpath
+ *
+ * @param url - in string format
+ */
+ public void addJar(final String url) {
+ try {
+ addJar(new URL(url));
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ }
+ /**
+ * Whether jar files should be parsed or ignored
+ *
+ * @param enabled
+ */
+ public void parseJarFiles(final boolean enabled) {
+ this.parseJar = enabled;
+ }
+ /**
+ * Finds and loads all classes/jar files in folder
+ *
+ * @param directory
+ */
+ public void addClasses(final File directory) {
+ if (directory == null || !directory.isDirectory()) {
+ throw new IllegalArgumentException("Not a valid directory.");
+ }
+ addClasses(directory, null);
+ }
- /**
- * Adds a jar to this classpath
- *
- * @param url
- * - in string format
- */
- public void addJar(final String url) {
- try {
- addJar(new URL(url));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Finds and loads all classes/jar files in folder
+ *
+ * @param f to find class / jar files
+ * @param root
+ */
+ public void addClasses(final File f, File root) {
+ if (f == null) {
+ return;
+ }
+ if (!f.exists()) {
+ f.mkdirs();
+ }
+ if (root == null) {
+ root = f;
+ }
+ for (File f1 : f.listFiles()) {
+ if (f1 == null) {
+ continue;
+ } else if (f1.isDirectory()) {
+ addClasses(f1, root);
+ } else {
+ try (FileInputStream fin = new FileInputStream(f1)) {
+ if (f1.getName().endsWith(".class")) {
+ loadClass(fin);
+ } else if (f.equals(root) && f1.getName().endsWith(".jar")) {
+ jarFiles.add(f1.toURI().toURL());
+ if (this.parseJar) {
+ // if enabled, there may be problem with duplicate
+ // class names.......
+ addJar(f1.toURI().toURL());
+ }
+ } else {
+ String path = f1.toURI().relativize(root.toURI())
+ .getPath();
+ loadResource(path, fin);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
- /**
- * Whether jar files should be parsed or ignored
- *
- * @param enabled
- */
- public void parseJarFiles(final boolean enabled) {
- this.parseJar = enabled;
- }
-
- /**
- * Finds and loads all classes/jar files in folder
- * @param directory
- */
- public void addClasses(final File directory) {
- if(directory == null || !directory.isDirectory()) {
- throw new IllegalArgumentException("Not a valid directory.");
- }
- addClasses(directory, null);
- }
-
- /**
- * Finds and loads all classes/jar files in folder
- *
- * @param f
- * to find class / jar files
- * @param root
- */
- public void addClasses(final File f, File root) {
- if (f == null)
- return;
- if (!f.exists()) {
- f.mkdirs();
- }
- if (root == null) {
- root = f;
- }
- for (File f1 : f.listFiles()) {
- if (f1 == null) {
- continue;
- } else if (f1.isDirectory()) {
- addClasses(f1, root);
- } else {
- try (FileInputStream fin = new FileInputStream(f1)) {
- if (f1.getName().endsWith(".class"))
- loadClass(fin);
- else if (f.equals(root) && f1.getName().endsWith(".jar")) {
- jarFiles.add(f1.toURI().toURL());
- if (this.parseJar) {
- // if enabled, there may be problem with duplicate
- // class names.......
- addJar(f1.toURI().toURL());
- }
- } else {
- String path = f1.toURI().relativize(root.toURI())
- .getPath();
- loadResource(path, fin);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- /**
- * Loads class from input stream
- *
- * @param in
- * @throws IOException
+ /**
+ * Loads class from input stream
+ *
+ * @param in
+ *
+ * @throws IOException
*/
protected void loadClass(InputStream in) throws IOException {
- ClassReader cr = new ClassReader(in);
- ClassNode cn = new ClassNode();
- RemappingClassAdapter rca = new RemappingClassAdapter(cn,classRemapper);
- RedirectClassAdapter redir = new RedirectClassAdapter(rca);
+ ClassReader cr = new ClassReader(in);
+ ClassNode cn = new ClassNode();
+ RemappingClassAdapter rca = new RemappingClassAdapter(cn, classRemapper);
+ RedirectClassAdapter redir = new RedirectClassAdapter(rca);
cr.accept(redir, ClassReader.EXPAND_FRAMES);
classNames.add(cn.name.replace('/', '.'));
classes.put(cn.name, cn);
}
+ /**
+ * Determines if this classpath represents a jar file
+ *
+ * @return if this classpath represents a jar file
+ */
+ public boolean isJar() {
+ return isJar;
+ }
+ /**
+ * Gets all jar files in this classpath
+ *
+ * @return array of classpath
+ */
+ public ClassPath[] getJarFiles() {
+ final ClassPath[] jars = new ClassPath[jarFiles.size()];
+ for (int i = 0; i < jarFiles.size(); i++) {
+ final ClassPath classPath = new ClassPath(true);
+ classPath.addJar(jarFiles.get(i));
+ jars[i] = classPath;
+ }
+ return jars;
+ }
- /**
- * Determines if this classpath represents a jar file
- *
- * @return if this classpath represents a jar file
- */
- public boolean isJar() {
- return isJar;
- }
+ /**
+ * Dumps a resource from a input stream
+ *
+ * @param classPath
+ * @param name
+ * @param inputstream
+ *
+ * @throws IOException
+ */
+ private void loadResource(final String name, final InputStream in)
+ throws IOException {
+ final File f = File.createTempFile("bot", ".tmp",
+ Directories.getTempDirectory());
+ f.deleteOnExit();
+ try (OutputStream out = new FileOutputStream(f)) {
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = in.read(buffer)) != -1) {
+ out.write(buffer, 0, len);
+ }
+ } catch (IOException e) {
+ }
+ this.resources.put(name, f);
+ }
- /**
- * Gets all jar files in this classpath
- *
- * @return array of classpath
- */
- public ClassPath[] getJarFiles() {
- final ClassPath[] jars = new ClassPath[jarFiles.size()];
- for (int i = 0; i < jarFiles.size(); i++) {
- final ClassPath classPath = new ClassPath(true);
- classPath.addJar(jarFiles.get(i));
- jars[i] = classPath;
- }
- return jars;
- }
+ /**
+ * Adds this jar to buildpath
+ */
+ public void addToBuildPath() {
+ BuildPath.add(lastParsed);
+ }
- /**
- * Dumps a resource from a input stream
- *
- * @param classPath
- * @param name
- * @param inputstream
- * @throws IOException
- */
- private void loadResource(final String name, final InputStream in)
- throws IOException {
- final File f = File.createTempFile("bot", ".tmp",
- Directories.getTempDirectory());
- f.deleteOnExit();
- try (OutputStream out = new FileOutputStream(f)) {
- byte[] buffer = new byte[1024];
- int len;
- while ((len = in.read(buffer)) != -1)
- out.write(buffer, 0, len);
- } catch (IOException e) {
- }
- this.resources.put(name, f);
- }
+ /**
+ * Dump this classPath classes to a jar file
+ *
+ * @param fileName
+ */
+ public void dump(final String fileName) {
+ dump(new File(fileName));
+ }
- /**
- * Adds this jar to buildpath
- */
- public void addToBuildPath() {
- BuildPath.add(lastParsed);
- }
+ /**
+ * Dump this classPath classes to a jar file
+ *
+ * @param file
+ */
+ public void dump(final File file) {
+ try {
+ dump(new FileOutputStream(file));
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
- /**
- * Dump this classPath classes to a jar file
- *
- * @param fileName
- */
- public void dump(final String fileName) {
- dump(new File(fileName));
- }
-
- /**
- * Dump this classPath classes to a jar file
- *
- * @param file
- */
- public void dump(final File file) {
- try {
- dump(new FileOutputStream(file));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Dumps this classPath classes to a jar file
- * @param stream
- */
- public void dump(final FileOutputStream stream) {
- try {
- JarOutputStream out = new JarOutputStream(stream);
- for (ClassNode cn : this.classes.values()) {
- JarEntry je = new JarEntry(cn.name + ".class");
- out.putNextEntry(je);
- ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- cn.accept(cw);
- out.write(cw.toByteArray());
- }
- for(Entry entry : this.resources.entrySet()) {
- JarEntry je = new JarEntry(entry.getKey());
- out.putNextEntry(je);
- out.write(Files.readAllBytes(entry.getValue().toPath()));
- }
- out.close();
- stream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Dumps this classPath classes to a jar file
+ *
+ * @param stream
+ */
+ public void dump(final FileOutputStream stream) {
+ try {
+ JarOutputStream out = new JarOutputStream(stream);
+ for (ClassNode cn : this.classes.values()) {
+ JarEntry je = new JarEntry(cn.name + ".class");
+ out.putNextEntry(je);
+ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+ cn.accept(cw);
+ out.write(cw.toByteArray());
+ }
+ for (Entry entry : this.resources.entrySet()) {
+ JarEntry je = new JarEntry(entry.getKey());
+ out.putNextEntry(je);
+ out.write(Files.readAllBytes(entry.getValue().toPath()));
+ }
+ out.close();
+ stream.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/desc/ScriptDescription.java b/src/main/java/org/parabot/core/desc/ScriptDescription.java
index 1c05bed..4719edb 100644
--- a/src/main/java/org/parabot/core/desc/ScriptDescription.java
+++ b/src/main/java/org/parabot/core/desc/ScriptDescription.java
@@ -2,135 +2,134 @@ package org.parabot.core.desc;
/**
* Holds information about a script
- *
+ *
* @author Everel
- *
*/
public class ScriptDescription implements Comparable {
- public String scriptName;
- public String author;
- public String category;
- public double version;
- public String description;
- public String[] servers;
- public String isVip;
- public String isPremium;
- public int bdnId;
+ public String scriptName;
+ public String author;
+ public String category;
+ public double version;
+ public String description;
+ public String[] servers;
+ public String isVip;
+ public String isPremium;
+ public int bdnId;
/**
- * The ScriptManifest
- *
- * @param scriptName
- * @param author
- * @param category
- * @param version
- * @param description
- * @param servers
- */
- public ScriptDescription(final String scriptName, final String author,
- final String category, final double version,
- final String description, final String[] servers) {
- this(scriptName, author, category, version, description, servers, null,
- null, -1);
- }
-
- /**
- * Used for BDN script (see BDNScripts parser)
- *
- * @param scriptName
- * @param author
- * @param category
- * @param version
- * @param description
- * @param servers
- * @param bdnId
- */
- public ScriptDescription(final String scriptName,
- final String author, final String category, final double version,
- final String description, final String[] servers, final int bdnId) {
- this(scriptName, author, category, version, description, servers, null,
- null, bdnId);
- }
-
- /**
- * Used by bot (java scripts and python scripts) and BDN Manager (bdn
- * manager is a private program)
- *
- * @param scriptName
- * @param author
- * @param category
- * @param version
- * @param description
- * @param servers
- * @param vip
- * @param premium
- */
- public ScriptDescription(final String scriptName, final String author,
- final String category, final double version,
- final String description, final String[] servers, final String vip,
- final String premium) {
- this(scriptName, author, category, version, description, servers, vip,
- premium, -1);
- }
-
- /**
- * Main constructor
- *
- * @param scriptName
- * @param author
- * @param category
- * @param version
- * @param description
- * @param servers
- * @param vip
- * @param premium
- * @param bdnId
- */
- public ScriptDescription(final String scriptName, final String author,
- final String category, final double version,
- final String description, final String[] servers, final String vip,
- final String premium, final int bdnId) {
- this.scriptName = scriptName;
- this.author = author;
- this.category = category;
- this.version = version;
- this.description = description;
- this.servers = servers;
- this.isVip = vip;
- this.isPremium = premium;
- this.bdnId = bdnId;
+ * The ScriptManifest
+ *
+ * @param scriptName
+ * @param author
+ * @param category
+ * @param version
+ * @param description
+ * @param servers
+ */
+ public ScriptDescription(final String scriptName, final String author,
+ final String category, final double version,
+ final String description, final String[] servers) {
+ this(scriptName, author, category, version, description, servers, null,
+ null, -1);
}
- @Override
- public String toString() {
- final StringBuilder b = new StringBuilder();
- b.append("[name: ").append(this.scriptName).append(", author: ")
- .append(this.author).append(", category: ")
- .append(this.category).append(", version: ")
- .append(this.version).append(", description: ")
- .append(this.description).append(", servers: ");
- if(this.servers != null) {
- for (int i = 0; i < this.servers.length; i++) {
- b.append(this.servers[i]);
- if (i < (this.servers.length - 1)) {
- b.append(" ");
- }
- }
- }
- b.append(", vip: ")
- .append(this.isVip == null ? "unknown" : this.isVip)
- .append(", premium: ")
- .append(this.isPremium == null ? "unknown" : this.isPremium)
- .append(", bdn id: ")
- .append(this.bdnId == -1 ? "unknown" : Integer
- .toString(this.bdnId))
- .append("]");
+ /**
+ * Used for BDN script (see BDNScripts parser)
+ *
+ * @param scriptName
+ * @param author
+ * @param category
+ * @param version
+ * @param description
+ * @param servers
+ * @param bdnId
+ */
+ public ScriptDescription(final String scriptName,
+ final String author, final String category, final double version,
+ final String description, final String[] servers, final int bdnId) {
+ this(scriptName, author, category, version, description, servers, null,
+ null, bdnId);
+ }
- return b.toString();
- }
+ /**
+ * Used by bot (java scripts and python scripts) and BDN Manager (bdn
+ * manager is a private program)
+ *
+ * @param scriptName
+ * @param author
+ * @param category
+ * @param version
+ * @param description
+ * @param servers
+ * @param vip
+ * @param premium
+ */
+ public ScriptDescription(final String scriptName, final String author,
+ final String category, final double version,
+ final String description, final String[] servers, final String vip,
+ final String premium) {
+ this(scriptName, author, category, version, description, servers, vip,
+ premium, -1);
+ }
- @Override
- public int compareTo(ScriptDescription o) {
- return scriptName.compareTo(o.scriptName);
- }
+ /**
+ * Main constructor
+ *
+ * @param scriptName
+ * @param author
+ * @param category
+ * @param version
+ * @param description
+ * @param servers
+ * @param vip
+ * @param premium
+ * @param bdnId
+ */
+ public ScriptDescription(final String scriptName, final String author,
+ final String category, final double version,
+ final String description, final String[] servers, final String vip,
+ final String premium, final int bdnId) {
+ this.scriptName = scriptName;
+ this.author = author;
+ this.category = category;
+ this.version = version;
+ this.description = description;
+ this.servers = servers;
+ this.isVip = vip;
+ this.isPremium = premium;
+ this.bdnId = bdnId;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder b = new StringBuilder();
+ b.append("[name: ").append(this.scriptName).append(", author: ")
+ .append(this.author).append(", category: ")
+ .append(this.category).append(", version: ")
+ .append(this.version).append(", description: ")
+ .append(this.description).append(", servers: ");
+ if (this.servers != null) {
+ for (int i = 0; i < this.servers.length; i++) {
+ b.append(this.servers[i]);
+ if (i < (this.servers.length - 1)) {
+ b.append(" ");
+ }
+ }
+ }
+ b.append(", vip: ")
+ .append(this.isVip == null ? "unknown" : this.isVip)
+ .append(", premium: ")
+ .append(this.isPremium == null ? "unknown" : this.isPremium)
+ .append(", bdn id: ")
+ .append(this.bdnId == -1 ? "unknown" : Integer
+ .toString(this.bdnId))
+ .append("]");
+
+ return b.toString();
+ }
+
+ @Override
+ public int compareTo(ScriptDescription o) {
+ return scriptName.compareTo(o.scriptName);
+ }
}
diff --git a/src/main/java/org/parabot/core/desc/ServerDescription.java b/src/main/java/org/parabot/core/desc/ServerDescription.java
index cfcc369..687410c 100644
--- a/src/main/java/org/parabot/core/desc/ServerDescription.java
+++ b/src/main/java/org/parabot/core/desc/ServerDescription.java
@@ -1,45 +1,43 @@
package org.parabot.core.desc;
/**
- *
* Holds information about a server
- *
+ *
* @author Everel
- *
*/
public class ServerDescription implements Comparable {
- private String serverName;
- private String author;
- private double revision;
+ private String serverName;
+ private String author;
+ private double revision;
- public ServerDescription(final String serverName, final String author,
- final double revision) {
- this.serverName = serverName;
- this.author = author;
- this.revision = revision;
- }
+ public ServerDescription(final String serverName, final String author,
+ final double revision) {
+ this.serverName = serverName;
+ this.author = author;
+ this.revision = revision;
+ }
- public String getServerName() {
- return this.serverName;
- }
+ public String getServerName() {
+ return this.serverName;
+ }
- public String getAuthor() {
- return this.author;
- }
+ public String getAuthor() {
+ return this.author;
+ }
- public double getRevision() {
- return this.revision;
- }
+ public double getRevision() {
+ return this.revision;
+ }
- @Override
- public String toString() {
- return String.format("[Server: %s, Author: %s, Revision: %.2f]",
- this.serverName, this.author, this.revision);
- }
+ @Override
+ public String toString() {
+ return String.format("[Server: %s, Author: %s, Revision: %.2f]",
+ this.serverName, this.author, this.revision);
+ }
- @Override
- public int compareTo(ServerDescription o) {
- return this.getServerName().compareTo(o.getServerName());
- }
+ @Override
+ public int compareTo(ServerDescription o) {
+ return this.getServerName().compareTo(o.getServerName());
+ }
}
diff --git a/src/main/java/org/parabot/core/desc/ServerProviderInfo.java b/src/main/java/org/parabot/core/desc/ServerProviderInfo.java
index ba20206..4172151 100644
--- a/src/main/java/org/parabot/core/desc/ServerProviderInfo.java
+++ b/src/main/java/org/parabot/core/desc/ServerProviderInfo.java
@@ -1,14 +1,11 @@
package org.parabot.core.desc;
import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.parabot.core.Configuration;
import org.parabot.core.Core;
-import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.WebUtil;
-import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -22,92 +19,91 @@ import java.util.zip.CRC32;
* Gets the information for the selected server provider
*
* @author Paradox, Everel
- *
*/
public class ServerProviderInfo {
- private HashMap settings;
- private Properties properties;
-
- public ServerProviderInfo(URL providerInfo, String username, String password) {
- this.properties = new Properties();
- this.settings = new HashMap<>();
+ private HashMap settings;
+ private Properties properties;
+
+ public ServerProviderInfo(URL providerInfo, String username, String password) {
+ this.properties = new Properties();
+ this.settings = new HashMap<>();
try {
Core.verbose("Reading info: " + providerInfo);
BufferedReader br = WebUtil.getReader(new URL(providerInfo.toString()), username, password);
- JSONObject jsonObject = (JSONObject) WebUtil.getJsonParser().parse(br);
- for (Object o : jsonObject.entrySet()) {
- Map.Entry, ?> pairs = (Map.Entry, ?>) o;
- if (String.valueOf(pairs.getKey()).equalsIgnoreCase("settings")){
- JSONObject object = (JSONObject) pairs.getValue();
- parseSettings(object);
- }else {
- properties.put(String.valueOf(pairs.getKey()), String.valueOf(pairs.getValue()));
- }
- }
- if (br != null) {
- br.close();
- }
- } catch (Exception e) {
+ JSONObject jsonObject = (JSONObject) WebUtil.getJsonParser().parse(br);
+ for (Object o : jsonObject.entrySet()) {
+ Map.Entry, ?> pairs = (Map.Entry, ?>) o;
+ if (String.valueOf(pairs.getKey()).equalsIgnoreCase("settings")) {
+ JSONObject object = (JSONObject) pairs.getValue();
+ parseSettings(object);
+ } else {
+ properties.put(String.valueOf(pairs.getKey()), String.valueOf(pairs.getValue()));
+ }
+ }
+ if (br != null) {
+ br.close();
+ }
+ } catch (Exception e) {
e.printStackTrace();
}
}
- public ServerProviderInfo(String clientJar, String hooks, String name, String clientClass, int bankTabs){
- this.properties = new Properties();
- this.settings = new HashMap<>();
+ public ServerProviderInfo(String clientJar, String hooks, String name, String clientClass, int bankTabs) {
+ this.properties = new Properties();
+ this.settings = new HashMap<>();
- try {
- BufferedReader br = WebUtil.getReader(new URL(Configuration.GET_SERVER_SETTINGS));
- JSONObject settings = (JSONObject) WebUtil.getJsonParser().parse(br);
- parseSettings(settings);
- } catch (ParseException | IOException e) {
- e.printStackTrace();
- }
+ try {
+ BufferedReader br = WebUtil.getReader(new URL(Configuration.GET_SERVER_SETTINGS));
+ JSONObject settings = (JSONObject) WebUtil.getJsonParser().parse(br);
+ parseSettings(settings);
+ } catch (ParseException | IOException e) {
+ e.printStackTrace();
+ }
- this.properties.setProperty("client_jar", clientJar);
- this.properties.setProperty("hooks", hooks);
- this.properties.setProperty("name", name);
- this.properties.setProperty("client_class", clientClass);
- this.properties.setProperty("provider_crc32", String.valueOf(getCRC32(name, "provider")));
- this.properties.setProperty("client_crc32", String.valueOf(getCRC32(name, "client")));
- this.properties.setProperty("bank_tabs", String.valueOf(bankTabs));
- }
+ this.properties.setProperty("client_jar", clientJar);
+ this.properties.setProperty("hooks", hooks);
+ this.properties.setProperty("name", name);
+ this.properties.setProperty("client_class", clientClass);
+ this.properties.setProperty("provider_crc32", String.valueOf(getCRC32(name, "provider")));
+ this.properties.setProperty("client_crc32", String.valueOf(getCRC32(name, "client")));
+ this.properties.setProperty("bank_tabs", String.valueOf(bankTabs));
+ }
- private long getCRC32(String name, String type){
- CRC32 crc = new CRC32();
- name += "-" + type;
- crc.update(name.getBytes());
- return crc.getValue();
- }
+ private long getCRC32(String name, String type) {
+ CRC32 crc = new CRC32();
+ name += "-" + type;
+ crc.update(name.getBytes());
+ return crc.getValue();
+ }
- private void parseSettings(JSONObject object){
- for (Object settingObject : object.entrySet()){
- Map.Entry, ?> settingValue = (Map.Entry, ?>) settingObject;
- String key = (String) settingValue.getKey();
- long value = (Long) settingValue.getValue();
- settings.put(key, (int) value);
- }
- }
-
- public URL getClient() {
- try {
- return new URL(properties.getProperty("client_jar"));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- public URL getExtendedHookFile() {
- try {
- return new URL(properties.getProperty("hooks") /*+ "&extended=true"*/);
- } catch (MalformedURLException e) {
- e.printStackTrace();
+ private void parseSettings(JSONObject object) {
+ for (Object settingObject : object.entrySet()) {
+ Map.Entry, ?> settingValue = (Map.Entry, ?>) settingObject;
+ String key = (String) settingValue.getKey();
+ long value = (Long) settingValue.getValue();
+ settings.put(key, (int) value);
+ }
+ }
+
+ public URL getClient() {
+ try {
+ return new URL(properties.getProperty("client_jar"));
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public URL getExtendedHookFile() {
+ try {
+ return new URL(properties.getProperty("hooks") /*+ "&extended=true"*/);
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
return getHookFile();
- }
- }
+ }
+ }
public URL getHookFile() {
try {
@@ -117,32 +113,32 @@ public class ServerProviderInfo {
}
return null;
}
-
- public String getClientClass() {
- return properties.getProperty("client_class");
- }
-
- public String getServerName() {
- return properties.getProperty("name");
- }
-
- public long getCRC32() {
- return Long.parseLong(properties.getProperty("provider_crc32"));
- }
-
- public long getClientCRC32() {
- return Long.parseLong(properties.getProperty("client_crc32"));
- }
-
- public int getBankTabs() {
- return Integer.parseInt(properties.getProperty("bank_tabs"));
- }
-
- public Properties getProperties() {
- return this.properties;
- }
- public HashMap getSettings() {
- return settings;
- }
+ public String getClientClass() {
+ return properties.getProperty("client_class");
+ }
+
+ public String getServerName() {
+ return properties.getProperty("name");
+ }
+
+ public long getCRC32() {
+ return Long.parseLong(properties.getProperty("provider_crc32"));
+ }
+
+ public long getClientCRC32() {
+ return Long.parseLong(properties.getProperty("client_crc32"));
+ }
+
+ public int getBankTabs() {
+ return Integer.parseInt(properties.getProperty("bank_tabs"));
+ }
+
+ public Properties getProperties() {
+ return this.properties;
+ }
+
+ public HashMap getSettings() {
+ return settings;
+ }
}
diff --git a/src/main/java/org/parabot/core/forum/Account.java b/src/main/java/org/parabot/core/forum/Account.java
index f2b2a1a..0185e1a 100644
--- a/src/main/java/org/parabot/core/forum/Account.java
+++ b/src/main/java/org/parabot/core/forum/Account.java
@@ -1,33 +1,28 @@
package org.parabot.core.forum;
-import org.parabot.core.Core;
-
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
- *
* Class which holds parabot forum account user and pass, only specific classes
* have access to it unless it's a modified version of parabot intended to
* steal user information.
- *
+ *
* @author Everel
- *
*/
public class Account {
- private String username;
- private String password;
+ private String username;
+ private String password;
private String api;
- /**
- *
- * @param username - Forum account username
- * @param password - Forum account password
- */
- public Account(final String username, final String password) {
- this.username = username;
- this.password = password;
- }
+ /**
+ * @param username - Forum account username
+ * @param password - Forum account password
+ */
+ public Account(final String username, final String password) {
+ this.username = username;
+ this.password = password;
+ }
public Account(String username, String password, String api) {
this.username = username;
@@ -36,26 +31,29 @@ public class Account {
}
/**
- * Gets user's parabot account name
- * @return username.
- */
- public String getUsername() {
- return this.username;
- }
-
- /**
- * Gets user's parabot password
- * @return password.
- */
- public String getPassword() {
- return this.password;
- }
+ * Gets user's parabot account name
+ *
+ * @return username.
+ */
+ public String getUsername() {
+ return this.username;
+ }
+
+ /**
+ * Gets user's parabot password
+ *
+ * @return password.
+ */
+ public String getPassword() {
+ return this.password;
+ }
/**
* Gets user's parabot account name
+ *
* @return username, already URL UTF-8 encoded.
*/
- public String getURLUsername(){
+ public String getURLUsername() {
try {
return URLEncoder.encode(this.username, "UTF-8");
} catch (UnsupportedEncodingException e) {
@@ -66,9 +64,10 @@ public class Account {
/**
* Gets user's password
+ *
* @return password, already URL UTF-8 encoded.
*/
- public String getURLPassword(){
+ public String getURLPassword() {
try {
return URLEncoder.encode(this.password, "UTF-8");
} catch (UnsupportedEncodingException e) {
diff --git a/src/main/java/org/parabot/core/forum/AccountManager.java b/src/main/java/org/parabot/core/forum/AccountManager.java
index a848863..6b729a5 100644
--- a/src/main/java/org/parabot/core/forum/AccountManager.java
+++ b/src/main/java/org/parabot/core/forum/AccountManager.java
@@ -20,99 +20,98 @@ import java.util.ArrayList;
/**
* Handles logging in to parabot forum, only certain classes may use this class.
- *
+ *
* @author Everel
- *
*/
public final class AccountManager {
- private static boolean validated;
- private static AccountManager instance;
+ private static boolean validated;
+ private static AccountManager instance;
- private Account account;
+ private Account account;
- private AccountManager() {
+ private AccountManager() {
- }
+ }
- public static final void validate() {
- if (validated) {
- return;
- }
- validated = true;
- instance = new AccountManager();
+ public static final void validate() {
+ if (validated) {
+ return;
+ }
+ validated = true;
+ instance = new AccountManager();
- Core.verbose("Initializing account manager accessors...");
- final ArrayList accessors = new ArrayList();
- accessors.add(BDNScripts.MANAGER_FETCHER);
- accessors.add(VerboseLoader.MANAGER_FETCHER);
- accessors.add(BDNScriptsExecuter.MANAGER_FETCHER);
- accessors.add(PublicServers.MANAGER_FETCHER);
- accessors.add(PublicServerExecuter.MANAGER_FETCHER);
- accessors.add(PBPreferences.MANAGER_FETCHER);
+ Core.verbose("Initializing account manager accessors...");
+ final ArrayList accessors = new ArrayList();
+ accessors.add(BDNScripts.MANAGER_FETCHER);
+ accessors.add(VerboseLoader.MANAGER_FETCHER);
+ accessors.add(BDNScriptsExecuter.MANAGER_FETCHER);
+ accessors.add(PublicServers.MANAGER_FETCHER);
+ accessors.add(PublicServerExecuter.MANAGER_FETCHER);
+ accessors.add(PBPreferences.MANAGER_FETCHER);
- for (final AccountManagerAccess accessor : accessors) {
- accessor.setManager(instance);
- }
- Core.verbose("Account managers initialized.");
- }
-
- public final boolean isLoggedIn() {
- return account != null;
- }
-
- public final Account getAccount() {
- return account;
- }
+ for (final AccountManagerAccess accessor : accessors) {
+ accessor.setManager(instance);
+ }
+ Core.verbose("Account managers initialized.");
+ }
- public final boolean login(final String user, final String pass, boolean requestTwoStep) {
- if (account != null) {
- throw new IllegalStateException("Already logged in.");
- }
- JSONObject result = null;
- if (!requestTwoStep){
- try {
- BufferedReader contents = WebUtil.getReader(WebUtil.getConnection(
- new URL(Configuration.LOGIN_SERVER),
- URLEncoder.encode(user, "UTF-8"),
- URLEncoder.encode(pass, "UTF-8")));
+ public final boolean isLoggedIn() {
+ return account != null;
+ }
- result = (JSONObject) WebUtil.getJsonParser().parse(contents);
+ public final Account getAccount() {
+ return account;
+ }
- } catch (Throwable t) {
- t.printStackTrace();
- return false;
- }
- }else{
- try {
- String two = JOptionPane.showInputDialog("Please provide your two factor authentication code\nYou can find this in either your email or the app you've setup");
- if (two != null && two.length() > 0) {
- String contents = WebUtil.getContents(Configuration.LOGIN_SERVER,
- "username=" + URLEncoder.encode(user, "UTF-8") + "&password=" + URLEncoder.encode(pass, "UTF-8") + "&2fa=" + URLEncoder.encode(two, "UTF-8")
- );
- result = (JSONObject) WebUtil.getJsonParser().parse(contents);
- }
- } catch (Throwable t) {
- t.printStackTrace();
- return false;
- }
- }
+ public final boolean login(final String user, final String pass, boolean requestTwoStep) {
+ if (account != null) {
+ throw new IllegalStateException("Already logged in.");
+ }
+ JSONObject result = null;
+ if (!requestTwoStep) {
+ try {
+ BufferedReader contents = WebUtil.getReader(WebUtil.getConnection(
+ new URL(Configuration.LOGIN_SERVER),
+ URLEncoder.encode(user, "UTF-8"),
+ URLEncoder.encode(pass, "UTF-8")));
- if (result != null) {
- if (result.get("complete") != null) {
- String api = (String) ((JSONObject) result.get("data")).get("api");
- account = new Account(user, pass, api);
- Context.setUsername(user);
- return true;
- } else if (result.get("error") != null) {
- String errorResult = (String) result.get("error");
- if (errorResult.equals("2fa") || errorResult.equals("2fae")) {
- return login(user, pass, true);
- }
- Core.verbose(errorResult);
- return false;
- }
- }
- return false;
- }
+ result = (JSONObject) WebUtil.getJsonParser().parse(contents);
+
+ } catch (Throwable t) {
+ t.printStackTrace();
+ return false;
+ }
+ } else {
+ try {
+ String two = JOptionPane.showInputDialog("Please provide your two factor authentication code\nYou can find this in either your email or the app you've setup");
+ if (two != null && two.length() > 0) {
+ String contents = WebUtil.getContents(Configuration.LOGIN_SERVER,
+ "username=" + URLEncoder.encode(user, "UTF-8") + "&password=" + URLEncoder.encode(pass, "UTF-8") + "&2fa=" + URLEncoder.encode(two, "UTF-8")
+ );
+ result = (JSONObject) WebUtil.getJsonParser().parse(contents);
+ }
+ } catch (Throwable t) {
+ t.printStackTrace();
+ return false;
+ }
+ }
+
+ if (result != null) {
+ if (result.get("complete") != null) {
+ String api = (String) ((JSONObject) result.get("data")).get("api");
+ account = new Account(user, pass, api);
+ Context.setUsername(user);
+ return true;
+ } else if (result.get("error") != null) {
+ String errorResult = (String) result.get("error");
+ if (errorResult.equals("2fa") || errorResult.equals("2fae")) {
+ return login(user, pass, true);
+ }
+ Core.verbose(errorResult);
+ return false;
+ }
+ }
+ return false;
+ }
}
diff --git a/src/main/java/org/parabot/core/forum/AccountManagerAccess.java b/src/main/java/org/parabot/core/forum/AccountManagerAccess.java
index 262b068..5ca37f8 100644
--- a/src/main/java/org/parabot/core/forum/AccountManagerAccess.java
+++ b/src/main/java/org/parabot/core/forum/AccountManagerAccess.java
@@ -1,14 +1,12 @@
package org.parabot.core.forum;
/**
- *
* Gives access to account details
- *
- * @author Everel
*
+ * @author Everel
*/
public interface AccountManagerAccess {
-
- public void setManager(AccountManager manager);
+
+ public void setManager(AccountManager manager);
}
diff --git a/src/main/java/org/parabot/core/io/ProgressListener.java b/src/main/java/org/parabot/core/io/ProgressListener.java
index 4d0992a..8be607d 100644
--- a/src/main/java/org/parabot/core/io/ProgressListener.java
+++ b/src/main/java/org/parabot/core/io/ProgressListener.java
@@ -1,12 +1,10 @@
package org.parabot.core.io;
/**
- *
* Keeps track of a progress
- *
- * @author Everel
*
+ * @author Everel
*/
-public interface ProgressListener extends org.parabot.api.io.ProgressListener{
+public interface ProgressListener extends org.parabot.api.io.ProgressListener {
}
diff --git a/src/main/java/org/parabot/core/io/SizeInputStream.java b/src/main/java/org/parabot/core/io/SizeInputStream.java
index d0fad56..4897b40 100644
--- a/src/main/java/org/parabot/core/io/SizeInputStream.java
+++ b/src/main/java/org/parabot/core/io/SizeInputStream.java
@@ -4,61 +4,59 @@ import java.io.IOException;
import java.io.InputStream;
/**
- *
* @author Everel
- *
*/
public class SizeInputStream extends InputStream {
- public int bytesRead;
- private ProgressListener l;
- private InputStream in;
- private long startTime;
- private double size;
+ public int bytesRead;
+ private ProgressListener l;
+ private InputStream in;
+ private long startTime;
+ private double size;
- public SizeInputStream(InputStream in, int size, ProgressListener l) {
- this.in = in;
- this.size = size;
- this.l = l;
- this.startTime = System.currentTimeMillis();
- }
+ public SizeInputStream(InputStream in, int size, ProgressListener l) {
+ this.in = in;
+ this.size = size;
+ this.l = l;
+ this.startTime = System.currentTimeMillis();
+ }
- public int available() {
- return ((int) size - bytesRead);
- }
+ public int available() {
+ return ((int) size - bytesRead);
+ }
- public int read() throws IOException {
- int b = in.read();
- if (b != -1) {
- bytesRead++;
- }
- updateListener();
- return b;
- }
+ public int read() throws IOException {
+ int b = in.read();
+ if (b != -1) {
+ bytesRead++;
+ }
+ updateListener();
+ return b;
+ }
- public int read(byte[] b) throws IOException {
- int read = in.read(b);
- bytesRead += read;
- updateListener();
- return read;
- }
+ public int read(byte[] b) throws IOException {
+ int read = in.read(b);
+ bytesRead += read;
+ updateListener();
+ return read;
+ }
- public int read(byte[] b, int off, int len) throws IOException {
- int read = in.read(b, off, len);
- bytesRead += read;
- updateListener();
- return read;
- }
-
- private void updateListener() {
- if(l != null) {
- double percent = ( bytesRead / size) * 100.0D;
- l.onProgressUpdate(percent);
-
- long curTime = System.currentTimeMillis();
- double timeSeconds = (curTime - startTime) / 1000.0D;
- double speed = bytesRead / (1024.0D * 1024.0D) / timeSeconds;
- l.updateDownloadSpeed(speed);
- }
- }
+ public int read(byte[] b, int off, int len) throws IOException {
+ int read = in.read(b, off, len);
+ bytesRead += read;
+ updateListener();
+ return read;
+ }
+
+ private void updateListener() {
+ if (l != null) {
+ double percent = (bytesRead / size) * 100.0D;
+ l.onProgressUpdate(percent);
+
+ long curTime = System.currentTimeMillis();
+ double timeSeconds = (curTime - startTime) / 1000.0D;
+ double speed = bytesRead / (1024.0D * 1024.0D) / timeSeconds;
+ l.updateDownloadSpeed(speed);
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/lib/Library.java b/src/main/java/org/parabot/core/lib/Library.java
index c8a7645..869b144 100644
--- a/src/main/java/org/parabot/core/lib/Library.java
+++ b/src/main/java/org/parabot/core/lib/Library.java
@@ -1,9 +1,7 @@
package org.parabot.core.lib;
/**
- *
* @author Everel
- *
*/
public abstract class Library extends org.parabot.api.io.libraries.Library {
diff --git a/src/main/java/org/parabot/core/lib/javafx/JavaFX.java b/src/main/java/org/parabot/core/lib/javafx/JavaFX.java
index 5684e45..43efd00 100644
--- a/src/main/java/org/parabot/core/lib/javafx/JavaFX.java
+++ b/src/main/java/org/parabot/core/lib/javafx/JavaFX.java
@@ -1,76 +1,74 @@
package org.parabot.core.lib.javafx;
-import java.io.File;
-import java.net.URL;
-
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.lib.Library;
import org.parabot.environment.api.utils.JavaUtil;
+import java.io.File;
+import java.net.URL;
+
/**
- *
* Jython util class
- *
+ *
* @author Everel
- *
*/
public class JavaFX extends Library {
- private static boolean valid;
+ private static boolean valid;
- @Override
- public void init() {
- if (!hasJar()) {
- System.err.println("Failed to load javafx... [jar missing]");
- return;
- }
- Core.verbose("Adding javafx jar file to build path: "
- + getJarFileURL().getPath());
- BuildPath.add(getJarFileURL());
+ public static boolean isValid() {
+ return valid;
+ }
- try {
- Class.forName("javafx.application.Application");
- valid = true;
- } catch (ClassNotFoundException e) {
- System.err
- .println("Failed to add javafx to build path, or incorrupt download");
- }
+ @Override
+ public void init() {
+ if (!hasJar()) {
+ System.err.println("Failed to load javafx... [jar missing]");
+ return;
+ }
+ Core.verbose("Adding javafx jar file to build path: "
+ + getJarFileURL().getPath());
+ BuildPath.add(getJarFileURL());
- Core.verbose("JavaFX initialized.");
- }
+ try {
+ Class.forName("javafx.application.Application");
+ valid = true;
+ } catch (ClassNotFoundException e) {
+ System.err
+ .println("Failed to add javafx to build path, or incorrupt download");
+ }
- @Override
- public boolean isAdded() {
- return valid;
- }
+ Core.verbose("JavaFX initialized.");
+ }
- @Override
- public File getJarFile() {
- return new File(Directories.getCachePath(), "javafx.jar");
- }
+ @Override
+ public boolean isAdded() {
+ return valid;
+ }
- @Override
- public URL getDownloadLink() {
- try {
- return new URL("http://bot.parabot.org/libs/jfxrt.jar");
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ @Override
+ public File getJarFile() {
+ return new File(Directories.getCachePath(), "javafx.jar");
+ }
- @Override
- public boolean requiresJar() {
- return JavaUtil.JAVA_VERSION <= 1.7;
- }
+ @Override
+ public URL getDownloadLink() {
+ try {
+ return new URL("http://bot.parabot.org/libs/jfxrt.jar");
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- @Override
- public String getLibraryName() {
- return "JavaFX";
- }
-
- public static boolean isValid() {
- return valid;
- }
+ @Override
+ public boolean requiresJar() {
+ return JavaUtil.JAVA_VERSION <= 1.7;
+ }
+
+ @Override
+ public String getLibraryName() {
+ return "JavaFX";
+ }
}
diff --git a/src/main/java/org/parabot/core/network/NetworkInterface.java b/src/main/java/org/parabot/core/network/NetworkInterface.java
index b1d3a78..4a8daf5 100644
--- a/src/main/java/org/parabot/core/network/NetworkInterface.java
+++ b/src/main/java/org/parabot/core/network/NetworkInterface.java
@@ -7,71 +7,75 @@ import java.util.Enumeration;
import java.util.NoSuchElementException;
public class NetworkInterface {
- public static byte[] mac = new byte[] { 11, 11, 11, 11, 11, 11 };
- private static byte[] realMac;
- private static NetworkInterface cached;
+ public static byte[] mac = new byte[]{ 11, 11, 11, 11, 11, 11 };
+ private static byte[] realMac;
+ private static NetworkInterface cached;
- static {
- try {
- mac = getRealHardwareAddress();
- } catch (SocketException ignored) {
- }
- }
+ static {
+ try {
+ mac = getRealHardwareAddress();
+ } catch (SocketException ignored) {
+ }
+ }
- public byte[] getHardwareAddress() {
- return mac;
- }
+ public static Enumeration getNetworkInterfaces()
+ throws SocketException {
+ final ArrayList netifs = new ArrayList<>();
- public static Enumeration getNetworkInterfaces()
- throws SocketException {
- final ArrayList netifs = new ArrayList<>();
+ return new Enumeration() {
+ private int i = 0;
- return new Enumeration() {
- private int i = 0;
- public NetworkInterface nextElement() {
- if (i < netifs.size()) {
- NetworkInterface netif = netifs.get(i++);
- return netif;
- } else {
- throw new NoSuchElementException();
- }
- }
+ public NetworkInterface nextElement() {
+ if (i < netifs.size()) {
+ NetworkInterface netif = netifs.get(i++);
+ return netif;
+ } else {
+ throw new NoSuchElementException();
+ }
+ }
- public boolean hasMoreElements() {
- return (i < netifs.size());
- }
- };
- }
+ public boolean hasMoreElements() {
+ return (i < netifs.size());
+ }
+ };
+ }
- public static byte[] getRealHardwareAddress() throws SocketException{
- if (realMac != null)
- return realMac;
- try {
- return realMac = java.net.NetworkInterface.getByInetAddress(
- InetAddress.getLocalHost()).getHardwareAddress();
- } catch (Exception ignored) {
- }
- return mac;
- }
+ public static byte[] getRealHardwareAddress() throws SocketException {
+ if (realMac != null) {
+ return realMac;
+ }
+ try {
+ return realMac = java.net.NetworkInterface.getByInetAddress(
+ InetAddress.getLocalHost()).getHardwareAddress();
+ } catch (Exception ignored) {
+ }
+ return mac;
+ }
- public static NetworkInterface getByInetAddress(InetAddress addr) {
- if (cached == null)
- cached = new NetworkInterface();
- return cached;
- }
+ public static NetworkInterface getByInetAddress(InetAddress addr) {
+ if (cached == null) {
+ cached = new NetworkInterface();
+ }
+ return cached;
+ }
- public static void setMac(byte[] mac2) {
- System.out.println("Setting mac address to: " + formatMac(mac2));
- mac = mac2;
- }
+ public static void setMac(byte[] mac2) {
+ System.out.println("Setting mac address to: " + formatMac(mac2));
+ mac = mac2;
+ }
- public static String formatMac(byte[] mac){
- StringBuilder b = new StringBuilder();
- for(int i = 0; i < 6;i++){
- b.append(String.format("%02X", mac[i]));
- if(i < 5)
- b.append(':');
- }
- return b.toString();
- }
+ public static String formatMac(byte[] mac) {
+ StringBuilder b = new StringBuilder();
+ for (int i = 0; i < 6; i++) {
+ b.append(String.format("%02X", mac[i]));
+ if (i < 5) {
+ b.append(':');
+ }
+ }
+ return b.toString();
+ }
+
+ public byte[] getHardwareAddress() {
+ return mac;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/network/Runtime.java b/src/main/java/org/parabot/core/network/Runtime.java
index 8c5930f..501575e 100644
--- a/src/main/java/org/parabot/core/network/Runtime.java
+++ b/src/main/java/org/parabot/core/network/Runtime.java
@@ -3,64 +3,63 @@ package org.parabot.core.network;
import java.io.IOException;
public class Runtime {
-
- private java.lang.Runtime rt;
-
- private static Runtime cached;
-
- private Runtime(java.lang.Runtime rt){
- this.rt = rt;
- }
-
-
- public void addShutdownHook(Thread t){
- rt.addShutdownHook(t);
- }
-
- public int availableProcessors(){
- return rt.availableProcessors();
- }
-
- public void exit(int i){
- rt.exit(i);
- }
-
- public Process exec(String str) throws IOException{
- System.out.println("RT:" + str);
- System.out.println("RT:" + str);
- return rt.exec(str);
- }
-
- public Process exec(String[] cmdarray) throws IOException{
- StringBuffer sb = new StringBuffer();
- for(int i = 0; i < cmdarray.length;i++){
- sb.append(cmdarray[i] + (i < cmdarray.length - 1 ? "," : ""));
- }
- System.out.println("RT: {" + sb + "}");
- System.out.println("RT: {" + sb + "}");
- return rt.exec(cmdarray);
- }
-
- public long freeMemory() {
- return rt.freeMemory();
- }
-
- public long totalMemory() {
- return rt.totalMemory();
- }
-
- public void gc(){
- rt.gc();
- }
-
- public long maxMemory(){
- return rt.maxMemory();
- }
-
- public static Runtime getRuntime(){
- if(cached == null)
- cached = new Runtime(java.lang.Runtime.getRuntime());
- return cached;
- }
+
+ private static Runtime cached;
+ private java.lang.Runtime rt;
+
+ private Runtime(java.lang.Runtime rt) {
+ this.rt = rt;
+ }
+
+ public static Runtime getRuntime() {
+ if (cached == null) {
+ cached = new Runtime(java.lang.Runtime.getRuntime());
+ }
+ return cached;
+ }
+
+ public void addShutdownHook(Thread t) {
+ rt.addShutdownHook(t);
+ }
+
+ public int availableProcessors() {
+ return rt.availableProcessors();
+ }
+
+ public void exit(int i) {
+ rt.exit(i);
+ }
+
+ public Process exec(String str) throws IOException {
+ System.out.println("RT:" + str);
+ System.out.println("RT:" + str);
+ return rt.exec(str);
+ }
+
+ public Process exec(String[] cmdarray) throws IOException {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < cmdarray.length; i++) {
+ sb.append(cmdarray[i] + (i < cmdarray.length - 1 ? "," : ""));
+ }
+ System.out.println("RT: {" + sb + "}");
+ System.out.println("RT: {" + sb + "}");
+ return rt.exec(cmdarray);
+ }
+
+ public long freeMemory() {
+ return rt.freeMemory();
+ }
+
+ public long totalMemory() {
+ return rt.totalMemory();
+ }
+
+ public void gc() {
+ rt.gc();
+ }
+
+ public long maxMemory() {
+ return rt.maxMemory();
+ }
}
diff --git a/src/main/java/org/parabot/core/network/proxy/ProxySocket.java b/src/main/java/org/parabot/core/network/proxy/ProxySocket.java
index 6082890..46b7454 100644
--- a/src/main/java/org/parabot/core/network/proxy/ProxySocket.java
+++ b/src/main/java/org/parabot/core/network/proxy/ProxySocket.java
@@ -11,284 +11,299 @@ import java.util.List;
public class ProxySocket extends Socket {
- private static List connections = new ArrayList();
+ public static boolean auth = false;
+ private static List connections = new ArrayList();
+ private static ProxyType proxyType = ProxyType.NONE;
+ private static int proxyPort = 0;
+ private static String username = null, password = null;
+ private static InetAddress proxyInetAddress = null;
+ private InetAddress addr;
+ private int port;
+ private InetSocketAddress cachedAddr;
- private static ProxyType proxyType = ProxyType.NONE;
+ public ProxySocket(InetAddress addr, int port) throws IOException {
+ super(addr, port);
+ }
- private static int proxyPort = 0;
+ public ProxySocket() {
+ super();
+ }
- private InetAddress addr;
- private int port;
+ public ProxySocket(String host, int port) throws IOException {
+ super(host, port);
+ }
- private static String username = null, password = null;
+ public static int closeConnections() {
+ int value = 0;
+ for (ProxySocket socket : connections) {
+ try {
+ connections.remove(socket);
+ if (socket.isClosed()) {
+ continue;
+ }
+ socket.close();
+ value++;
+ } catch (Exception e) {
- public static boolean auth = false;
+ }
+ }
+ return value;
+ }
- private static InetAddress proxyInetAddress = null;
+ public static void setProxy(ProxyType type, String host, int port) {
+ try {
+ proxyInetAddress = InetAddress.getByName(host);
+ proxyPort = port;
+ proxyType = type;
+ } catch (UnknownHostException e) {
+ throw new RuntimeException(e);
+ }
+ }
- private InetSocketAddress cachedAddr;
+ public static InetAddress getProxyAddress() {
+ return proxyInetAddress;
+ }
- public static int closeConnections() {
- int value = 0;
- for (ProxySocket socket : connections)
- try {
- connections.remove(socket);
- if (socket.isClosed())
- continue;
- socket.close();
- value++;
- } catch (Exception e) {
+ public static int getProxyPort() {
+ return proxyPort;
+ }
- }
- return value;
- }
+ public static ProxyType getProxyType() {
+ return proxyType;
+ }
- public ProxySocket(InetAddress addr, int port) throws IOException {
- super(addr, port);
- }
+ public static void setType(ProxyType pt) {
+ proxyType = pt;
+ }
- public ProxySocket() {
- super();
- }
+ public static int getConnectionCount() {
+ return connections.size();
+ }
- public ProxySocket(String host, int port) throws IOException {
- super(host, port);
- }
+ public static void setLogin(String user, char[] pass) {
+ setLogin(user, new String(pass));
+ }
- public static void setProxy(ProxyType type, String host, int port) {
- try {
- proxyInetAddress = InetAddress.getByName(host);
- proxyPort = port;
- proxyType = type;
- } catch (UnknownHostException e) {
- throw new RuntimeException(e);
- }
- }
+ public static void setLogin(String user, String pass) {
+ username = user;
+ password = pass;
+ }
- public static InetAddress getProxyAddress() {
- return proxyInetAddress;
- }
+ @Override
+ public void connect(SocketAddress addr) throws IOException {
+ connections.add(this);
+ if (addr instanceof InetSocketAddress) {
+ InetSocketAddress isa = (InetSocketAddress) addr;
+ this.addr = InetAddress.getByName(isa.getHostString());
+ this.port = isa.getPort();
+ }
+ if (proxyType != ProxyType.NONE) {
+ try {
+ super.connect(cachedAddr = new InetSocketAddress(
+ proxyInetAddress, proxyPort));
+ initProxy();
+ } catch (Exception e) {
+ UILog.log("Proxy Error", e.getMessage(),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ } else {
+ super.connect(addr);
+ }
+ }
- public static int getProxyPort() {
- return proxyPort;
- }
+ private void initProxy() throws IOException {
+ System.out.println("Proxying:" + addr + ":" + port + " Over:"
+ + proxyInetAddress + ":" + proxyPort + " Type:" + proxyType);
+ switch (proxyType) {
+ case HTTP:
+ http_connect();
+ break;
+ case SOCKS4:
+ socks4_connect();
+ break;
+ case SOCKS5:
+ socks5_connect();
+ break;
+ default:
+ throw new IOException("Unsupported proxy type:" + proxyType);
+ }
+ }
- public static ProxyType getProxyType() {
- return proxyType;
- }
+ private void http_connect() throws IOException {
+ InputStream in = getInputStream();
+ BufferedReader br = new BufferedReader(new InputStreamReader(in));
+ OutputStream out = getOutputStream();
+ out.write(("CONNECT " + addr.getHostAddress() + ":" + port + "\r\n")
+ .getBytes());
+ // out.write("Connection:keep-alive\r\n".getBytes());
+ out.write("\r\n".getBytes());
+ String str;
+ while ((str = br.readLine()) != null) {
+ if (str.length() == 0) {
+ break;
+ }
+ if (!str.startsWith("HTTP")) {
+ continue;
+ }
+ int code = Integer.parseInt(str.substring(9, 12));
+ switch (code) {
+ case 404:
+ throw new IOException(
+ "Proxy seems to think we're connecting to a webpage...");
+ case 403:
+ throw new IOException(
+ "Proxy doesn't support connecting to port: " + port
+ + "! Try a different proxy.");
+ }
+ if (code / 100 != 2) {
+ throw new IOException(
+ "Unable to connect to proxy server! HTTP Error code:"
+ + code);
+ }
+ }
+ }
- @Override
- public void connect(SocketAddress addr) throws IOException {
- connections.add(this);
- if (addr instanceof InetSocketAddress) {
- InetSocketAddress isa = (InetSocketAddress) addr;
- this.addr = InetAddress.getByName(isa.getHostString());
- this.port = isa.getPort();
- }
- if (proxyType != ProxyType.NONE) {
- try {
- super.connect(cachedAddr = new InetSocketAddress(
- proxyInetAddress, proxyPort));
- initProxy();
- } catch (Exception e) {
- UILog.log("Proxy Error", e.getMessage(),
- JOptionPane.ERROR_MESSAGE);
- }
- } else
- super.connect(addr);
- }
+ private void socks4_connect() throws IOException {
+ DataOutputStream out = new DataOutputStream(getOutputStream());
+ DataInputStream in = new DataInputStream(getInputStream());
- private void initProxy() throws IOException {
- System.out.println("Proxying:" + addr + ":" + port + " Over:"
- + proxyInetAddress + ":" + proxyPort + " Type:" + proxyType);
- switch (proxyType) {
- case HTTP:
- http_connect();
- break;
- case SOCKS4:
- socks4_connect();
- break;
- case SOCKS5:
- socks5_connect();
- break;
- default:
- throw new IOException("Unsupported proxy type:" + proxyType);
- }
- }
+ out.write(0x04);
+ out.write(0x01); // connection type (TCP stream)
+ out.writeShort(port);
+ byte[] b = addr.getAddress();
+ if (b.length != 4) {
+ throw new IOException("Unsupported IP type for socksv4!");
+ }
+ out.write(b);
+ out.write(0); // the userID stuff, 0 means end of string (null
+ // terminated)
+ out.flush();
- private void http_connect() throws IOException {
- InputStream in = getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(in));
- OutputStream out = getOutputStream();
- out.write(("CONNECT " + addr.getHostAddress() + ":" + port + "\r\n")
- .getBytes());
- // out.write("Connection:keep-alive\r\n".getBytes());
- out.write("\r\n".getBytes());
- String str;
- while ((str = br.readLine()) != null) {
- if (str.length() == 0)
- break;
- if (!str.startsWith("HTTP"))
- continue;
- int code = Integer.parseInt(str.substring(9, 12));
- switch (code) {
- case 404:
- throw new IOException(
- "Proxy seems to think we're connecting to a webpage...");
- case 403:
- throw new IOException(
- "Proxy doesn't support connecting to port: " + port
- + "! Try a different proxy.");
- }
- if (code / 100 != 2)
- throw new IOException(
- "Unable to connect to proxy server! HTTP Error code:"
- + code);
- }
- }
+ if (in.read() != 0x00) // null byte
+ {
+ throw new IOException("Proxy server dun goofed");
+ }
+ if (in.read() != 0x5a) {
+ throw new IOException(
+ "Proxy server was unable to connect to server!");
+ }
- private void socks4_connect() throws IOException {
- DataOutputStream out = new DataOutputStream(getOutputStream());
- DataInputStream in = new DataInputStream(getInputStream());
+ in.readShort(); // ignored
+ in.readFully(b); // ignored
+ }
- out.write(0x04);
- out.write(0x01); // connection type (TCP stream)
- out.writeShort(port);
- byte[] b = addr.getAddress();
- if (b.length != 4)
- throw new IOException("Unsupported IP type for socksv4!");
- out.write(b);
- out.write(0); // the userID stuff, 0 means end of string (null
- // terminated)
- out.flush();
+ private void socks5_connect() throws IOException {
+ DataOutputStream out = new DataOutputStream(getOutputStream());
+ DataInputStream in = new DataInputStream(getInputStream());
+ out.write(0x05); // the version
+ out.write(auth ? 2 : 1); // number of authentication methods (no auth
+ // for now)
+ out.write(0); // the authentication (none)
+ if (auth) {
+ out.write(2);
+ }
+ out.flush();
+ if (in.read() != 0x05) // remote proxy version
+ {
+ throw new IOException("Proxy server is not supported!");
+ }
+ switch (in.read()) { // auth method
+ case 0:
+ break; // no auth
+ case 2:
+ // username and pass stuff
+ out.write(0x01); // user/pass version #
+ out.write(username.length());
+ out.write(username.getBytes());
+ out.write(password.length());
+ out.write(password.getBytes());
+ out.flush();
+ in.read(); // skip the version
+ if (in.read() == 0) // Successful login, continue
+ {
+ break;
+ }
+ default:
+ throw new IOException("Proxy server declined request!");
+ }
- if (in.read() != 0x00) // null byte
- throw new IOException("Proxy server dun goofed");
- if (in.read() != 0x5a)
- throw new IOException(
- "Proxy server was unable to connect to server!");
+ // now to write the actual request
+ out.write(0x05); // again the socks version
+ out.write(0x01); // the connection type (0x01 = TCP Connection)
+ out.write(0x00); // the reserve byte, un-used
+ byte[] b = addr.getAddress();
+ out.write(b.length == 4 ? 0x01 : 0x04); // if ipv4 or ipv6 (0x03 =
+ // domain name, but that's
+ // unsupported as of yet)
+ out.write(b);
+ out.writeShort(port);
+ out.flush();
- in.readShort(); // ignored
- in.readFully(b); // ignored
- }
+ // now to read the server's reply
+ if (in.read() != 0x05) // socks version (again)
+ {
+ throw new IOException("Proxy server dun goofed");
+ }
+ int reply = in.read();
+ if (reply == 0x08) {
+ throw new IOException("Bad address sent to proxy server");
+ }
+ if (reply != 0x00) {
+ throw new IOException("Unable to connect to server!");
+ }
+ in.read(); // reserve byte
+ int addrType = in.read();
+ b = new byte[4];
+ switch (addrType) {
+ case 0x01:
+ b = new byte[4];
+ break;
+ case 0x04:
+ b = new byte[16];
+ break;
+ default:
+ throw new IOException("Bad address type from proxy server!");
+ }
+ in.readFully(b);
+ in.readShort(); // the returned port #, ignored
+ }
- private void socks5_connect() throws IOException {
- DataOutputStream out = new DataOutputStream(getOutputStream());
- DataInputStream in = new DataInputStream(getInputStream());
- out.write(0x05); // the version
- out.write(auth ? 2 : 1); // number of authentication methods (no auth
- // for now)
- out.write(0); // the authentication (none)
- if (auth) {
- out.write(2);
- }
- out.flush();
- if (in.read() != 0x05) // remote proxy version
- throw new IOException("Proxy server is not supported!");
- switch (in.read()) { // auth method
- case 0:
- break; // no auth
- case 2:
- // username and pass stuff
- out.write(0x01); // user/pass version #
- out.write(username.length());
- out.write(username.getBytes());
- out.write(password.length());
- out.write(password.getBytes());
- out.flush();
- in.read(); // skip the version
- if (in.read() == 0) // Successful login, continue
- break;
- default:
- throw new IOException("Proxy server declined request!");
- }
+ @Override
+ public int getPort() {
+ if (super.getInetAddress().equals(proxyInetAddress)) {
+ return port;
+ }
+ return super.getPort();
+ }
- // now to write the actual request
- out.write(0x05); // again the socks version
- out.write(0x01); // the connection type (0x01 = TCP Connection)
- out.write(0x00); // the reserve byte, un-used
- byte[] b = addr.getAddress();
- out.write(b.length == 4 ? 0x01 : 0x04); // if ipv4 or ipv6 (0x03 =
- // domain name, but that's
- // unsupported as of yet)
- out.write(b);
- out.writeShort(port);
- out.flush();
+ @Override
+ public InetAddress getInetAddress() {
+ if (super.getInetAddress().equals(proxyInetAddress)) {
+ return addr;
+ }
+ return super.getInetAddress();
+ }
- // now to read the server's reply
- if (in.read() != 0x05) // socks version (again)
- throw new IOException("Proxy server dun goofed");
- int reply = in.read();
- if (reply == 0x08)
- throw new IOException("Bad address sent to proxy server");
- if (reply != 0x00)
- throw new IOException("Unable to connect to server!");
- in.read(); // reserve byte
- int addrType = in.read();
- b = new byte[4];
- switch (addrType) {
- case 0x01:
- b = new byte[4];
- break;
- case 0x04:
- b = new byte[16];
- break;
- default:
- throw new IOException("Bad address type from proxy server!");
- }
- in.readFully(b);
- in.readShort(); // the returned port #, ignored
- }
+ @Override
+ public SocketAddress getRemoteSocketAddress() {
+ if (super.getInetAddress().equals(proxyInetAddress)) {
+ return cachedAddr;
+ }
+ return super.getRemoteSocketAddress();
+ }
- @Override
- public int getPort() {
- if (super.getInetAddress().equals(proxyInetAddress))
- return port;
- return super.getPort();
- }
+ @Override
+ public SocketChannel getChannel() {
+ if (super.getInetAddress().equals(proxyInetAddress)) {
+ return null;
+ }
+ return super.getChannel();
+ }
- @Override
- public InetAddress getInetAddress() {
- if (super.getInetAddress().equals(proxyInetAddress))
- return addr;
- return super.getInetAddress();
- }
-
- @Override
- public SocketAddress getRemoteSocketAddress() {
- if (super.getInetAddress().equals(proxyInetAddress))
- return cachedAddr;
- return super.getRemoteSocketAddress();
- }
-
- @Override
- public SocketChannel getChannel() {
- if (super.getInetAddress().equals(proxyInetAddress))
- return null;
- return super.getChannel();
- }
-
- @Override
- public void close() throws IOException {
- connections.remove(this);
- super.close();
- }
-
- public static void setType(ProxyType pt) {
- proxyType = pt;
- }
-
- public static int getConnectionCount() {
- return connections.size();
- }
-
- public static void setLogin(String user, char[] pass) {
- setLogin(user, new String(pass));
- }
-
- public static void setLogin(String user, String pass) {
- username = user;
- password = pass;
- }
+ @Override
+ public void close() throws IOException {
+ connections.remove(this);
+ super.close();
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/network/proxy/ProxyType.java b/src/main/java/org/parabot/core/network/proxy/ProxyType.java
index cf365ee..ab7b866 100644
--- a/src/main/java/org/parabot/core/network/proxy/ProxyType.java
+++ b/src/main/java/org/parabot/core/network/proxy/ProxyType.java
@@ -1,5 +1,5 @@
package org.parabot.core.network.proxy;
public enum ProxyType {
- NONE,SOCKS5, SOCKS4, HTTP
+ NONE, SOCKS5, SOCKS4, HTTP
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/paint/AbstractDebugger.java b/src/main/java/org/parabot/core/paint/AbstractDebugger.java
index 98e26a2..e2276f2 100644
--- a/src/main/java/org/parabot/core/paint/AbstractDebugger.java
+++ b/src/main/java/org/parabot/core/paint/AbstractDebugger.java
@@ -3,23 +3,20 @@ package org.parabot.core.paint;
import org.parabot.environment.api.interfaces.Paintable;
/**
- *
* Abstract class for debugging in game values & more
- *
- * @author Everel
*
+ * @author Everel
*/
public abstract class AbstractDebugger implements Paintable {
-
- /**
- * Toggles this debugger
- */
- public abstract void toggle();
- /**
- *
- * @return True if this debugger is enabled, otherwise false
+ /**
+ * Toggles this debugger
*/
- public abstract boolean isEnabled();
+ public abstract void toggle();
+
+ /**
+ * @return True if this debugger is enabled, otherwise false
+ */
+ public abstract boolean isEnabled();
}
diff --git a/src/main/java/org/parabot/core/paint/PaintDebugger.java b/src/main/java/org/parabot/core/paint/PaintDebugger.java
index 4b8c7fd..1026933 100644
--- a/src/main/java/org/parabot/core/paint/PaintDebugger.java
+++ b/src/main/java/org/parabot/core/paint/PaintDebugger.java
@@ -1,61 +1,58 @@
package org.parabot.core.paint;
-import java.awt.Color;
-import java.awt.Graphics;
+import org.parabot.core.Context;
+
+import java.awt.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
-import org.parabot.core.Context;
-
/**
- *
* Manages and paints on a collection of AbstractDebuggers
- *
- * @author Everel
*
+ * @author Everel
*/
public class PaintDebugger {
- private final HashMap debuggers;
- private final Queue stringDebug;
-
- public PaintDebugger() {
- this.debuggers = new HashMap();
- this.stringDebug = new LinkedList();
- }
-
- public final void addDebugger(final String name, final AbstractDebugger debugger) {
- debuggers.put(name, debugger);
- }
-
- public void debug(Graphics g) {
- for(final AbstractDebugger d : debuggers.values()) {
- if(d.isEnabled()) {
- d.paint(g);
- }
- }
- g.setColor(Color.green);
- int y = 40;
- while(stringDebug.size() > 0) {
- g.drawString(stringDebug.poll(), 10, y);
- y += 15;
- }
- }
-
- public static final PaintDebugger getInstance() {
- return Context.getInstance().getPaintDebugger();
- }
-
- public final void addLine(final String debugLine) {
- stringDebug.add(debugLine);
- }
-
- public final void toggle(final String name) {
- debuggers.get(name).toggle();
- }
-
- public final boolean isEnabled(final String name) {
- return debuggers.get(name).isEnabled();
- }
+ private final HashMap debuggers;
+ private final Queue stringDebug;
+
+ public PaintDebugger() {
+ this.debuggers = new HashMap();
+ this.stringDebug = new LinkedList();
+ }
+
+ public static final PaintDebugger getInstance() {
+ return Context.getInstance().getPaintDebugger();
+ }
+
+ public final void addDebugger(final String name, final AbstractDebugger debugger) {
+ debuggers.put(name, debugger);
+ }
+
+ public void debug(Graphics g) {
+ for (final AbstractDebugger d : debuggers.values()) {
+ if (d.isEnabled()) {
+ d.paint(g);
+ }
+ }
+ g.setColor(Color.green);
+ int y = 40;
+ while (stringDebug.size() > 0) {
+ g.drawString(stringDebug.poll(), 10, y);
+ y += 15;
+ }
+ }
+
+ public final void addLine(final String debugLine) {
+ stringDebug.add(debugLine);
+ }
+
+ public final void toggle(final String name) {
+ debuggers.get(name).toggle();
+ }
+
+ public final boolean isEnabled(final String name) {
+ return debuggers.get(name).isEnabled();
+ }
}
diff --git a/src/main/java/org/parabot/core/parsers/hooks/HookParser.java b/src/main/java/org/parabot/core/parsers/hooks/HookParser.java
index 3de98b0..03d8292 100644
--- a/src/main/java/org/parabot/core/parsers/hooks/HookParser.java
+++ b/src/main/java/org/parabot/core/parsers/hooks/HookParser.java
@@ -3,6 +3,7 @@ package org.parabot.core.parsers.hooks;
import org.parabot.core.asm.hooks.HookFile;
import org.parabot.core.asm.interfaces.Injectable;
import org.parabot.core.asm.wrappers.*;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -15,9 +16,8 @@ import java.util.HashMap;
*/
public abstract class HookParser {
-
public HookParser(HookFile hookFile) {
-
+
}
public abstract Interface[] getInterfaces();
@@ -25,18 +25,18 @@ public abstract class HookParser {
public abstract Super[] getSupers();
public abstract Getter[] getGetters();
-
+
public abstract Setter[] getSetters();
public abstract Invoker[] getInvokers();
public abstract Callback[] getCallbacks();
-
+
public abstract HashMap getConstants();
public Injectable[] getInjectables() {
ArrayList injectables = new ArrayList();
- Interface[] interfaces = getInterfaces();
+ Interface[] interfaces = getInterfaces();
if (interfaces != null) {
Collections.addAll(injectables, interfaces);
}
diff --git a/src/main/java/org/parabot/core/parsers/hooks/JSONHookParser.java b/src/main/java/org/parabot/core/parsers/hooks/JSONHookParser.java
index 0ff8598..2a230a0 100644
--- a/src/main/java/org/parabot/core/parsers/hooks/JSONHookParser.java
+++ b/src/main/java/org/parabot/core/parsers/hooks/JSONHookParser.java
@@ -1,248 +1,241 @@
package org.parabot.core.parsers.hooks;
-import java.io.InputStreamReader;
-import java.util.HashMap;
-import java.util.Map;
-
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.parabot.core.asm.adapters.AddInterfaceAdapter;
import org.parabot.core.asm.hooks.HookFile;
-import org.parabot.core.asm.wrappers.Callback;
-import org.parabot.core.asm.wrappers.Getter;
-import org.parabot.core.asm.wrappers.Interface;
-import org.parabot.core.asm.wrappers.Invoker;
-import org.parabot.core.asm.wrappers.Setter;
-import org.parabot.core.asm.wrappers.Super;
+import org.parabot.core.asm.wrappers.*;
+
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.Map;
/**
- *
* @author Dane
- *
*/
public class JSONHookParser extends HookParser {
- private JSONObject root;
- private Map interfaces;
- private HashMap constants;
+ private JSONObject root;
+ private Map interfaces;
+ private HashMap constants;
- public JSONHookParser(HookFile file) {
- super(file);
+ public JSONHookParser(HookFile file) {
+ super(file);
- JSONParser parser = new JSONParser();
+ JSONParser parser = new JSONParser();
- try {
- parser.parse(new InputStreamReader(file.getInputStream()));
- } catch (Throwable t) {
- throw new RuntimeException("Unable to parse hooks: " + t);
- }
- }
+ try {
+ parser.parse(new InputStreamReader(file.getInputStream()));
+ } catch (Throwable t) {
+ throw new RuntimeException("Unable to parse hooks: " + t);
+ }
+ }
- public String get(JSONObject o, String s) {
- return this.get(o, s);
- }
+ public String get(JSONObject o, String s) {
+ return this.get(o, s);
+ }
- public String formatDescription(String s) {
- StringBuilder b = new StringBuilder();
+ public String formatDescription(String s) {
+ StringBuilder b = new StringBuilder();
- if (s.charAt(0) == '[') {
- for (int j = 0; j < s.length(); j++) {
- if (s.charAt(j) == '[') {
- b.append('[');
- }
- }
- s = s.replaceAll("\\[", "");
- }
+ if (s.charAt(0) == '[') {
+ for (int j = 0; j < s.length(); j++) {
+ if (s.charAt(j) == '[') {
+ b.append('[');
+ }
+ }
+ s = s.replaceAll("\\[", "");
+ }
- return b.append('L').append(String.format(s, AddInterfaceAdapter.getAccessorPackage())).append(';').toString();
- }
+ return b.append('L').append(String.format(s, AddInterfaceAdapter.getAccessorPackage())).append(';').toString();
+ }
- @Override
- public Interface[] getInterfaces() {
- JSONArray a = (JSONArray) root.get("interfaces");
- interfaces = new HashMap<>();
+ @Override
+ public Interface[] getInterfaces() {
+ JSONArray a = (JSONArray) root.get("interfaces");
+ interfaces = new HashMap<>();
- if (a != null && a.size() > 0) {
- Interface[] i = new Interface[a.size()];
- for (int j = 0; j < a.size(); j++) {
- JSONObject o = (JSONObject) a.get(j);
+ if (a != null && a.size() > 0) {
+ Interface[] i = new Interface[a.size()];
+ for (int j = 0; j < a.size(); j++) {
+ JSONObject o = (JSONObject) a.get(j);
- String clazz = this.get(o, "class");
- String interfaze = this.get(o, "interface");
+ String clazz = this.get(o, "class");
+ String interfaze = this.get(o, "interface");
- interfaces.put(clazz, interfaze);
- i[j] = new Interface(clazz, interfaze);
- }
- return i;
- }
- return null;
- }
+ interfaces.put(clazz, interfaze);
+ i[j] = new Interface(clazz, interfaze);
+ }
+ return i;
+ }
+ return null;
+ }
- @Override
- public Super[] getSupers() {
- JSONArray a = (JSONArray) root.get("supers");
+ @Override
+ public Super[] getSupers() {
+ JSONArray a = (JSONArray) root.get("supers");
- if (a != null && a.size() > 0) {
- Super[] s = new Super[a.size()];
- for (int i = 0; i < a.size(); i++) {
- JSONObject o = (JSONObject) a.get(i);
- s[i] = new Super(this.get(o, "class"), this.get(o, "super"));
- }
- return s;
- }
- return null;
- }
+ if (a != null && a.size() > 0) {
+ Super[] s = new Super[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ JSONObject o = (JSONObject) a.get(i);
+ s[i] = new Super(this.get(o, "class"), this.get(o, "super"));
+ }
+ return s;
+ }
+ return null;
+ }
- @Override
- public Getter[] getGetters() {
- JSONArray a = (JSONArray) root.get("getters");
+ @Override
+ public Getter[] getGetters() {
+ JSONArray a = (JSONArray) root.get("getters");
- if (a != null && a.size() > 0) {
- Getter[] g = new Getter[a.size()];
- for (int i = 0; i < a.size(); i++) {
- JSONObject o = (JSONObject) a.get(i);
+ if (a != null && a.size() > 0) {
+ Getter[] g = new Getter[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ JSONObject o = (JSONObject) a.get(i);
- if (o.containsKey("class") && o.containsKey("accessor")) {
- throw new RuntimeException("Cannot have class AND accessor tags together!");
- }
+ if (o.containsKey("class") && o.containsKey("accessor")) {
+ throw new RuntimeException("Cannot have class AND accessor tags together!");
+ }
- if (o.containsKey("accessor") && this.interfaces == null) {
- throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
- }
+ if (o.containsKey("accessor") && this.interfaces == null) {
+ throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
+ }
- String desc = this.get(o, "desc");
+ String desc = this.get(o, "desc");
- if (desc != null && desc.contains("%s")) {
- desc = formatDescription(desc);
- }
+ if (desc != null && desc.contains("%s")) {
+ desc = formatDescription(desc);
+ }
- String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
- String into = o.containsKey("into") ? this.get(o, "into") : clazz;
+ String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
+ String into = o.containsKey("into") ? this.get(o, "into") : clazz;
- g[i] = new Getter(into, clazz, this.get(o, "field"), this.get(o, "method"), desc, o.containsKey("static") ? (boolean) o.get("static") : false, 0, null);
- }
- return g;
- }
- return null;
- }
+ g[i] = new Getter(into, clazz, this.get(o, "field"), this.get(o, "method"), desc, o.containsKey("static") ? (boolean) o.get("static") : false, 0, null);
+ }
+ return g;
+ }
+ return null;
+ }
- @Override
- public Setter[] getSetters() {
- JSONArray a = (JSONArray) root.get("setters");
+ @Override
+ public Setter[] getSetters() {
+ JSONArray a = (JSONArray) root.get("setters");
- if (a != null && a.size() > 0) {
- Setter[] s = new Setter[a.size()];
- for (int i = 0; i < a.size(); i++) {
- JSONObject o = (JSONObject) a.get(i);
+ if (a != null && a.size() > 0) {
+ Setter[] s = new Setter[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ JSONObject o = (JSONObject) a.get(i);
- if (o.containsKey("class") && o.containsKey("accessor")) {
- throw new RuntimeException("Cannot have class AND accessor tags together!");
- }
+ if (o.containsKey("class") && o.containsKey("accessor")) {
+ throw new RuntimeException("Cannot have class AND accessor tags together!");
+ }
- if (o.containsKey("accessor") && this.interfaces == null) {
- throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
- }
+ if (o.containsKey("accessor") && this.interfaces == null) {
+ throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
+ }
- String desc = this.get(o, "desc");
+ String desc = this.get(o, "desc");
- if (desc != null && desc.contains("%s")) {
- desc = formatDescription(desc);
- }
+ if (desc != null && desc.contains("%s")) {
+ desc = formatDescription(desc);
+ }
- String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
- String into = o.containsKey("into") ? this.get(o, "into") : clazz;
+ String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
+ String into = o.containsKey("into") ? this.get(o, "into") : clazz;
- s[i] = new Setter(into, clazz, this.get(o, "field"), this.get(o, "method"), desc, o.containsKey("static") ? (boolean) o.get("static") : false, null);
- }
- return s;
- }
- return null;
- }
+ s[i] = new Setter(into, clazz, this.get(o, "field"), this.get(o, "method"), desc, o.containsKey("static") ? (boolean) o.get("static") : false, null);
+ }
+ return s;
+ }
+ return null;
+ }
- @Override
- public Invoker[] getInvokers() {
- JSONArray a = (JSONArray) root.get("invokers");
+ @Override
+ public Invoker[] getInvokers() {
+ JSONArray a = (JSONArray) root.get("invokers");
- if (a != null && a.size() > 0) {
- Invoker[] i = new Invoker[a.size()];
- for (int j = 0; j < a.size(); j++) {
- JSONObject o = (JSONObject) a.get(j);
+ if (a != null && a.size() > 0) {
+ Invoker[] i = new Invoker[a.size()];
+ for (int j = 0; j < a.size(); j++) {
+ JSONObject o = (JSONObject) a.get(j);
- if (o.containsKey("class") && o.containsKey("accessor")) {
- throw new RuntimeException("Cannot have class AND accessor tags together!");
- }
+ if (o.containsKey("class") && o.containsKey("accessor")) {
+ throw new RuntimeException("Cannot have class AND accessor tags together!");
+ }
- if (o.containsKey("accessor") && this.interfaces == null) {
- throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
- }
+ if (o.containsKey("accessor") && this.interfaces == null) {
+ throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
+ }
- String desc = this.get(o, "desc");
+ String desc = this.get(o, "desc");
- if (desc != null && desc.contains("%s")) {
- desc = formatDescription(desc);
- }
+ if (desc != null && desc.contains("%s")) {
+ desc = formatDescription(desc);
+ }
- String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
- String into = o.containsKey("into") ? this.get(o, "into") : clazz;
+ String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
+ String into = o.containsKey("into") ? this.get(o, "into") : clazz;
- i[j] = new Invoker(into, clazz, this.get(o, "invokemethod"), this.get(o, "argdesc"), this.get(o, "desc"), this.get(o, "method"), false, null, null);
- }
- return i;
- }
- return null;
- }
+ i[j] = new Invoker(into, clazz, this.get(o, "invokemethod"), this.get(o, "argdesc"), this.get(o, "desc"), this.get(o, "method"), false, null, null);
+ }
+ return i;
+ }
+ return null;
+ }
- @Override
- public Callback[] getCallbacks() {
- JSONArray a = (JSONArray) root.get("callbacks");
+ @Override
+ public Callback[] getCallbacks() {
+ JSONArray a = (JSONArray) root.get("callbacks");
- if (a != null && a.size() > 0) {
- Callback[] c = new Callback[a.size()];
- for (int j = 0; j < a.size(); j++) {
- JSONObject o = (JSONObject) a.get(j);
+ if (a != null && a.size() > 0) {
+ Callback[] c = new Callback[a.size()];
+ for (int j = 0; j < a.size(); j++) {
+ JSONObject o = (JSONObject) a.get(j);
- if (o.containsKey("class") && o.containsKey("accessor")) {
- throw new RuntimeException("Cannot have class AND accessor tags together!");
- }
+ if (o.containsKey("class") && o.containsKey("accessor")) {
+ throw new RuntimeException("Cannot have class AND accessor tags together!");
+ }
- if (o.containsKey("accessor") && this.interfaces == null) {
- throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
- }
+ if (o.containsKey("accessor") && this.interfaces == null) {
+ throw new RuntimeException("Cannot use accessor tag before parsing interfaces!");
+ }
- String desc = this.get(o, "desc");
+ String desc = this.get(o, "desc");
- if (desc != null && desc.contains("%s")) {
- desc = formatDescription(desc);
- }
+ if (desc != null && desc.contains("%s")) {
+ desc = formatDescription(desc);
+ }
- String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
+ String clazz = o.containsKey("class") ? this.get(o, "class") : interfaces.get(this.get(o, "accessor"));
- c[j] = new Callback(clazz, this.get(o, "method"), this.get(o, "callclass"), this.get(o, "callmethod"), this.get(o, "calldesc"), this.get(o, "callargs"), this.get(o, "desc"), false);
- }
- return c;
- }
- return null;
- }
+ c[j] = new Callback(clazz, this.get(o, "method"), this.get(o, "callclass"), this.get(o, "callmethod"), this.get(o, "calldesc"), this.get(o, "callargs"), this.get(o, "desc"), false);
+ }
+ return c;
+ }
+ return null;
+ }
- @Override
- public HashMap getConstants() {
- if (this.constants == null) {
- this.constants = new HashMap<>();
- }
+ @Override
+ public HashMap getConstants() {
+ if (this.constants == null) {
+ this.constants = new HashMap<>();
+ }
- if (!this.constants.isEmpty()) {
- return this.constants;
- }
+ if (!this.constants.isEmpty()) {
+ return this.constants;
+ }
- JSONArray a = (JSONArray) root.get("constants");
+ JSONArray a = (JSONArray) root.get("constants");
- if (a != null && a.size() > 0) {
- for (int j = 0; j < a.size(); j++) {
- JSONObject o = (JSONObject) a.get(j);
- this.constants.put(this.get(o, "name"), (String) o.get("value"));
- }
- }
+ if (a != null && a.size() > 0) {
+ for (int j = 0; j < a.size(); j++) {
+ JSONObject o = (JSONObject) a.get(j);
+ this.constants.put(this.get(o, "name"), (String) o.get("value"));
+ }
+ }
- return this.constants;
- }
+ return this.constants;
+ }
}
diff --git a/src/main/java/org/parabot/core/parsers/hooks/XMLHookParser.java b/src/main/java/org/parabot/core/parsers/hooks/XMLHookParser.java
index c334cb2..af01411 100644
--- a/src/main/java/org/parabot/core/parsers/hooks/XMLHookParser.java
+++ b/src/main/java/org/parabot/core/parsers/hooks/XMLHookParser.java
@@ -1,274 +1,44 @@
package org.parabot.core.parsers.hooks;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
import org.parabot.core.Core;
import org.parabot.core.asm.adapters.AddInterfaceAdapter;
import org.parabot.core.asm.hooks.HookFile;
-import org.parabot.core.asm.wrappers.Callback;
-import org.parabot.core.asm.wrappers.Getter;
-import org.parabot.core.asm.wrappers.Interface;
-import org.parabot.core.asm.wrappers.Invoker;
-import org.parabot.core.asm.wrappers.Setter;
-import org.parabot.core.asm.wrappers.Super;
+import org.parabot.core.asm.wrappers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.util.ArrayList;
+import java.util.HashMap;
+
public class XMLHookParser extends HookParser {
- private Document doc;
- private HashMap interfaceMap;
- private HashMap constants;
- private boolean parsedInterfaces;
+ private Document doc;
+ private HashMap interfaceMap;
+ private HashMap constants;
+ private boolean parsedInterfaces;
- public XMLHookParser(HookFile hookFile) {
- super(hookFile);
- interfaceMap = new HashMap();
- constants = new HashMap();
- try {
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory
- .newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- doc = dBuilder.parse(hookFile.getInputStream());
- doc.getDocumentElement().normalize();
- if (!doc.getDocumentElement().getNodeName().equals("injector")) {
- throw new RuntimeException("Incorrect hook file.");
- }
- } catch (Throwable t) {
- throw new RuntimeException("Unable to parse hooks " + t);
- }
- }
+ public XMLHookParser(HookFile hookFile) {
+ super(hookFile);
+ interfaceMap = new HashMap();
+ constants = new HashMap();
+ try {
+ DocumentBuilderFactory dbFactory = DocumentBuilderFactory
+ .newInstance();
+ DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+ doc = dBuilder.parse(hookFile.getInputStream());
+ doc.getDocumentElement().normalize();
+ if (!doc.getDocumentElement().getNodeName().equals("injector")) {
+ throw new RuntimeException("Incorrect hook file.");
+ }
+ } catch (Throwable t) {
+ throw new RuntimeException("Unable to parse hooks " + t);
+ }
+ }
- @Override
- public Interface[] getInterfaces() {
- parsedInterfaces = true;
- final NodeList interfaceRootList = doc
- .getElementsByTagName("interfaces");
- switch (interfaceRootList.getLength()) {
- case 0:
- return null;
- case 1:
- break;
- default:
- throw new RuntimeException(
- "Hook file may not contains multiple tags ");
- }
- final Node node = interfaceRootList.item(0);
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
- final Element interfaceRoot = (Element) node;
- final NodeList interfaces = interfaceRoot.getElementsByTagName("add");
- if (interfaces.getLength() == 0) {
- return null;
- }
- final ArrayList interfaceList = new ArrayList();
- for (int x = 0; x < interfaces.getLength(); x++) {
- final Node n = interfaces.item(x);
- if (n.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- final Element addInterface = (Element) n;
- final String className = getValue("classname", addInterface);
- final String interfaceClass = getValue("interface", addInterface);
- interfaceMap.put(interfaceClass, className);
- final Interface inf = new Interface(className, interfaceClass);
- interfaceList.add(inf);
- }
- return interfaceList.toArray(new Interface[interfaceList.size()]);
- }
-
- @Override
- public Super[] getSupers() {
- final NodeList interfaceRootList = doc.getElementsByTagName("supers");
- switch (interfaceRootList.getLength()) {
- case 0:
- return null;
- case 1:
- break;
- default:
- throw new RuntimeException(
- "Hook file may not contains multiple tags ");
- }
- final Node node = interfaceRootList.item(0);
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
- final Element superRoot = (Element) node;
- final NodeList supers = superRoot.getElementsByTagName("add");
- if (supers.getLength() == 0) {
- return null;
- }
- final ArrayList superList = new ArrayList();
- for (int x = 0; x < supers.getLength(); x++) {
- final Node n = supers.item(x);
- if (n.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- final Element addSuper = (Element) n;
- final String className = getValue("classname", addSuper);
- final String superClass = getValue("super", addSuper);
- final Super sup = new Super(className, superClass);
- superList.add(sup);
- }
- return superList.toArray(new Super[superList.size()]);
- }
-
- @Override
- public Getter[] getGetters() {
- final NodeList getterRootList = doc.getElementsByTagName("getters");
- switch (getterRootList.getLength()) {
- case 0:
- return null;
- case 1:
- break;
- default:
- throw new RuntimeException(
- "Hook file may not contains multiple tags ");
- }
- final Node node = getterRootList.item(0);
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
- final Element getterRoot = (Element) node;
- final NodeList getters = getterRoot.getElementsByTagName("add");
- if (getters.getLength() == 0) {
- return null;
- }
- final ArrayList getterList = new ArrayList();
- for (int x = 0; x < getters.getLength(); x++) {
- final Node n = getters.item(x);
- if (n.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- final Element addGetter = (Element) n;
- if (isSet("classname", addGetter) && isSet("accessor", addGetter)) {
- throw new RuntimeException(
- "Can't set classname and accessor tag together.");
- }
- if (isSet("accessor", addGetter) && !parsedInterfaces) {
- throw new RuntimeException(
- "You'll need to parse interfaces first.");
- }
- final String className = isSet("classname", addGetter) ? getValue(
- "classname", addGetter) : interfaceMap.get(getValue(
- "accessor", addGetter));
- final String into = isSet("into", addGetter) ? getValue("into",
- addGetter) : className;
- final long multiplier = isSet("multiplier", addGetter) ? Long.parseLong(getValue("multiplier", addGetter)) : 0L;
- final String fieldName = getValue("field", addGetter);
- final String fieldDesc = isSet("descfield", addGetter) ? getValue("descfield", addGetter) : null;
- final String methodName = getValue("methodname", addGetter);
- boolean staticMethod = isSet("methstatic", addGetter) ? (getValue(
- "methstatic", addGetter).equals("true")) : false;
- String returnDesc = isSet("desc", addGetter) ? getValue("desc",
- addGetter) : null;
- String array = "";
- if (returnDesc != null && returnDesc.contains("%s")) {
- StringBuilder str = new StringBuilder();
- if (returnDesc.startsWith("[")) {
- for (int i = 0; i < returnDesc.length(); i++) {
- if (returnDesc.charAt(i) == '[') {
- array += '[';
- }
- }
- returnDesc = returnDesc.replaceAll("\\[", "");
- }
- str.append(array)
- .append('L')
- .append(String.format(returnDesc,
- AddInterfaceAdapter.getAccessorPackage()))
- .append(";");
- returnDesc = str.toString();
- }
- final Getter get = new Getter(into, className, fieldName,
- methodName, returnDesc, staticMethod, multiplier, fieldDesc);
- getterList.add(get);
- }
- Core.verbose("Fields hooked: " + getterList.size());
- return getterList.toArray(new Getter[getterList.size()]);
- }
-
- @Override
- public Setter[] getSetters() {
- final NodeList setterRootList = doc.getElementsByTagName("setters");
- switch (setterRootList.getLength()) {
- case 0:
- return null;
- case 1:
- break;
- default:
- throw new RuntimeException(
- "Hook file may not contains multiple tags ");
- }
- final Node node = setterRootList.item(0);
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
- final Element setterRoot = (Element) node;
- final NodeList setters = setterRoot.getElementsByTagName("add");
- if (setters.getLength() == 0) {
- return null;
- }
- final ArrayList setterList = new ArrayList();
- for (int x = 0; x < setters.getLength(); x++) {
- final Node n = setters.item(x);
- if (n.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- final Element addSetter = (Element) n;
- if (isSet("classname", addSetter) && isSet("accessor", addSetter)) {
- throw new RuntimeException(
- "Can't set classname and accessor tag together.");
- }
- if (isSet("accessor", addSetter) && !parsedInterfaces) {
- throw new RuntimeException(
- "You'll need to parse interfaces first.");
- }
- final String className = isSet("classname", addSetter) ? getValue(
- "classname", addSetter) : interfaceMap.get(getValue(
- "accessor", addSetter));
- final String into = isSet("into", addSetter) ? getValue("into",
- addSetter) : className;
- final String fieldName = getValue("field", addSetter);
- final String fieldDesc = isSet("descfield", addSetter) ? getValue("descfield", addSetter) : null;
- final String methodName = getValue("methodname", addSetter);
- boolean staticMethod = isSet("methstatic", addSetter) ? (getValue(
- "methstatic", addSetter).equals("true")) : false;
- String returnDesc = isSet("desc", addSetter) ? getValue("desc",
- addSetter) : null;
- String array = "";
- if (returnDesc != null && returnDesc.contains("%s")) {
- StringBuilder str = new StringBuilder();
- if (returnDesc.startsWith("[")) {
- for (int i = 0; i < returnDesc.length(); i++) {
- if (returnDesc.charAt(i) == '[') {
- array += '[';
- }
- }
- returnDesc = returnDesc.replaceAll("\\[", "");
- }
- str.append(array)
- .append('L')
- .append(String.format(returnDesc,
- AddInterfaceAdapter.getAccessorPackage()))
- .append(";");
- returnDesc = str.toString();
- }
- final Setter get = new Setter(className, into, fieldName,
- methodName, returnDesc, staticMethod, fieldDesc);
- setterList.add(get);
- }
- return setterList.toArray(new Setter[setterList.size()]);
- }
-
-
- private static String resolveDesc(String returnDesc) {
+ private static String resolveDesc(String returnDesc) {
String array = "";
if (returnDesc != null && returnDesc.contains("%s")) {
StringBuilder str = new StringBuilder();
@@ -301,9 +71,232 @@ public class XMLHookParser extends HookParser {
return node.getNodeValue();
}
- @Override
- public Invoker[] getInvokers() {
- final NodeList invokerRootList = doc.getElementsByTagName("invokers");
+ @Override
+ public Interface[] getInterfaces() {
+ parsedInterfaces = true;
+ final NodeList interfaceRootList = doc
+ .getElementsByTagName("interfaces");
+ switch (interfaceRootList.getLength()) {
+ case 0:
+ return null;
+ case 1:
+ break;
+ default:
+ throw new RuntimeException(
+ "Hook file may not contains multiple tags ");
+ }
+ final Node node = interfaceRootList.item(0);
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
+ return null;
+ }
+ final Element interfaceRoot = (Element) node;
+ final NodeList interfaces = interfaceRoot.getElementsByTagName("add");
+ if (interfaces.getLength() == 0) {
+ return null;
+ }
+ final ArrayList interfaceList = new ArrayList();
+ for (int x = 0; x < interfaces.getLength(); x++) {
+ final Node n = interfaces.item(x);
+ if (n.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ final Element addInterface = (Element) n;
+ final String className = getValue("classname", addInterface);
+ final String interfaceClass = getValue("interface", addInterface);
+ interfaceMap.put(interfaceClass, className);
+ final Interface inf = new Interface(className, interfaceClass);
+ interfaceList.add(inf);
+ }
+ return interfaceList.toArray(new Interface[interfaceList.size()]);
+ }
+
+ @Override
+ public Super[] getSupers() {
+ final NodeList interfaceRootList = doc.getElementsByTagName("supers");
+ switch (interfaceRootList.getLength()) {
+ case 0:
+ return null;
+ case 1:
+ break;
+ default:
+ throw new RuntimeException(
+ "Hook file may not contains multiple tags ");
+ }
+ final Node node = interfaceRootList.item(0);
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
+ return null;
+ }
+ final Element superRoot = (Element) node;
+ final NodeList supers = superRoot.getElementsByTagName("add");
+ if (supers.getLength() == 0) {
+ return null;
+ }
+ final ArrayList superList = new ArrayList();
+ for (int x = 0; x < supers.getLength(); x++) {
+ final Node n = supers.item(x);
+ if (n.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ final Element addSuper = (Element) n;
+ final String className = getValue("classname", addSuper);
+ final String superClass = getValue("super", addSuper);
+ final Super sup = new Super(className, superClass);
+ superList.add(sup);
+ }
+ return superList.toArray(new Super[superList.size()]);
+ }
+
+ @Override
+ public Getter[] getGetters() {
+ final NodeList getterRootList = doc.getElementsByTagName("getters");
+ switch (getterRootList.getLength()) {
+ case 0:
+ return null;
+ case 1:
+ break;
+ default:
+ throw new RuntimeException(
+ "Hook file may not contains multiple tags ");
+ }
+ final Node node = getterRootList.item(0);
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
+ return null;
+ }
+ final Element getterRoot = (Element) node;
+ final NodeList getters = getterRoot.getElementsByTagName("add");
+ if (getters.getLength() == 0) {
+ return null;
+ }
+ final ArrayList getterList = new ArrayList();
+ for (int x = 0; x < getters.getLength(); x++) {
+ final Node n = getters.item(x);
+ if (n.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ final Element addGetter = (Element) n;
+ if (isSet("classname", addGetter) && isSet("accessor", addGetter)) {
+ throw new RuntimeException(
+ "Can't set classname and accessor tag together.");
+ }
+ if (isSet("accessor", addGetter) && !parsedInterfaces) {
+ throw new RuntimeException(
+ "You'll need to parse interfaces first.");
+ }
+ final String className = isSet("classname", addGetter) ? getValue(
+ "classname", addGetter) : interfaceMap.get(getValue(
+ "accessor", addGetter));
+ final String into = isSet("into", addGetter) ? getValue("into",
+ addGetter) : className;
+ final long multiplier = isSet("multiplier", addGetter) ? Long.parseLong(getValue("multiplier", addGetter)) : 0L;
+ final String fieldName = getValue("field", addGetter);
+ final String fieldDesc = isSet("descfield", addGetter) ? getValue("descfield", addGetter) : null;
+ final String methodName = getValue("methodname", addGetter);
+ boolean staticMethod = isSet("methstatic", addGetter) ? (getValue(
+ "methstatic", addGetter).equals("true")) : false;
+ String returnDesc = isSet("desc", addGetter) ? getValue("desc",
+ addGetter) : null;
+ String array = "";
+ if (returnDesc != null && returnDesc.contains("%s")) {
+ StringBuilder str = new StringBuilder();
+ if (returnDesc.startsWith("[")) {
+ for (int i = 0; i < returnDesc.length(); i++) {
+ if (returnDesc.charAt(i) == '[') {
+ array += '[';
+ }
+ }
+ returnDesc = returnDesc.replaceAll("\\[", "");
+ }
+ str.append(array)
+ .append('L')
+ .append(String.format(returnDesc,
+ AddInterfaceAdapter.getAccessorPackage()))
+ .append(";");
+ returnDesc = str.toString();
+ }
+ final Getter get = new Getter(into, className, fieldName,
+ methodName, returnDesc, staticMethod, multiplier, fieldDesc);
+ getterList.add(get);
+ }
+ Core.verbose("Fields hooked: " + getterList.size());
+ return getterList.toArray(new Getter[getterList.size()]);
+ }
+
+ @Override
+ public Setter[] getSetters() {
+ final NodeList setterRootList = doc.getElementsByTagName("setters");
+ switch (setterRootList.getLength()) {
+ case 0:
+ return null;
+ case 1:
+ break;
+ default:
+ throw new RuntimeException(
+ "Hook file may not contains multiple tags ");
+ }
+ final Node node = setterRootList.item(0);
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
+ return null;
+ }
+ final Element setterRoot = (Element) node;
+ final NodeList setters = setterRoot.getElementsByTagName("add");
+ if (setters.getLength() == 0) {
+ return null;
+ }
+ final ArrayList setterList = new ArrayList();
+ for (int x = 0; x < setters.getLength(); x++) {
+ final Node n = setters.item(x);
+ if (n.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ final Element addSetter = (Element) n;
+ if (isSet("classname", addSetter) && isSet("accessor", addSetter)) {
+ throw new RuntimeException(
+ "Can't set classname and accessor tag together.");
+ }
+ if (isSet("accessor", addSetter) && !parsedInterfaces) {
+ throw new RuntimeException(
+ "You'll need to parse interfaces first.");
+ }
+ final String className = isSet("classname", addSetter) ? getValue(
+ "classname", addSetter) : interfaceMap.get(getValue(
+ "accessor", addSetter));
+ final String into = isSet("into", addSetter) ? getValue("into",
+ addSetter) : className;
+ final String fieldName = getValue("field", addSetter);
+ final String fieldDesc = isSet("descfield", addSetter) ? getValue("descfield", addSetter) : null;
+ final String methodName = getValue("methodname", addSetter);
+ boolean staticMethod = isSet("methstatic", addSetter) ? (getValue(
+ "methstatic", addSetter).equals("true")) : false;
+ String returnDesc = isSet("desc", addSetter) ? getValue("desc",
+ addSetter) : null;
+ String array = "";
+ if (returnDesc != null && returnDesc.contains("%s")) {
+ StringBuilder str = new StringBuilder();
+ if (returnDesc.startsWith("[")) {
+ for (int i = 0; i < returnDesc.length(); i++) {
+ if (returnDesc.charAt(i) == '[') {
+ array += '[';
+ }
+ }
+ returnDesc = returnDesc.replaceAll("\\[", "");
+ }
+ str.append(array)
+ .append('L')
+ .append(String.format(returnDesc,
+ AddInterfaceAdapter.getAccessorPackage()))
+ .append(";");
+ returnDesc = str.toString();
+ }
+ final Setter get = new Setter(className, into, fieldName,
+ methodName, returnDesc, staticMethod, fieldDesc);
+ setterList.add(get);
+ }
+ return setterList.toArray(new Setter[setterList.size()]);
+ }
+
+ @Override
+ public Invoker[] getInvokers() {
+ final NodeList invokerRootList = doc.getElementsByTagName("invokers");
switch (invokerRootList.getLength()) {
case 0:
return null;
@@ -317,8 +310,8 @@ public class XMLHookParser extends HookParser {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
- final Element invokerRoot = (Element) node;
- final NodeList invokers = invokerRoot.getElementsByTagName("add");
+ final Element invokerRoot = (Element) node;
+ final NodeList invokers = invokerRoot.getElementsByTagName("add");
if (invokers.getLength() == 0) {
return null;
}
@@ -342,26 +335,26 @@ public class XMLHookParser extends HookParser {
"accessor", addInvoker));
final String into = isSet("into", addInvoker) ? getValue("into",
addInvoker) : className;
- final String methodName = getValue("methodname", addInvoker);
+ final String methodName = getValue("methodname", addInvoker);
final String invMethodName = getValue("invokemethod", addInvoker);
- final String argsDesc = getValue("argsdesc", addInvoker);
+ final String argsDesc = getValue("argsdesc", addInvoker);
String returnDesc = isSet("desc", addInvoker) ? resolveDesc(getValue(
"desc", addInvoker)) : null;
-
- final boolean isInterface = isSet("interface", addInvoker) ? Boolean.parseBoolean(getValue("interface", addInvoker)) : false;
- final String instanceCast = isSet("instancecast", addInvoker) ? getValue("instancecast", addInvoker) : null;
- final String checkCastArgsDesc = isSet("castargs", addInvoker) ? getValue("castargs", addInvoker) : null;
+
+ final boolean isInterface = isSet("interface", addInvoker) ? Boolean.parseBoolean(getValue("interface", addInvoker)) : false;
+ final String instanceCast = isSet("instancecast", addInvoker) ? getValue("instancecast", addInvoker) : null;
+ final String checkCastArgsDesc = isSet("castargs", addInvoker) ? getValue("castargs", addInvoker) : null;
final Invoker invoker = new Invoker(into, className, invMethodName,
argsDesc, returnDesc, methodName, isInterface, instanceCast, checkCastArgsDesc);
invokerList.add(invoker);
}
return invokerList.toArray(new Invoker[invokerList.size()]);
- }
+ }
- @Override
- public HashMap getConstants() {
- if (!constants.isEmpty()) {
+ @Override
+ public HashMap getConstants() {
+ if (!constants.isEmpty()) {
return constants;
}
final NodeList constantsRootList = doc
@@ -379,7 +372,7 @@ public class XMLHookParser extends HookParser {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
- final Element constantRoot = (Element) node;
+ final Element constantRoot = (Element) node;
final NodeList constantsList = constantRoot.getElementsByTagName("add");
if (constantsList.getLength() == 0) {
// return empty hashmap
@@ -391,16 +384,16 @@ public class XMLHookParser extends HookParser {
continue;
}
final Element addConstant = (Element) n;
- final String key = getValue("key", addConstant);
- final String value = getValue("value", addConstant);
+ final String key = getValue("key", addConstant);
+ final String value = getValue("value", addConstant);
constants.put(key, value);
}
return constants;
- }
+ }
- @Override
- public Callback[] getCallbacks() {
- final NodeList callbackRootList = doc.getElementsByTagName("callbacks");
+ @Override
+ public Callback[] getCallbacks() {
+ final NodeList callbackRootList = doc.getElementsByTagName("callbacks");
switch (callbackRootList.getLength()) {
case 0:
return null;
@@ -414,8 +407,8 @@ public class XMLHookParser extends HookParser {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
- final Element callbackRoot = (Element) node;
- final NodeList callbacks = callbackRoot.getElementsByTagName("add");
+ final Element callbackRoot = (Element) node;
+ final NodeList callbacks = callbackRoot.getElementsByTagName("add");
if (callbacks.getLength() == 0) {
return null;
}
@@ -439,12 +432,12 @@ public class XMLHookParser extends HookParser {
"classname", addCallback) : interfaceMap.get(getValue(
"accessor", addCallback));
- final String methodName = getValue("methodname", addCallback);
- final String callClass = getValue("callclass", addCallback);
- final String callMethod = getValue("callmethod", addCallback);
- final String callDesc = getValue("calldesc", addCallback);
- final String callArgs = getValue("callargs", addCallback);
- final String desc = getValue("desc", addCallback);
+ final String methodName = getValue("methodname", addCallback);
+ final String callClass = getValue("callclass", addCallback);
+ final String callMethod = getValue("callmethod", addCallback);
+ final String callDesc = getValue("calldesc", addCallback);
+ final String callArgs = getValue("callargs", addCallback);
+ final String desc = getValue("desc", addCallback);
final boolean conditional = isSet("conditional", addCallback);
final Callback callback = new Callback(className, methodName, desc,
@@ -452,6 +445,6 @@ public class XMLHookParser extends HookParser {
callbackList.add(callback);
}
return callbackList.toArray(new Callback[callbackList.size()]);
- }
+ }
}
diff --git a/src/main/java/org/parabot/core/parsers/randoms/PublicRandoms.java b/src/main/java/org/parabot/core/parsers/randoms/PublicRandoms.java
index 4a1d80f..ed285ff 100644
--- a/src/main/java/org/parabot/core/parsers/randoms/PublicRandoms.java
+++ b/src/main/java/org/parabot/core/parsers/randoms/PublicRandoms.java
@@ -28,14 +28,14 @@ public class PublicRandoms extends RandomParser {
download();
}
try {
- URL url = myJar.toURI().toURL();
- URL[] urls = new URL[]{url};
+ URL url = myJar.toURI().toURL();
+ URL[] urls = new URL[]{ url };
String server = Context.getInstance().getServerProviderInfo().getServerName();
- URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
- Class> classToLoad = Class.forName("org.parabot.randoms.Core", true, child);
- Method method = classToLoad.getDeclaredMethod("init", String.class);
- Object instance = classToLoad.newInstance();
+ URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
+ Class> classToLoad = Class.forName("org.parabot.randoms.Core", true, child);
+ Method method = classToLoad.getDeclaredMethod("init", String.class);
+ Object instance = classToLoad.newInstance();
System.out.println(server);
method.invoke(instance, server);
Core.verbose("Successfully parsed public random!");
diff --git a/src/main/java/org/parabot/core/parsers/scripts/BDNScripts.java b/src/main/java/org/parabot/core/parsers/scripts/BDNScripts.java
index f8b23a1..1c72934 100644
--- a/src/main/java/org/parabot/core/parsers/scripts/BDNScripts.java
+++ b/src/main/java/org/parabot/core/parsers/scripts/BDNScripts.java
@@ -40,19 +40,19 @@ public class BDNScripts extends ScriptParser {
JSONParser parser = new JSONParser();
try {
BufferedReader br = WebUtil.getReader(new URL(
- Configuration.GET_SCRIPTS + Context.getInstance().getServerProviderInfo().getServerName()),
+ Configuration.GET_SCRIPTS + Context.getInstance().getServerProviderInfo().getServerName()),
manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
String line;
while ((line = br.readLine()) != null) {
- JSONObject jsonObject = (JSONObject) parser.parse(line);
- int bdnId = Integer.parseInt(String.valueOf(jsonObject.get("id")));
- String scriptName = String.valueOf(jsonObject.get("name"));
- String author = String.valueOf(jsonObject.get("author"));
- double version = Double.parseDouble(String.valueOf(jsonObject.get("version")));
- String category = String.valueOf(jsonObject.get("category"));
- String description = String.valueOf(jsonObject.get("description"));
+ JSONObject jsonObject = (JSONObject) parser.parse(line);
+ int bdnId = Integer.parseInt(String.valueOf(jsonObject.get("id")));
+ String scriptName = String.valueOf(jsonObject.get("name"));
+ String author = String.valueOf(jsonObject.get("author"));
+ double version = Double.parseDouble(String.valueOf(jsonObject.get("version")));
+ String category = String.valueOf(jsonObject.get("category"));
+ String description = String.valueOf(jsonObject.get("description"));
final ScriptDescription desc = new ScriptDescription(scriptName,
author, category, version, description,
diff --git a/src/main/java/org/parabot/core/parsers/scripts/ScriptParser.java b/src/main/java/org/parabot/core/parsers/scripts/ScriptParser.java
index 068d6e1..9bb26d3 100644
--- a/src/main/java/org/parabot/core/parsers/scripts/ScriptParser.java
+++ b/src/main/java/org/parabot/core/parsers/scripts/ScriptParser.java
@@ -1,14 +1,14 @@
package org.parabot.core.parsers.scripts;
+import org.parabot.core.Core;
+import org.parabot.core.desc.ScriptDescription;
+import org.parabot.environment.scripts.executers.ScriptExecuter;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
-import org.parabot.core.Core;
-import org.parabot.core.desc.ScriptDescription;
-import org.parabot.environment.scripts.executers.ScriptExecuter;
-
/**
* Abstract class for parsing scripts
*
@@ -18,8 +18,6 @@ public abstract class ScriptParser {
public static final Map SCRIPT_CACHE = new HashMap();
- public abstract void execute();
-
public static ScriptDescription[] getDescriptions() {
SCRIPT_CACHE.clear();
final ArrayList parsers = new ArrayList();
@@ -43,10 +41,12 @@ public abstract class ScriptParser {
}
Core.verbose("Scripts parsed.");
}
-
- Map SORTED_SCRIPT_CACHE = new TreeMap( SCRIPT_CACHE );
+
+ Map SORTED_SCRIPT_CACHE = new TreeMap(SCRIPT_CACHE);
return SORTED_SCRIPT_CACHE.keySet().toArray(new ScriptDescription[SORTED_SCRIPT_CACHE.size()]);
}
+ public abstract void execute();
+
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/parsers/servers/LocalServers.java b/src/main/java/org/parabot/core/parsers/servers/LocalServers.java
index 96c0e14..eb0f698 100644
--- a/src/main/java/org/parabot/core/parsers/servers/LocalServers.java
+++ b/src/main/java/org/parabot/core/parsers/servers/LocalServers.java
@@ -1,36 +1,23 @@
package org.parabot.core.parsers.servers;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Objects;
-
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
-import org.parabot.core.Configuration;
-import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.Directories;
-import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.desc.ServerProviderInfo;
-import org.parabot.core.ui.components.VerboseLoader;
-import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.WebUtil;
import org.parabot.environment.servers.ServerManifest;
-import org.parabot.environment.servers.ServerProvider;
import org.parabot.environment.servers.executers.LocalPublicServerExecuter;
import org.parabot.environment.servers.executers.LocalServerExecuter;
-import org.parabot.environment.servers.executers.PublicServerExecuter;
import org.parabot.environment.servers.loader.ServerLoader;
-import javax.swing.*;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
/**
* Parses local server providers located in the servers directory
@@ -86,24 +73,24 @@ public class LocalServers extends ServerParser {
}
}
- for (File file : Directories.listJSONFiles(Directories.getServerPath())){
+ for (File file : Directories.listJSONFiles(Directories.getServerPath())) {
Core.verbose("[Local server in]: " + file.getName());
try {
- JSONObject object = (JSONObject) WebUtil.getJsonParser().parse(new FileReader(file));
- String name = (String) object.get("name");
- String author = (String) object.get("author");
- double version = (Double) object.get("version");
- String clientClass = (String) object.get("client-class");
- Object bank;
- int bankTabs = 0;
- if ((bank = object.get("bank")) != null){
+ JSONObject object = (JSONObject) WebUtil.getJsonParser().parse(new FileReader(file));
+ String name = (String) object.get("name");
+ String author = (String) object.get("author");
+ double version = (Double) object.get("version");
+ String clientClass = (String) object.get("client-class");
+ Object bank;
+ int bankTabs = 0;
+ if ((bank = object.get("bank")) != null) {
bankTabs = (int) bank;
}
JSONObject locations = (JSONObject) object.get("locations");
- String server = (String) locations.get("server");
- String provider = (String) locations.get("provider");
- String hooks = (String) locations.get("hooks");
+ String server = (String) locations.get("server");
+ String provider = (String) locations.get("provider");
+ String hooks = (String) locations.get("hooks");
Core.verbose("[Local server]: " + name);
ServerProviderInfo serverProviderInfo = new ServerProviderInfo(server, hooks, name, clientClass, bankTabs);
diff --git a/src/main/java/org/parabot/core/parsers/servers/PublicServers.java b/src/main/java/org/parabot/core/parsers/servers/PublicServers.java
index ead4bdc..3aced4c 100644
--- a/src/main/java/org/parabot/core/parsers/servers/PublicServers.java
+++ b/src/main/java/org/parabot/core/parsers/servers/PublicServers.java
@@ -43,9 +43,9 @@ public class PublicServers extends ServerParser {
while ((line = br.readLine()) != null) {
JSONObject jsonObject = (JSONObject) parser.parse(line);
- String name = String.valueOf(jsonObject.get("name"));
- String author = String.valueOf(jsonObject.get("author"));
- double version = Double.parseDouble(String.valueOf(jsonObject.get("version")));
+ String name = String.valueOf(jsonObject.get("name"));
+ String author = String.valueOf(jsonObject.get("author"));
+ double version = Double.parseDouble(String.valueOf(jsonObject.get("version")));
ServerDescription desc = new ServerDescription(name,
author, version);
diff --git a/src/main/java/org/parabot/core/parsers/servers/ServerParser.java b/src/main/java/org/parabot/core/parsers/servers/ServerParser.java
index 91d5b24..4ee3739 100644
--- a/src/main/java/org/parabot/core/parsers/servers/ServerParser.java
+++ b/src/main/java/org/parabot/core/parsers/servers/ServerParser.java
@@ -17,8 +17,6 @@ import java.util.TreeMap;
public abstract class ServerParser {
public static final Map SERVER_CACHE = new HashMap();
- public abstract void execute();
-
public static final ServerDescription[] getDescriptions() {
SERVER_CACHE.clear();
final ArrayList parsers = new ArrayList<>();
@@ -43,9 +41,11 @@ public abstract class ServerParser {
Core.verbose("Server providers parsed.");
}
- Map SORTED_SERVER_CACHE = new TreeMap( SERVER_CACHE );
+ Map SORTED_SERVER_CACHE = new TreeMap(SERVER_CACHE);
return SORTED_SERVER_CACHE.keySet().toArray(new ServerDescription[SORTED_SERVER_CACHE.size()]);
}
+ public abstract void execute();
+
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/core/reflect/RefClass.java b/src/main/java/org/parabot/core/reflect/RefClass.java
index 9dd39bb..5a8206e 100644
--- a/src/main/java/org/parabot/core/reflect/RefClass.java
+++ b/src/main/java/org/parabot/core/reflect/RefClass.java
@@ -9,324 +9,321 @@ import java.util.ArrayList;
import java.util.Arrays;
/**
- *
* A RefClass represents a class or an instance of that class, if
* no instance is provided this class can only get values from static fields and
* only invoke static methods
- *
+ *
* @author Everel
- *
*/
public class RefClass extends RefModifiers {
- private Object instance;
- private Class> clazz;
+ private Object instance;
+ private Class> clazz;
- public RefClass(Class> clazz) {
- this(clazz, null);
- }
+ public RefClass(Class> clazz) {
+ this(clazz, null);
+ }
- public RefClass(Object instance) {
- this(instance.getClass(), instance);
- }
+ public RefClass(Object instance) {
+ this(instance.getClass(), instance);
+ }
- public RefClass(Class> clazz, Object instance) {
- super(clazz.getModifiers());
- this.clazz = clazz;
- setInstance(instance);
- }
+ public RefClass(Class> clazz, Object instance) {
+ super(clazz.getModifiers());
+ this.clazz = clazz;
+ setInstance(instance);
+ }
- /**
- * Sets the instance of this class so now non static fields values can be
- * retrieved and non static methods can be invoked
- *
- * @param instance
- * instance of this class.
- */
- public void setInstance(Object instance) {
- if (instance == null) {
- this.instance = null;
- return;
- }
- if (this.clazz != null) {
- if (!clazz.isInstance(instance)) {
- throw new IllegalArgumentException(instance
- + " is not an instance of the class " + clazz);
- }
- }
- this.instance = instance;
- }
+ /**
+ * Gets the instance of this class
+ *
+ * @return if an instance of this class is known it will return that
+ * instance, otherwise it will return null.
+ */
+ public Object getInstance() {
+ return this.instance;
+ }
- /**
- * Gets the instance of this class
- *
- * @return if an instance of this class is known it will return that
- * instance, otherwise it will return null.
- */
- public Object getInstance() {
- return this.instance;
- }
+ /**
+ * Sets the instance of this class so now non static fields values can be
+ * retrieved and non static methods can be invoked
+ *
+ * @param instance instance of this class.
+ */
+ public void setInstance(Object instance) {
+ if (instance == null) {
+ this.instance = null;
+ return;
+ }
+ if (this.clazz != null) {
+ if (!clazz.isInstance(instance)) {
+ throw new IllegalArgumentException(instance
+ + " is not an instance of the class " + clazz);
+ }
+ }
+ this.instance = instance;
+ }
- /**
- * Gets the class which this RefClass is representing
- *
- * @return class which this RefClass is representing
- */
- public Class> getRepresentingClass() {
- return this.clazz;
- }
+ /**
+ * Gets the class which this RefClass is representing
+ *
+ * @return class which this RefClass is representing
+ */
+ public Class> getRepresentingClass() {
+ return this.clazz;
+ }
- public String getClassName() {
- return this.clazz.getName();
- }
+ public String getClassName() {
+ return this.clazz.getName();
+ }
- public String getSimpleName() {
- return this.clazz.getSimpleName();
- }
+ public String getSimpleName() {
+ return this.clazz.getSimpleName();
+ }
- public String getCanonicalName() {
- return this.clazz.getCanonicalName();
- }
+ public String getCanonicalName() {
+ return this.clazz.getCanonicalName();
+ }
- public Annotation[] getAnnotations(){
- return this.clazz.getAnnotations();
- }
+ public Annotation[] getAnnotations() {
+ return this.clazz.getAnnotations();
+ }
- /**
- * Gets the type of this class
- *
- * @return type of this class
- */
- public org.objectweb.asm.Type getASMType() {
- return org.objectweb.asm.Type.getType(this.clazz);
- }
+ /**
+ * Gets the type of this class
+ *
+ * @return type of this class
+ */
+ public org.objectweb.asm.Type getASMType() {
+ return org.objectweb.asm.Type.getType(this.clazz);
+ }
- /**
- * Gets the class' fields
- *
- * @return all fields if an instance is provided, otherwise only static
- * fields
- */
- public RefField[] getFields() {
- ArrayList fields = new ArrayList();
- // add all static fields
- for (Field f : clazz.getDeclaredFields()) {
- if (Modifier.isStatic(f.getModifiers())) {
- fields.add(new RefField(f, instance));
- }
- }
- if (this.instance != null) {
- // add all non static fields
- for (Field f : clazz.getDeclaredFields()) {
- if (!Modifier.isStatic(f.getModifiers())) {
- fields.add(new RefField(f, instance));
- }
- }
- }
- return fields.toArray(new RefField[fields.size()]);
- }
-
- /**
- * Determines if a object is an instance of this class
- * @param object the object you want to check
- * @return true if the object is an instance of this class; false otherwise
- */
- public boolean instanceOf(Object object) {
- return this.clazz.isInstance(object);
- }
+ /**
+ * Gets the class' fields
+ *
+ * @return all fields if an instance is provided, otherwise only static
+ * fields
+ */
+ public RefField[] getFields() {
+ ArrayList fields = new ArrayList();
+ // add all static fields
+ for (Field f : clazz.getDeclaredFields()) {
+ if (Modifier.isStatic(f.getModifiers())) {
+ fields.add(new RefField(f, instance));
+ }
+ }
+ if (this.instance != null) {
+ // add all non static fields
+ for (Field f : clazz.getDeclaredFields()) {
+ if (!Modifier.isStatic(f.getModifiers())) {
+ fields.add(new RefField(f, instance));
+ }
+ }
+ }
+ return fields.toArray(new RefField[fields.size()]);
+ }
- /**
- * Gets field by field name
- *
- * @param name
- * name of the field
- * @return the field if found
- */
- public RefField getField(String name) {
- return getField(name, null);
- }
+ /**
+ * Determines if a object is an instance of this class
+ *
+ * @param object the object you want to check
+ *
+ * @return true if the object is an instance of this class; false otherwise
+ */
+ public boolean instanceOf(Object object) {
+ return this.clazz.isInstance(object);
+ }
- /**
- * Gets field by field name and desc
- *
- * @param name
- * name of the field
- * @param desc
- * desc type of the field
- * @return the field if found
- */
- public RefField getField(String name, String desc) {
- RefField[] fields = getFields();
- for (RefField f : fields) {
- if (f.getName().equals(name)) {
- if (desc == null) {
- return f;
- }
- if (desc.equals(f.getTypeDesc())) {
- return f;
- }
- }
- }
- return null;
- }
+ /**
+ * Gets field by field name
+ *
+ * @param name name of the field
+ *
+ * @return the field if found
+ */
+ public RefField getField(String name) {
+ return getField(name, null);
+ }
- /**
- * Determines if this class has a super class
- *
- * @return true if this class has a super class and which is
- * not the java/lang/Object class, otherwise false.
- */
- public boolean hasSuperclass() {
- return hasSuperclass(true);
- }
+ /**
+ * Gets field by field name and desc
+ *
+ * @param name name of the field
+ * @param desc desc type of the field
+ *
+ * @return the field if found
+ */
+ public RefField getField(String name, String desc) {
+ RefField[] fields = getFields();
+ for (RefField f : fields) {
+ if (f.getName().equals(name)) {
+ if (desc == null) {
+ return f;
+ }
+ if (desc.equals(f.getTypeDesc())) {
+ return f;
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Determines if this class has a super class
- *
- * @param ignoreObjectClass
- * if you want this method to return false when the superclass is
- * the java/lang/Object class
- * @return true if this class has a superclass, otherwise
- * false
- */
- public boolean hasSuperclass(boolean ignoreObjectClass) {
- if (!ignoreObjectClass) {
- return !clazz.equals(Object.class);
- }
- Class> superClass = clazz.getSuperclass();
- if(superClass == null) {
- return false;
- }
- return !superClass.equals(Object.class);
- }
+ /**
+ * Determines if this class has a super class
+ *
+ * @return true if this class has a super class and which is
+ * not the java/lang/Object class, otherwise false.
+ */
+ public boolean hasSuperclass() {
+ return hasSuperclass(true);
+ }
- /**
- * Returns a new RefClass representing the superclass of this RefClass
- *
- * @return superclass of this RefClass
- */
- public RefClass getSuperclass() {
- return new RefClass(clazz.getSuperclass(), instance);
- }
+ /**
+ * Determines if this class has a super class
+ *
+ * @param ignoreObjectClass if you want this method to return false when the superclass is
+ * the java/lang/Object class
+ *
+ * @return true if this class has a superclass, otherwise
+ * false
+ */
+ public boolean hasSuperclass(boolean ignoreObjectClass) {
+ if (!ignoreObjectClass) {
+ return !clazz.equals(Object.class);
+ }
+ Class> superClass = clazz.getSuperclass();
+ if (superClass == null) {
+ return false;
+ }
+ return !superClass.equals(Object.class);
+ }
- /**
- * Creates a new instance of this class
- *
- * @return a RefClass representing a fresh created instance of that class
- */
- public RefClass newInstance() {
- try {
- return new RefClass(clazz.newInstance());
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Returns a new RefClass representing the superclass of this RefClass
+ *
+ * @return superclass of this RefClass
+ */
+ public RefClass getSuperclass() {
+ return new RefClass(clazz.getSuperclass(), instance);
+ }
- /**
- * Gets the empty (without parameters) constructor of this class if any
- *
- * @return empty constructor if there, otherwise null
- */
- public RefConstructor getConstructor() {
- return getConstructor(new Class>[] {});
- }
+ /**
+ * Creates a new instance of this class
+ *
+ * @return a RefClass representing a fresh created instance of that class
+ */
+ public RefClass newInstance() {
+ try {
+ return new RefClass(clazz.newInstance());
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Gets a RefConstructor from this class
- *
- * @param parameters
- * the constructor it's parameters
- * @return the retrieved constructor
- */
- public RefConstructor getConstructor(Class>[] parameters) {
- try {
- return new RefConstructor(clazz.getDeclaredConstructor(parameters));
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Gets the empty (without parameters) constructor of this class if any
+ *
+ * @return empty constructor if there, otherwise null
+ */
+ public RefConstructor getConstructor() {
+ return getConstructor(new Class>[]{});
+ }
- /**
- * Gets all constructors of this class
- *
- * @return an array with all the constructors in this class
- */
- public RefConstructor[] getConstructors() {
- Constructor>[] constructors = clazz.getDeclaredConstructors();
- RefConstructor[] refConstructors = new RefConstructor[constructors.length];
- for (int i = 0; i < constructors.length; i++) {
- refConstructors[i] = new RefConstructor(constructors[i]);
- }
- return refConstructors;
- }
+ /**
+ * Gets a RefConstructor from this class
+ *
+ * @param parameters the constructor it's parameters
+ *
+ * @return the retrieved constructor
+ */
+ public RefConstructor getConstructor(Class>[] parameters) {
+ try {
+ return new RefConstructor(clazz.getDeclaredConstructor(parameters));
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Gets the class' methods
- *
- * @return all methods if an instance is provided, otherwise only static
- * methods
- */
- public RefMethod[] getMethods() {
- ArrayList methods = new ArrayList();
- // add all static methods
- for (Method m : clazz.getDeclaredMethods()) {
- if (Modifier.isStatic(m.getModifiers())) {
- methods.add(new RefMethod(m, instance));
- }
- }
- if (this.instance != null) {
- // add all non static methods
- for (Method m : clazz.getDeclaredMethods()) {
- if (!Modifier.isStatic(m.getModifiers())) {
- methods.add(new RefMethod(m, instance));
- }
- }
- }
- return methods.toArray(new RefMethod[methods.size()]);
- }
+ /**
+ * Gets all constructors of this class
+ *
+ * @return an array with all the constructors in this class
+ */
+ public RefConstructor[] getConstructors() {
+ Constructor>[] constructors = clazz.getDeclaredConstructors();
+ RefConstructor[] refConstructors = new RefConstructor[constructors.length];
+ for (int i = 0; i < constructors.length; i++) {
+ refConstructors[i] = new RefConstructor(constructors[i]);
+ }
+ return refConstructors;
+ }
- /**
- * Finds and returns the first RefMethod match with given method name
- *
- * @param name
- * method its name
- * @return the first match, or if not found null
- */
- public RefMethod getMethod(String name) {
- return getMethod(name, null);
- }
+ /**
+ * Gets the class' methods
+ *
+ * @return all methods if an instance is provided, otherwise only static
+ * methods
+ */
+ public RefMethod[] getMethods() {
+ ArrayList methods = new ArrayList();
+ // add all static methods
+ for (Method m : clazz.getDeclaredMethods()) {
+ if (Modifier.isStatic(m.getModifiers())) {
+ methods.add(new RefMethod(m, instance));
+ }
+ }
+ if (this.instance != null) {
+ // add all non static methods
+ for (Method m : clazz.getDeclaredMethods()) {
+ if (!Modifier.isStatic(m.getModifiers())) {
+ methods.add(new RefMethod(m, instance));
+ }
+ }
+ }
+ return methods.toArray(new RefMethod[methods.size()]);
+ }
- /**
- * Finds a RefMethod in this RefClass
- *
- * @param name
- * the method its name
- * @param parameters
- * the method its parameters
- * @return the matched method or if not found null null
- */
- public RefMethod getMethod(String name, Class>[] parameters) {
- try {
- for (RefMethod method : getMethods()) {
- if (method.getName().equals(name)) {
- if (parameters == null || Arrays.equals(method.getParameterTypes(), parameters)) {
- return method;
- }
- }
- }
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Finds and returns the first RefMethod match with given method name
+ *
+ * @param name method its name
+ *
+ * @return the first match, or if not found null
+ */
+ public RefMethod getMethod(String name) {
+ return getMethod(name, null);
+ }
- public String toString() {
- if (this.instance != null) {
- return new StringBuilder().append(this.instance.toString())
- .append(" : ").append(this.clazz.toString()).toString();
- }
- return this.clazz.toString();
- }
+ /**
+ * Finds a RefMethod in this RefClass
+ *
+ * @param name the method its name
+ * @param parameters the method its parameters
+ *
+ * @return the matched method or if not found null null
+ */
+ public RefMethod getMethod(String name, Class>[] parameters) {
+ try {
+ for (RefMethod method : getMethods()) {
+ if (method.getName().equals(name)) {
+ if (parameters == null || Arrays.equals(method.getParameterTypes(), parameters)) {
+ return method;
+ }
+ }
+ }
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
+
+ public String toString() {
+ if (this.instance != null) {
+ return new StringBuilder().append(this.instance.toString())
+ .append(" : ").append(this.clazz.toString()).toString();
+ }
+ return this.clazz.toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/reflect/RefConstructor.java b/src/main/java/org/parabot/core/reflect/RefConstructor.java
index 18632ec..6534472 100644
--- a/src/main/java/org/parabot/core/reflect/RefConstructor.java
+++ b/src/main/java/org/parabot/core/reflect/RefConstructor.java
@@ -3,103 +3,101 @@ package org.parabot.core.reflect;
import java.lang.reflect.Constructor;
/**
- *
* A RefConstructor class represent a constructor method of a
* RefClass.
- *
+ *
* @author Everel
- *
*/
public class RefConstructor extends RefModifiers {
- private Constructor> constructor;
+ private Constructor> constructor;
- public RefConstructor(Constructor> constructor) {
- super(constructor.getModifiers());
- this.constructor = constructor;
- }
+ public RefConstructor(Constructor> constructor) {
+ super(constructor.getModifiers());
+ this.constructor = constructor;
+ }
- /**
- * Creates a new instance of this class by invoking this constructor
- *
- * @return the instance of the class
- */
- public RefClass newInstance() {
- return newInstance(new Object[] {});
- }
+ /**
+ * Creates a new instance of this class by invoking this constructor
+ *
+ * @return the instance of the class
+ */
+ public RefClass newInstance() {
+ return newInstance(new Object[]{});
+ }
- /**
- * Creates a new instance of this class by invoking this constructor
- *
- * @param args
- * the arguments for the constructor
- * @return the instance of the class
- */
- public RefClass newInstance(Object... args) {
- if (!constructor.isAccessible()) {
- constructor.setAccessible(true);
- }
- try {
- Object instance = constructor.newInstance(args);
- return new RefClass(instance);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Creates a new instance of this class by invoking this constructor
+ *
+ * @param args the arguments for the constructor
+ *
+ * @return the instance of the class
+ */
+ public RefClass newInstance(Object... args) {
+ if (!constructor.isAccessible()) {
+ constructor.setAccessible(true);
+ }
+ try {
+ Object instance = constructor.newInstance(args);
+ return new RefClass(instance);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Get the value of the accessible flag for this object.
- *
- * @return the value of the object's accessible flag
- */
- public boolean isAccessible() {
- return constructor.isAccessible();
- }
+ /**
+ * Get the value of the accessible flag for this object.
+ *
+ * @return the value of the object's accessible flag
+ */
+ public boolean isAccessible() {
+ return constructor.isAccessible();
+ }
- /**
- * Returns true if this constructor is a synthetic constructor;
- * returns false otherwise.
- *
- * @return true if this constructor is a synthetic constructor;
- * returns false otherwise
- */
- public boolean isSynthetic() {
- return constructor.isSynthetic();
- }
+ /**
+ * Returns true if this constructor is a synthetic constructor;
+ * returns false otherwise.
+ *
+ * @return true if this constructor is a synthetic constructor;
+ * returns false otherwise
+ */
+ public boolean isSynthetic() {
+ return constructor.isSynthetic();
+ }
- /**
- * Returns the name of the constructor.
- *
- * @return name of the constructor
- */
- public String getName() {
- return constructor.getName();
- }
+ /**
+ * Returns the name of the constructor.
+ *
+ * @return name of the constructor
+ */
+ public String getName() {
+ return constructor.getName();
+ }
- /**
- * Returns an array of the parameter types of this constructor
- *
- * @return an array of the parameter types of this constructor
- */
- public Class>[] getParameterTypes() {
- return constructor.getParameterTypes();
- }
+ /**
+ * Returns an array of the parameter types of this constructor
+ *
+ * @return an array of the parameter types of this constructor
+ */
+ public Class>[] getParameterTypes() {
+ return constructor.getParameterTypes();
+ }
- /**
- * Gets the java reflection API constructor representation
- *
- * @return constructor
- */
- public Constructor> getConstructor() {
- return this.constructor;
- }
+ /**
+ * Gets the java reflection API constructor representation
+ *
+ * @return constructor
+ */
+ public Constructor> getConstructor() {
+ return this.constructor;
+ }
- public String toGenericString() {
- return constructor.toGenericString();
- }
+ public String toGenericString() {
+ return constructor.toGenericString();
+ }
- public String toString() {
- return constructor.toString();
- }
+ public String toString() {
+ return constructor.toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/reflect/RefField.java b/src/main/java/org/parabot/core/reflect/RefField.java
index 68c884e..36a7b0b 100644
--- a/src/main/java/org/parabot/core/reflect/RefField.java
+++ b/src/main/java/org/parabot/core/reflect/RefField.java
@@ -4,378 +4,366 @@ import java.lang.reflect.Field;
import java.lang.reflect.Type;
/**
- *
* A RefField represents a field in a RefClass
- *
- * @author Everel
*
+ * @author Everel
*/
public class RefField extends RefModifiers {
- private Field field;
- private Object instance;
+ private Field field;
+ private Object instance;
- public RefField(Field field) {
- this(field, null);
- }
+ public RefField(Field field) {
+ this(field, null);
+ }
- public RefField(Field field, Object instance) {
- super(field.getModifiers());
- this.field = field;
- this.instance = instance;
- }
+ public RefField(Field field, Object instance) {
+ super(field.getModifiers());
+ this.field = field;
+ this.instance = instance;
+ }
- /**
- * Retrieves the field it's value as object
- *
- * @return the value of the field
- */
- public Object asObject() {
- if (instance == null && !isStatic()) {
- throw new IllegalStateException(
- "Non static field cannot be fetched without an instance");
- }
- try {
- if (!isAccessible()) {
- field.setAccessible(true);
- }
- return field.get(instance);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Retrieves the field it's value as object
+ *
+ * @return the value of the field
+ */
+ public Object asObject() {
+ if (instance == null && !isStatic()) {
+ throw new IllegalStateException(
+ "Non static field cannot be fetched without an instance");
+ }
+ try {
+ if (!isAccessible()) {
+ field.setAccessible(true);
+ }
+ return field.get(instance);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Retrieves the field value as an integer
- *
- * @return integer value of field
- */
- public int asInt() {
- return (int) asObject();
- }
+ /**
+ * Retrieves the field value as an integer
+ *
+ * @return integer value of field
+ */
+ public int asInt() {
+ return (int) asObject();
+ }
- /**
- * Retrieves the field value as a long
- *
- * @return long value of field
- */
- public long asLong() {
- return (long) asObject();
- }
+ /**
+ * Retrieves the field value as a long
+ *
+ * @return long value of field
+ */
+ public long asLong() {
+ return (long) asObject();
+ }
- /**
- * Retrieves the field value as an double
- *
- * @return double value of field
- */
- public double asDouble() {
- return (double) asObject();
- }
+ /**
+ * Retrieves the field value as an double
+ *
+ * @return double value of field
+ */
+ public double asDouble() {
+ return (double) asObject();
+ }
- /**
- * Retrieves the field value as a float
- *
- * @return float value of field
- */
- public float asFloat() {
- return (float) asObject();
- }
+ /**
+ * Retrieves the field value as a float
+ *
+ * @return float value of field
+ */
+ public float asFloat() {
+ return (float) asObject();
+ }
- /**
- * Retrieves the field value as a boolean
- *
- * @return boolean value of field
- */
- public boolean asBoolean() {
- return (boolean) asObject();
- }
+ /**
+ * Retrieves the field value as a boolean
+ *
+ * @return boolean value of field
+ */
+ public boolean asBoolean() {
+ return (boolean) asObject();
+ }
- /**
- * Retrieves the field value as a short
- *
- * @return short value of field
- */
- public short asShort() {
- return (short) asObject();
- }
+ /**
+ * Retrieves the field value as a short
+ *
+ * @return short value of field
+ */
+ public short asShort() {
+ return (short) asObject();
+ }
- /**
- * Retrieves the field value as a byte
- *
- * @return byte value of field
- */
- public byte asByte() {
- return (byte) asObject();
- }
+ /**
+ * Retrieves the field value as a byte
+ *
+ * @return byte value of field
+ */
+ public byte asByte() {
+ return (byte) asObject();
+ }
- /**
- * Retrieves the field value as a java/lang/String
- *
- * @return String value of field
- */
- public String asString() {
- return (String) asObject();
- }
+ /**
+ * Retrieves the field value as a java/lang/String
+ *
+ * @return String value of field
+ */
+ public String asString() {
+ return (String) asObject();
+ }
- /**
- * Retrieves the field value as a character
- *
- * @return char value of field
- */
- public char asChar() {
- return (char) asObject();
- }
+ /**
+ * Retrieves the field value as a character
+ *
+ * @return char value of field
+ */
+ public char asChar() {
+ return (char) asObject();
+ }
- /**
- * Sets the field value
- *
- * @param object
- * object to set
- */
- public void set(Object object) {
- if (instance == null && !isStatic()) {
- throw new IllegalStateException(
- "Non static field cannot be set without an instance");
- }
- if (!field.isAccessible()) {
- field.setAccessible(true);
- }
- try {
- field.set(instance, object);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
+ /**
+ * Sets the field value
+ *
+ * @param object object to set
+ */
+ public void set(Object object) {
+ if (instance == null && !isStatic()) {
+ throw new IllegalStateException(
+ "Non static field cannot be set without an instance");
+ }
+ if (!field.isAccessible()) {
+ field.setAccessible(true);
+ }
+ try {
+ field.set(instance, object);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
- /**
- * Sets the field integer value
- *
- * @param i
- * value to set
- */
- public void setInt(int i) {
- set(i);
- }
+ /**
+ * Sets the field integer value
+ *
+ * @param i value to set
+ */
+ public void setInt(int i) {
+ set(i);
+ }
- /**
- * Sets the field long value
- *
- * @param l
- * value to set
- */
- public void setLong(long l) {
- set(l);
- }
+ /**
+ * Sets the field long value
+ *
+ * @param l value to set
+ */
+ public void setLong(long l) {
+ set(l);
+ }
- /**
- * Sets the field double value
- *
- * @param d
- * value to set
- */
- public void setDouble(double d) {
- set(d);
- }
+ /**
+ * Sets the field double value
+ *
+ * @param d value to set
+ */
+ public void setDouble(double d) {
+ set(d);
+ }
- /**
- * Sets the field float value
- *
- * @param f
- * value to set
- */
- public void setFloat(float f) {
- set(f);
- }
+ /**
+ * Sets the field float value
+ *
+ * @param f value to set
+ */
+ public void setFloat(float f) {
+ set(f);
+ }
- /**
- * Sets the field boolean value
- *
- * @param b
- * value to set
- */
- public void setBoolean(boolean b) {
- set(b);
- }
+ /**
+ * Sets the field boolean value
+ *
+ * @param b value to set
+ */
+ public void setBoolean(boolean b) {
+ set(b);
+ }
- /**
- * Sets the field short value
- *
- * @param s
- * value to set
- */
- public void setShort(short s) {
- set(s);
- }
+ /**
+ * Sets the field short value
+ *
+ * @param s value to set
+ */
+ public void setShort(short s) {
+ set(s);
+ }
- /**
- * Sets the byte integer value
- *
- * @param b
- * value to set
- */
- public void setByte(byte b) {
- set(b);
- }
+ /**
+ * Sets the byte integer value
+ *
+ * @param b value to set
+ */
+ public void setByte(byte b) {
+ set(b);
+ }
- /**
- * Sets the field string value
- *
- * @param s
- * value to set
- */
- public void setString(String s) {
- set(s);
- }
+ /**
+ * Sets the field char value
+ *
+ * @param c value to set
+ */
+ public void setChar(char c) {
+ set(c);
+ }
- /**
- * Sets the field char value
- *
- * @param c
- * value to set
- */
- public void setChar(char c) {
- set(c);
- }
+ /**
+ * Gets the field type
+ *
+ * @return type of field
+ */
+ public Class> getType() {
+ return field.getType();
+ }
- /**
- * Gets the field type
- *
- * @return type of field
- */
- public Class> getType() {
- return field.getType();
- }
+ /**
+ * Gets the field type
+ *
+ * @return type of field
+ */
+ public org.objectweb.asm.Type getASMType() {
+ return org.objectweb.asm.Type.getType(getType());
+ }
- /**
- * Gets the field type
- *
- * @return type of field
- */
- public org.objectweb.asm.Type getASMType() {
- return org.objectweb.asm.Type.getType(getType());
- }
+ /**
+ * Gets the field description
+ *
+ * @return desc of field
+ */
+ public String getTypeDesc() {
+ return getASMType().getDescriptor();
+ }
- /**
- * Gets the field description
- *
- * @return desc of field
- */
- public String getTypeDesc() {
- return getASMType().getDescriptor();
- }
+ /**
+ * Gets the generic type of this field if any
+ *
+ * @return generic type
+ */
+ public Type getGenericType() {
+ return field.getGenericType();
+ }
- /**
- * Gets the generic type of this field if any
- *
- * @return generic type
- */
- public Type getGenericType() {
- return field.getGenericType();
- }
+ /**
+ * Determines if this field is an array
+ *
+ * @return true if this field is an array (type)
+ */
+ public boolean isArray() {
+ return getASMType().getSort() == org.objectweb.asm.Type.ARRAY;
+ }
- /**
- * Determines if this field is an array
- *
- * @return true if this field is an array (type)
- */
- public boolean isArray() {
- return getASMType().getSort() == org.objectweb.asm.Type.ARRAY;
- }
+ /**
+ * Returns the number of dimensions of this array type. This method should
+ * only be used for an array type.
+ *
+ * @return the number of dimensions of this array type
+ */
+ public int getArrayDimensions() {
+ return getASMType().getDimensions();
+ }
- /**
- * Returns the number of dimensions of this array type. This method should
- * only be used for an array type.
- *
- * @return the number of dimensions of this array type
- */
- public int getArrayDimensions() {
- return getASMType().getDimensions();
- }
+ /**
+ * Determines if field type is a primitive type
+ *
+ * @return true if the field is a primitive type, otherwise
+ * false
+ */
+ public boolean isPrimitiveType() {
+ return RefUtils.isPrimitive(getType());
+ }
- /**
- * Determines if field type is a primitive type
- *
- * @return true if the field is a primitive type, otherwise
- * false
- */
- public boolean isPrimitiveType() {
- return RefUtils.isPrimitive(getType());
- }
+ /**
+ * Determines if field type is a string type
+ *
+ * @return true if the field type is a string type, otherwise
+ * false
+ */
+ public boolean isString() {
+ return getType() == String.class;
+ }
- /**
- * Determines if field type is a string type
- *
- * @return true if the field type is a string type, otherwise
- * false
- */
- public boolean isString() {
- return getType() == String.class;
- }
+ /**
+ * Sets the field string value
+ *
+ * @param s value to set
+ */
+ public void setString(String s) {
+ set(s);
+ }
- /**
- * Returns true if this field represents an element of an
- * enumerated type; returns false otherwise.
- *
- * @return true if and only if this field represents an element
- * of an enumerated type.
- */
- public boolean isEnumConstants() {
- return field.isEnumConstant();
- }
+ /**
+ * Returns true if this field represents an element of an
+ * enumerated type; returns false otherwise.
+ *
+ * @return true if and only if this field represents an element
+ * of an enumerated type.
+ */
+ public boolean isEnumConstants() {
+ return field.isEnumConstant();
+ }
- /**
- * Get the value of the accessible flag for this object.
- *
- * @return the value of the object's accessible flag
- */
- public boolean isAccessible() {
- return field.isAccessible();
- }
+ /**
+ * Get the value of the accessible flag for this object.
+ *
+ * @return the value of the object's accessible flag
+ */
+ public boolean isAccessible() {
+ return field.isAccessible();
+ }
- /**
- * Returns true if this field is a synthetic field; returns
- * false otherwise.
- *
- * @return true if this field is a synthetic field; returns
- * false otherwise
- */
- public boolean isSynthetic() {
- return field.isSynthetic();
- }
+ /**
+ * Returns true if this field is a synthetic field; returns
+ * false otherwise.
+ *
+ * @return true if this field is a synthetic field; returns
+ * false otherwise
+ */
+ public boolean isSynthetic() {
+ return field.isSynthetic();
+ }
- /**
- * Returns the name of the field.
- *
- * @return name of the field
- */
- public String getName() {
- return field.getName();
- }
+ /**
+ * Returns the name of the field.
+ *
+ * @return name of the field
+ */
+ public String getName() {
+ return field.getName();
+ }
- /**
- * Gets the java reflection API field representation
- *
- * @return field
- */
- public Field getField() {
- return field;
- }
-
- /**
- * Gets the declaring RefClass of this field
- * @return RefClass holding this field
- */
- public RefClass getOwner() {
- return new RefClass(field.getDeclaringClass(), instance);
- }
+ /**
+ * Gets the java reflection API field representation
+ *
+ * @return field
+ */
+ public Field getField() {
+ return field;
+ }
- public String toGenericString() {
- return field.toGenericString();
- }
+ /**
+ * Gets the declaring RefClass of this field
+ *
+ * @return RefClass holding this field
+ */
+ public RefClass getOwner() {
+ return new RefClass(field.getDeclaringClass(), instance);
+ }
- public String toString() {
- return field.toString();
- }
-
+ public String toGenericString() {
+ return field.toGenericString();
+ }
+
+ public String toString() {
+ return field.toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/reflect/RefMethod.java b/src/main/java/org/parabot/core/reflect/RefMethod.java
index 2c3aac8..8eafb62 100644
--- a/src/main/java/org/parabot/core/reflect/RefMethod.java
+++ b/src/main/java/org/parabot/core/reflect/RefMethod.java
@@ -3,150 +3,147 @@ package org.parabot.core.reflect;
import java.lang.reflect.Method;
/**
- *
* A RefMethod class represent a method of a RefClass.
- *
+ *
* @author Everel
- *
*/
public class RefMethod extends RefModifiers {
- private Method method;
- private Object instance;
+ private Method method;
+ private Object instance;
- public RefMethod(Method method) {
- this(method, null);
- }
+ public RefMethod(Method method) {
+ this(method, null);
+ }
- public RefMethod(Method method, Object instance) {
- super(method.getModifiers());
- this.method = method;
- this.instance = instance;
- }
+ public RefMethod(Method method, Object instance) {
+ super(method.getModifiers());
+ this.method = method;
+ this.instance = instance;
+ }
- /**
- * Get the value of the accessible flag for this object.
- *
- * @return the value of the object's accessible flag
- */
- public boolean isAccessible() {
- return method.isAccessible();
- }
+ /**
+ * Get the value of the accessible flag for this object.
+ *
+ * @return the value of the object's accessible flag
+ */
+ public boolean isAccessible() {
+ return method.isAccessible();
+ }
- /**
- * Determines if this method is a bridge method.
- *
- * @return true if this method is a bridge method, otherwise
- * false
- */
- public boolean isBridge() {
- return method.isBridge();
- }
+ /**
+ * Determines if this method is a bridge method.
+ *
+ * @return true if this method is a bridge method, otherwise
+ * false
+ */
+ public boolean isBridge() {
+ return method.isBridge();
+ }
- /**
- * Determines if this method can take a variable amount of arguments
- *
- * @return true if this method can take a variable amount of
- * arguments
- */
- public boolean isVarArgs() {
- return method.isVarArgs();
- }
+ /**
+ * Determines if this method can take a variable amount of arguments
+ *
+ * @return true if this method can take a variable amount of
+ * arguments
+ */
+ public boolean isVarArgs() {
+ return method.isVarArgs();
+ }
- /**
- * Returns true if this method is a synthetic method; returns
- * false otherwise.
- *
- * @return true if this method is a synthetic method; returns
- * false otherwise
- */
- public boolean isSynthetic() {
- return method.isSynthetic();
- }
+ /**
+ * Returns true if this method is a synthetic method; returns
+ * false otherwise.
+ *
+ * @return true if this method is a synthetic method; returns
+ * false otherwise
+ */
+ public boolean isSynthetic() {
+ return method.isSynthetic();
+ }
- /**
- * Returns the name of the method.
- *
- * @return name of the method
- */
- public String getName() {
- return method.getName();
- }
+ /**
+ * Returns the name of the method.
+ *
+ * @return name of the method
+ */
+ public String getName() {
+ return method.getName();
+ }
- /**
- * Returns an array of the parameter types of this method
- *
- * @return an array of the parameter types of this method
- */
- public Class>[] getParameterTypes() {
- return method.getParameterTypes();
- }
+ /**
+ * Returns an array of the parameter types of this method
+ *
+ * @return an array of the parameter types of this method
+ */
+ public Class>[] getParameterTypes() {
+ return method.getParameterTypes();
+ }
- /**
- * Gets the return type of this class
- *
- * @return return type of this class
- */
- public Class> getReturnType() {
- return method.getReturnType();
- }
+ /**
+ * Gets the return type of this class
+ *
+ * @return return type of this class
+ */
+ public Class> getReturnType() {
+ return method.getReturnType();
+ }
- /**
- * Gets the return type of this class
- *
- * @return return type of this class
- */
- public org.objectweb.asm.Type getASMReturnType() {
- return org.objectweb.asm.Type.getType(getReturnType());
- }
+ /**
+ * Gets the return type of this class
+ *
+ * @return return type of this class
+ */
+ public org.objectweb.asm.Type getASMReturnType() {
+ return org.objectweb.asm.Type.getType(getReturnType());
+ }
- /**
- * Gets the java reflection API method representation
- *
- * @return constructor
- */
- public Method getMethod() {
- return this.method;
- }
+ /**
+ * Gets the java reflection API method representation
+ *
+ * @return constructor
+ */
+ public Method getMethod() {
+ return this.method;
+ }
- /**
- * Invokes the method and returns it returned object
- *
- * @return object returned by the method
- */
- public Object invoke() {
- return invoke(new Object[] {});
- }
+ /**
+ * Invokes the method and returns it returned object
+ *
+ * @return object returned by the method
+ */
+ public Object invoke() {
+ return invoke(new Object[]{});
+ }
- /**
- *
- * Invokes the method and returns it returned object
- *
- * @param args
- * arguments for the invokable method
- * @return object returned by the method
- */
- public Object invoke(Object... args) {
- if (!isStatic() && instance == null) {
- throw new IllegalStateException(
- "Can not invoke non static method without an instance.");
- }
- if(!isAccessible()) {
- method.setAccessible(true);
- }
- try {
- Object retObject = method.invoke(instance, args);
- return retObject;
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return null;
- }
+ /**
+ * Invokes the method and returns it returned object
+ *
+ * @param args arguments for the invokable method
+ *
+ * @return object returned by the method
+ */
+ public Object invoke(Object... args) {
+ if (!isStatic() && instance == null) {
+ throw new IllegalStateException(
+ "Can not invoke non static method without an instance.");
+ }
+ if (!isAccessible()) {
+ method.setAccessible(true);
+ }
+ try {
+ Object retObject = method.invoke(instance, args);
+ return retObject;
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ return null;
+ }
- public String toGenericString() {
- return method.toGenericString();
- }
+ public String toGenericString() {
+ return method.toGenericString();
+ }
- public String toString() {
- return method.toString();
- }
+ public String toString() {
+ return method.toString();
+ }
}
diff --git a/src/main/java/org/parabot/core/reflect/RefModifiers.java b/src/main/java/org/parabot/core/reflect/RefModifiers.java
index 82daffa..fd0e9b0 100644
--- a/src/main/java/org/parabot/core/reflect/RefModifiers.java
+++ b/src/main/java/org/parabot/core/reflect/RefModifiers.java
@@ -3,75 +3,73 @@ package org.parabot.core.reflect;
import java.lang.reflect.Modifier;
/**
- *
* @author Everel
- *
*/
public class RefModifiers {
- private int modifiers;
+ private int modifiers;
- public RefModifiers() {
+ public RefModifiers() {
- }
+ }
- public RefModifiers(int modifiers) {
- setModifiers(modifiers);
- }
+ public RefModifiers(int modifiers) {
+ setModifiers(modifiers);
+ }
- public void setModifiers(int modifiers) {
- this.modifiers = modifiers;
- }
+ public int getModifiers() {
+ return this.modifiers;
+ }
- public int getModifiers() {
- return this.modifiers;
- }
+ public void setModifiers(int modifiers) {
+ this.modifiers = modifiers;
+ }
- public boolean isStatic() {
- return Modifier.isStatic(modifiers);
- }
+ public boolean isStatic() {
+ return Modifier.isStatic(modifiers);
+ }
- public boolean isAbstract() {
- return Modifier.isAbstract(modifiers);
- }
+ public boolean isAbstract() {
+ return Modifier.isAbstract(modifiers);
+ }
- public boolean isFinal() {
- return Modifier.isFinal(modifiers);
- }
+ public boolean isFinal() {
+ return Modifier.isFinal(modifiers);
+ }
- public boolean isInterface() {
- return Modifier.isInterface(modifiers);
- }
+ public boolean isInterface() {
+ return Modifier.isInterface(modifiers);
+ }
- public boolean isNative() {
- return Modifier.isNative(modifiers);
- }
+ public boolean isNative() {
+ return Modifier.isNative(modifiers);
+ }
- public boolean isPrivate() {
- return Modifier.isPrivate(modifiers);
- }
+ public boolean isPrivate() {
+ return Modifier.isPrivate(modifiers);
+ }
- public boolean isProtected() {
- return Modifier.isProtected(modifiers);
- }
+ public boolean isProtected() {
+ return Modifier.isProtected(modifiers);
+ }
- public boolean isPublic() {
- return Modifier.isPublic(modifiers);
- }
+ public boolean isPublic() {
+ return Modifier.isPublic(modifiers);
+ }
- public boolean isStrict() {
- return Modifier.isStrict(modifiers);
- }
+ public boolean isStrict() {
+ return Modifier.isStrict(modifiers);
+ }
- public boolean isSynchronized() {
- return Modifier.isSynchronized(modifiers);
- }
+ public boolean isSynchronized() {
+ return Modifier.isSynchronized(modifiers);
+ }
- public boolean isTransient() {
- return Modifier.isTransient(modifiers);
- }
+ public boolean isTransient() {
+ return Modifier.isTransient(modifiers);
+ }
- public boolean isVolatile() {
- return Modifier.isVolatile(modifiers);
- }
+ public boolean isVolatile() {
+ return Modifier.isVolatile(modifiers);
+ }
}
diff --git a/src/main/java/org/parabot/core/reflect/RefUtils.java b/src/main/java/org/parabot/core/reflect/RefUtils.java
index 8f251d9..53bb5ba 100644
--- a/src/main/java/org/parabot/core/reflect/RefUtils.java
+++ b/src/main/java/org/parabot/core/reflect/RefUtils.java
@@ -5,19 +5,17 @@ import java.util.HashSet;
import java.util.Set;
/**
- *
* @author Everel
- *
*/
public class RefUtils {
- public static final Set> PRIMITIVE_TYPES = new HashSet>(
- Arrays.asList(Boolean.class, Character.class, Byte.class,
- Short.class, Integer.class, Long.class, Float.class,
- Double.class, Void.class));
+ public static final Set> PRIMITIVE_TYPES = new HashSet>(
+ Arrays.asList(Boolean.class, Character.class, Byte.class,
+ Short.class, Integer.class, Long.class, Float.class,
+ Double.class, Void.class));
- public static boolean isPrimitive(Class> clazz) {
- return PRIMITIVE_TYPES.contains(clazz);
- }
+ public static boolean isPrimitive(Class> clazz) {
+ return PRIMITIVE_TYPES.contains(clazz);
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/BotDialog.java b/src/main/java/org/parabot/core/ui/BotDialog.java
index 15634bf..d3c903b 100644
--- a/src/main/java/org/parabot/core/ui/BotDialog.java
+++ b/src/main/java/org/parabot/core/ui/BotDialog.java
@@ -1,68 +1,64 @@
package org.parabot.core.ui;
-import java.awt.Color;
-import java.awt.Dimension;
-
-import javax.swing.JDialog;
-
import org.parabot.core.ui.components.PaintComponent;
import org.parabot.environment.OperatingSystem;
+import javax.swing.*;
+import java.awt.*;
+
/**
- *
* @author Everel
- *
*/
public class BotDialog extends JDialog {
- private static final long serialVersionUID = 521800552287194673L;
- private static BotDialog instance;
+ private static final long serialVersionUID = 521800552287194673L;
+ private static BotDialog instance;
- private BotDialog(BotUI botUI) {
- super(botUI);
+ private BotDialog(BotUI botUI) {
+ super(botUI);
- botUI.setDialog(this);
- setUndecorated(true);
- getRootPane().setOpaque(false);
- if (!OperatingSystem.getOS().equals(OperatingSystem.OTHER)) {
- try {
- setBackground(new Color(0, 0, 0, 0));
- } catch (UnsupportedOperationException e) {
- //My "fix" for the perpixel errors some user have when using VPSes
- if (e.getMessage().contains("PERPIXEL_TRANS")) {
- System.err
- .println("WARNING: We were unable to set a translucent background!"
- + "\n\tThis generally occurs with old/outdated graphics drivers. Please consider updating them if possible."
- + "\n\tParabot will still attempt to run, however some GUI elements may or may not function.");
- }
- }
- }
- setFocusableWindowState(true);
- setPreferredSize(botUI.getSize());
- setSize(botUI.getSize());
- setVisible(true);
- setContentPane(PaintComponent.getInstance(botUI.getSize()));
- botUI.setVisible(true);
+ botUI.setDialog(this);
+ setUndecorated(true);
+ getRootPane().setOpaque(false);
+ if (!OperatingSystem.getOS().equals(OperatingSystem.OTHER)) {
+ try {
+ setBackground(new Color(0, 0, 0, 0));
+ } catch (UnsupportedOperationException e) {
+ //My "fix" for the perpixel errors some user have when using VPSes
+ if (e.getMessage().contains("PERPIXEL_TRANS")) {
+ System.err
+ .println("WARNING: We were unable to set a translucent background!"
+ + "\n\tThis generally occurs with old/outdated graphics drivers. Please consider updating them if possible."
+ + "\n\tParabot will still attempt to run, however some GUI elements may or may not function.");
+ }
+ }
+ }
+ setFocusableWindowState(true);
+ setPreferredSize(botUI.getSize());
+ setSize(botUI.getSize());
+ setVisible(true);
+ setContentPane(PaintComponent.getInstance(botUI.getSize()));
+ botUI.setVisible(true);
- }
+ }
- public void setDimensions(Dimension dimension) {
- setUndecorated(true);
- getRootPane().setOpaque(false);
- setBackground(new Color(0, 0, 0, 0));
- setFocusableWindowState(true);
- setPreferredSize(dimension);
- setSize(dimension);
- setVisible(true);
- setContentPane(PaintComponent.getInstance());
- PaintComponent.getInstance().setDimensions(dimension);
- }
+ public static BotDialog getInstance(BotUI botUI) {
+ return instance == null ? instance = new BotDialog(botUI) : instance;
+ }
- public static BotDialog getInstance(BotUI botUI) {
- return instance == null ? instance = new BotDialog(botUI) : instance;
- }
+ public static BotDialog getInstance() {
+ return getInstance(null);
+ }
- public static BotDialog getInstance() {
- return getInstance(null);
- }
+ public void setDimensions(Dimension dimension) {
+ setUndecorated(true);
+ getRootPane().setOpaque(false);
+ setBackground(new Color(0, 0, 0, 0));
+ setFocusableWindowState(true);
+ setPreferredSize(dimension);
+ setSize(dimension);
+ setVisible(true);
+ setContentPane(PaintComponent.getInstance());
+ PaintComponent.getInstance().setDimensions(dimension);
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/BotUI.java b/src/main/java/org/parabot/core/ui/BotUI.java
index c33b6bd..90b384f 100644
--- a/src/main/java/org/parabot/core/ui/BotUI.java
+++ b/src/main/java/org/parabot/core/ui/BotUI.java
@@ -31,15 +31,14 @@ import java.util.ArrayList;
public class BotUI extends JFrame implements ActionListener, ComponentListener, WindowListener {
private static final long serialVersionUID = -2126184292879805519L;
- private static BotUI instance;
+ private static BotUI instance;
private static JDialog dialog;
private JMenuBar menuBar;
- private JMenu features, scripts, file;
+ private JMenu features, scripts, file;
private JMenuItem run, pause, stop, cacheClear, notifications;
private boolean runScript, pauseScript;
-
public BotUI(String username, String password) {
if (instance != null) {
throw new IllegalStateException("BotUI already created");
@@ -75,7 +74,6 @@ public class BotUI extends JFrame implements ActionListener, ComponentListener,
return instance;
}
-
private void createMenu() {
menuBar = new JMenuBar();
@@ -84,17 +82,17 @@ public class BotUI extends JFrame implements ActionListener, ComponentListener,
features = new JMenu("Features");
JMenuItem screenshot = new JMenuItem("Create screenshot");
- JMenuItem proxy = new JMenuItem("Network");
- JMenuItem randoms = new JMenuItem("Randoms");
- JMenuItem dialog = new JCheckBoxMenuItem("Disable dialog");
- JMenuItem logger = new JCheckBoxMenuItem("Logger");
+ JMenuItem proxy = new JMenuItem("Network");
+ JMenuItem randoms = new JMenuItem("Randoms");
+ JMenuItem dialog = new JCheckBoxMenuItem("Disable dialog");
+ JMenuItem logger = new JCheckBoxMenuItem("Logger");
if (!OperatingSystem.getOS().equals(OperatingSystem.WINDOWS)) {
dialog.setSelected(true);
}
JMenuItem explorer = new JMenuItem("Reflection explorer");
- JMenuItem exit = new JMenuItem("Exit");
+ JMenuItem exit = new JMenuItem("Exit");
run = new JMenuItem("Run");
run.setIcon(new ImageIcon(Images.getResource("/storage/images/run.png")));
@@ -146,7 +144,6 @@ public class BotUI extends JFrame implements ActionListener, ComponentListener,
menuBar.add(scripts);
menuBar.add(features);
-
setJMenuBar(menuBar);
}
@@ -159,12 +156,15 @@ public class BotUI extends JFrame implements ActionListener, ComponentListener,
switch (command) {
case "Create screenshot":
try {
- Robot robot = new Robot();
- Rectangle parabotScreen = new Rectangle((int) getLocation().getX(), (int) getLocation().getY() + (menuBar.getHeight() + features.getHeight()), getWidth(), getHeight());
- BufferedImage image = robot.createScreenCapture(parabotScreen);
- String randString = StringUtils.randomString(10);
- boolean search = true;
- boolean duplicate = false;
+ Robot robot = new Robot();
+ int menuBarHeight = menuBar.getHeight() + file.getHeight();
+ Rectangle parabotScreen = new Rectangle(
+ (int) getLocation().getX(), (int) getLocation().getY() + menuBarHeight,
+ getWidth(), getHeight() - menuBarHeight);
+ BufferedImage image = robot.createScreenCapture(parabotScreen);
+ String randString = StringUtils.randomString(10);
+ boolean search = true;
+ boolean duplicate = false;
while (search) {
File[] files;
if ((files = Directories.getScreenshotDir().listFiles()) != null) {
diff --git a/src/main/java/org/parabot/core/ui/Logger.java b/src/main/java/org/parabot/core/ui/Logger.java
index f263886..ec19797 100644
--- a/src/main/java/org/parabot/core/ui/Logger.java
+++ b/src/main/java/org/parabot/core/ui/Logger.java
@@ -11,14 +11,14 @@ import java.awt.event.ActionListener;
* @author JKetelaar
*/
public class Logger extends JPanel {
- private static final long serialVersionUID = 1L;
- private static Logger instance;
- private final DefaultListModel model;
- private final JList list;
+ private static final long serialVersionUID = 1L;
+ private static Logger instance;
+ private final DefaultListModel model;
+ private final JList list;
private boolean clearable;
- private Logger(){
+ private Logger() {
setLayout(new BorderLayout());
list = new JList<>();
@@ -41,38 +41,24 @@ public class Logger extends JPanel {
list.setModel(model);
setPreferredSize(new Dimension((int) GamePanel.getInstance().getPreferredSize().getWidth(), 150));
model.addElement("Logger initialised");
-
+
setVisible(false);
}
- private ListCellRenderer super String> getRenderer() {
- return new DefaultListCellRenderer(){
- private static final long serialVersionUID = -3589192791360628745L;
-
- @Override
- public Component getListCellRendererComponent(JList> list,
- Object value, int index, boolean isSelected,
- boolean cellHasFocus) {
- JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
- listCellRendererComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0,Color.BLACK));
- return listCellRendererComponent;
- }
- };
- }
-
public static Logger getInstance() {
return instance == null ? instance = new Logger() : instance;
}
/**
* Logs a message in the logger ui
+ *
* @param message
* @param uliratha Determines if this should be sent to the uliratha server
*/
- public static void addMessage(String message, boolean uliratha){
+ public static void addMessage(String message, boolean uliratha) {
instance.model.addElement(message);
- if (uliratha){
+ if (uliratha) {
// TODO: Implement latest Uliratha
}
@@ -80,7 +66,7 @@ public class Logger extends JPanel {
if (last >= 0) {
instance.list.ensureIndexIsVisible(last);
}
- if (instance.list.getModel().getSize() > 100 && instance.list.getModel().getElementAt(0) != null){
+ if (instance.list.getModel().getSize() > 100 && instance.list.getModel().getElementAt(0) != null) {
instance.model.remove(0);
}
}
@@ -88,14 +74,29 @@ public class Logger extends JPanel {
/**
* @param message
*/
- public static void addMessage(String message){
+ public static void addMessage(String message) {
addMessage(message, true);
}
- protected static void clearLogger(){
+ protected static void clearLogger() {
instance.model.clear();
}
+ private ListCellRenderer super String> getRenderer() {
+ return new DefaultListCellRenderer() {
+ private static final long serialVersionUID = -3589192791360628745L;
+
+ @Override
+ public Component getListCellRendererComponent(JList> list,
+ Object value, int index, boolean isSelected,
+ boolean cellHasFocus) {
+ JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
+ listCellRendererComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
+ return listCellRendererComponent;
+ }
+ };
+ }
+
public boolean isClearable() {
return clearable;
}
diff --git a/src/main/java/org/parabot/core/ui/LoginUI.java b/src/main/java/org/parabot/core/ui/LoginUI.java
index 3bf6b35..f93b723 100644
--- a/src/main/java/org/parabot/core/ui/LoginUI.java
+++ b/src/main/java/org/parabot/core/ui/LoginUI.java
@@ -17,156 +17,153 @@ import java.io.IOException;
import java.net.URI;
/**
- *
* Users must login with their parabot account through this LoginUI class
- *
- * @author Everel
*
+ * @author Everel
*/
public class LoginUI extends JFrame {
- private static final long serialVersionUID = 2032832552863466297L;
- private static LoginUI instance;
- private static AccountManager manager;
-
- private JTextField txtUsername;
- private JPasswordField txtPassword;
- private JButton cmdLogin;
- private JButton cmdRegister;
+ private static final long serialVersionUID = 2032832552863466297L;
+ private static LoginUI instance;
+ private static AccountManager manager;
+ private JTextField txtUsername;
+ private JPasswordField txtPassword;
+ private JButton cmdLogin;
+ private JButton cmdRegister;
- public void attemptLogin() {
- String username = txtUsername.getText();
- String password = new String(txtPassword.getPassword());
+ public LoginUI(String username, String password) {
+ instance = this;
+ attempt(username, password);
+ }
- if (username.length() > 0 && password.length() > 0) {
- if (manager.login(username, password, false)) {
- Core.verbose("Logged in.");
- instance.dispose();
- Core.verbose("Running server selector.");
- ServerSelector.getInstance();
- } else {
- Core.verbose("Failed to log in.");
- UILog.log("Error", "Incorrect username or password. Have you tried logging into http://bdn.parabot.org/account/", JOptionPane.ERROR_MESSAGE);
- }
- }
- }
+ public LoginUI() {
+ instance = this;
- private void attempt(String user, String pass) {
- Core.verbose("Logging in...");
- if (manager.login(user, pass, false)) {
- Core.verbose("Logged in.");
- instance.dispose();
- Core.verbose("Running server selector.");
- ServerSelector.getInstance();
- } else {
- Core.verbose("Failed to log in.");
- UILog.log("Error", "Incorrect username or password. Have you tried logging into http://bdn.parabot.org/account/", JOptionPane.ERROR_MESSAGE);
- }
+ this.setTitle("Login");
+ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ this.setLocationByPlatform(true);
+ this.setLayout(new BorderLayout());
+ this.setResizable(false);
- }
+ SwingUtil.setParabotIcons(this);
- public LoginUI(String username, String password) {
- instance = this;
- attempt(username, password);
- }
+ int w = 250;
+ int x = 8;
+ int y = 64;
- public LoginUI() {
- instance = this;
+ JPanel panel = new JPanel() {
+ private static final long serialVersionUID = 2258761648532714183L;
- this.setTitle("Login");
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLocationByPlatform(true);
- this.setLayout(new BorderLayout());
- this.setResizable(false);
-
- SwingUtil.setParabotIcons(this);
+ @Override
+ public void paintComponent(Graphics g) {
+ super.paintComponent(g);
+ ((Graphics2D) g).setRenderingHint(
+ RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BICUBIC);
+ g.drawImage(Images
+ .getResource("/storage/images/para.png"),
+ 0, 8, 250, 45, null);
+ }
+ };
+ panel.setLayout(null);
- int w = 250;
- int x = 8;
- int y = 64;
+ txtUsername = new JTextField("");
+ txtUsername.setBounds(x, y, w - (x << 1), 26);
+ txtUsername.addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if (e.getKeyCode() == 10 || e.getKeyCode() == 13) {
+ txtPassword.requestFocus();
+ }
+ }
+ });
- JPanel panel = new JPanel() {
- private static final long serialVersionUID = 2258761648532714183L;
+ y += 30;
- @Override
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- ((Graphics2D) g).setRenderingHint(
- RenderingHints.KEY_INTERPOLATION,
- RenderingHints.VALUE_INTERPOLATION_BICUBIC);
- g.drawImage(Images
- .getResource("/storage/images/para.png"),
- 0, 8, 250, 45, null);
- }
- };
- panel.setLayout(null);
+ txtPassword = new JPasswordField("");
+ txtPassword.setBounds(x, y, w - (x << 1), 26);
+ txtPassword.addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if (e.getKeyCode() == 10 || e.getKeyCode() == 13) {
+ attemptLogin();
+ }
+ }
+ });
- txtUsername = new JTextField("");
- txtUsername.setBounds(x, y, w - (x << 1), 26);
- txtUsername.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.getKeyCode() == 10 || e.getKeyCode() == 13) {
- txtPassword.requestFocus();
- }
- }
- });
+ y += 30;
- y += 30;
+ cmdLogin = new JButton("Login");
+ cmdLogin.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent arg0) {
+ attemptLogin();
+ }
+ });
+ cmdLogin.setBounds(x, y, (w - (x << 1)) / 2 - 8, 24);
- txtPassword = new JPasswordField("");
- txtPassword.setBounds(x, y, w - (x << 1), 26);
- txtPassword.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.getKeyCode() == 10 || e.getKeyCode() == 13) {
- attemptLogin();
- }
- }
- });
+ cmdRegister = new JButton("Register");
+ cmdRegister.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent arg0) {
+ URI uri = URI
+ .create(Configuration.REGISTRATION_PAGE);
+ try {
+ Desktop.getDesktop().browse(uri);
+ } catch (IOException e1) {
+ JOptionPane.showMessageDialog(null, "Connection Error",
+ "Error", JOptionPane.ERROR_MESSAGE);
+ e1.printStackTrace();
+ }
+ }
+ });
+ cmdRegister.setBounds(x + (w - (x << 1)) / 2 + 8, y,
+ (w - (x << 1)) / 2 - 8, 24);
- y += 30;
+ panel.add(txtUsername);
+ panel.add(txtPassword);
+ panel.add(cmdLogin);
+ panel.add(cmdRegister);
- cmdLogin = new JButton("Login");
- cmdLogin.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent arg0) {
- attemptLogin();
- }
- });
- cmdLogin.setBounds(x, y, (w - (x << 1)) / 2 - 8, 24);
+ this.add(panel, BorderLayout.CENTER);
- cmdRegister = new JButton("Register");
- cmdRegister.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent arg0) {
- URI uri = URI
- .create(Configuration.REGISTRATION_PAGE);
- try {
- Desktop.getDesktop().browse(uri);
- } catch (IOException e1) {
- JOptionPane.showMessageDialog(null, "Connection Error",
- "Error", JOptionPane.ERROR_MESSAGE);
- e1.printStackTrace();
- }
- }
- });
- cmdRegister.setBounds(x + (w - (x << 1)) / 2 + 8, y,
- (w - (x << 1)) / 2 - 8, 24);
+ this.setVisible(true);
+ this.requestFocus();
- panel.add(txtUsername);
- panel.add(txtPassword);
- panel.add(cmdLogin);
- panel.add(cmdRegister);
+ this.setSize(255, 182);
+ this.setLocationRelativeTo(null);
- this.add(panel, BorderLayout.CENTER);
+ }
- this.setVisible(true);
- this.requestFocus();
+ public void attemptLogin() {
+ String username = txtUsername.getText();
+ String password = new String(txtPassword.getPassword());
- this.setSize(255, 182);
- this.setLocationRelativeTo(null);
+ if (username.length() > 0 && password.length() > 0) {
+ if (manager.login(username, password, false)) {
+ Core.verbose("Logged in.");
+ instance.dispose();
+ Core.verbose("Running server selector.");
+ ServerSelector.getInstance();
+ } else {
+ Core.verbose("Failed to log in.");
+ UILog.log("Error", "Incorrect username or password. Have you tried logging into http://bdn.parabot.org/account/", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+ }
- }
+ private void attempt(String user, String pass) {
+ Core.verbose("Logging in...");
+ if (manager.login(user, pass, false)) {
+ Core.verbose("Logged in.");
+ instance.dispose();
+ Core.verbose("Running server selector.");
+ ServerSelector.getInstance();
+ } else {
+ Core.verbose("Failed to log in.");
+ UILog.log("Error", "Incorrect username or password. Have you tried logging into http://bdn.parabot.org/account/", JOptionPane.ERROR_MESSAGE);
+ }
+
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/NetworkUI.java b/src/main/java/org/parabot/core/ui/NetworkUI.java
index 4905575..df001ce 100644
--- a/src/main/java/org/parabot/core/ui/NetworkUI.java
+++ b/src/main/java/org/parabot/core/ui/NetworkUI.java
@@ -27,17 +27,17 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
private static NetworkUI instance;
private JComboBox proxyType;
- private JTextField proxyHost;
- private IntTextField proxyPort;
- private JButton submitButton;
+ private JTextField proxyHost;
+ private IntTextField proxyPort;
+ private JButton submitButton;
private JList[] macList;
- private JScrollPane[] macScrollList;
+ private JScrollPane[] macScrollList;
- private JCheckBox authCheckBox;
- private JTextField authUsername;
+ private JCheckBox authCheckBox;
+ private JTextField authUsername;
private JPasswordField authPassword;
- private JButton randomize;
+ private JButton randomize;
private NetworkUI() {
initGUI();
@@ -50,8 +50,9 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
@Override
public void setVisible(boolean b) {
BotUI.getInstance().setEnabled(!b);
- if (ProxySocket.getProxyAddress() != null)
+ if (ProxySocket.getProxyAddress() != null) {
proxyHost.setText(ProxySocket.getProxyAddress().getHostName());
+ }
proxyPort.setText("" + ProxySocket.getProxyPort());
proxyType.setSelectedItem(ProxySocket.getProxyType());
authCheckBox.setSelected(ProxySocket.auth);
@@ -92,10 +93,10 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
randomize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- Random rand = new Random();
+ Random rand = new Random();
byte[] macAddr = new byte[6];
rand.nextBytes(macAddr);
- macAddr[0] = (byte)(macAddr[0] & (byte)254);
+ macAddr[0] = (byte) (macAddr[0] & (byte) 254);
for (int i = 0; i < macAddr.length; i++) {
int value = macAddr[i] & 0xFF;
macList[i].setSelectedIndex(value);
@@ -104,7 +105,6 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
}
});
-
authCheckBox = new JCheckBox("Auth");
authCheckBox.setSelected(ProxySocket.auth);
authCheckBox.addActionListener(this);
@@ -262,9 +262,10 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
.setLogin(username, password);
byte[] mac = new byte[macList.length];
- for (int i = 0; i < mac.length; i++)
+ for (int i = 0; i < mac.length; i++) {
mac[i] = (byte) Short.parseShort(
(String) macList[i].getSelectedValue(), 16);
+ }
NetworkInterface.setMac(mac);
try {
@@ -277,8 +278,8 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
}
}
ProxyType type = (ProxyType) proxyType.getSelectedItem();
- String host = proxyHost.getText();
- int port = proxyPort.getValue();
+ String host = proxyHost.getText();
+ int port = proxyPort.getValue();
ProxySocket.setProxy(type, host, port);
UILog.log("Info", "Network settings have been set!");
@@ -340,8 +341,9 @@ public class NetworkUI extends JFrame implements KeyListener, ActionListener,
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
- if (str == null)
+ if (str == null) {
return;
+ }
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str
+ oldString.substring(offs);
diff --git a/src/main/java/org/parabot/core/ui/RandomUI.java b/src/main/java/org/parabot/core/ui/RandomUI.java
index 2581266..7aae7a7 100644
--- a/src/main/java/org/parabot/core/ui/RandomUI.java
+++ b/src/main/java/org/parabot/core/ui/RandomUI.java
@@ -16,7 +16,7 @@ public class RandomUI implements ActionListener {
private static RandomUI instance;
- private JFrame frame;
+ private JFrame frame;
private ArrayList checkBoxes;
public static RandomUI getInstance() {
diff --git a/src/main/java/org/parabot/core/ui/ReflectUI.java b/src/main/java/org/parabot/core/ui/ReflectUI.java
index 32d7f59..a35ba39 100644
--- a/src/main/java/org/parabot/core/ui/ReflectUI.java
+++ b/src/main/java/org/parabot/core/ui/ReflectUI.java
@@ -27,11 +27,11 @@ import java.util.HashMap;
*/
public class ReflectUI extends JFrame {
private static final long serialVersionUID = 98565034137367257L;
- private JTree tree;
+ private JTree tree;
private DefaultMutableTreeNode root;
- private DefaultTreeModel model;
- private JEditorPane basicInfoPane;
- private JEditorPane selectionInfoPane;
+ private DefaultTreeModel model;
+ private JEditorPane basicInfoPane;
+ private JEditorPane selectionInfoPane;
private Object instance;
@@ -82,7 +82,7 @@ public class ReflectUI extends JFrame {
@Override
public void actionPerformed(ActionEvent e) {
RefField result = null;
- String search = searchFunction.getText();
+ String search = searchFunction.getText();
for (RefField f : fields.values()) {
if (f != null && (f.asObject()) != null) {
String value;
@@ -103,7 +103,6 @@ public class ReflectUI extends JFrame {
}
});
-
final JButton adjustClasses = new JButton("Expand");
adjustClasses.addActionListener(new ActionListener() {
@Override
@@ -130,7 +129,6 @@ public class ReflectUI extends JFrame {
searchContent.setMaximumSize(new Dimension(500, (int) searchContent.getPreferredSize().getHeight()));
searchContent.add(searchButton);
-
tree = new JTree();
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
@@ -139,9 +137,9 @@ public class ReflectUI extends JFrame {
@Override
public void valueChanged(TreeSelectionEvent event) {
- TreePath path = event.getPath();
+ TreePath path = event.getPath();
Object[] pathElements = path.getPath();
- Object element = pathElements[pathElements.length - 1];
+ Object element = pathElements[pathElements.length - 1];
if (pathElements.length == 2) {
setClassInfo(classes.get(element));
} else if (pathElements.length == 3) {
@@ -181,7 +179,7 @@ public class ReflectUI extends JFrame {
content.add(searchContent);
JScrollPane contentPane = new JScrollPane(content);
- Dimension prefSize = content.getPreferredSize();
+ Dimension prefSize = content.getPreferredSize();
contentPane.setPreferredSize(new Dimension(prefSize.width + contentPane.getVerticalScrollBar().getPreferredSize().width, prefSize.height + contentPane.getHorizontalScrollBar().getPreferredSize().height));
setContentPane(contentPane);
pack();
@@ -190,8 +188,8 @@ public class ReflectUI extends JFrame {
}
private void fillModel() {
- Context context = Context.getInstance();
- ClassPath classPath = context.getClassPath();
+ Context context = Context.getInstance();
+ ClassPath classPath = context.getClassPath();
ASMClassLoader classLoader = context.getASMClassLoader();
for (String className : classPath.classNames) {
try {
@@ -221,7 +219,7 @@ public class ReflectUI extends JFrame {
}
private void fillBasicInfoPane() {
- Context context = Context.getInstance();
+ Context context = Context.getInstance();
ClassPath classPath = context.getClassPath();
StringBuilder builder = new StringBuilder();
@@ -233,8 +231,8 @@ public class ReflectUI extends JFrame {
}
private void setFieldInfo(RefField refField) {
- StringBuilder builder = new StringBuilder();
- RefClass refClass = refField.getOwner();
+ StringBuilder builder = new StringBuilder();
+ RefClass refClass = refField.getOwner();
builder.append("").append(refClass.getClassName()).append(".").append(refField.getName()).append("
");
builder.append("Class: ").append(refClass.getClassName()).append("
");
builder.append("Value: ").append(refField.asObject()).append("
");
@@ -244,7 +242,7 @@ public class ReflectUI extends JFrame {
if (refField.isArray() && refField.getASMType().getClassName().contains("String") && refField.getArrayDimensions() == 1) {
String[] strings = (String[]) refField.asObject();
- String values = StringUtils.implode(", ", strings);
+ String values = StringUtils.implode(", ", strings);
builder.append("Values: ").append(values).append("
");
}
diff --git a/src/main/java/org/parabot/core/ui/ScriptSelector.java b/src/main/java/org/parabot/core/ui/ScriptSelector.java
index 38cc6fa..e69994f 100644
--- a/src/main/java/org/parabot/core/ui/ScriptSelector.java
+++ b/src/main/java/org/parabot/core/ui/ScriptSelector.java
@@ -23,202 +23,198 @@ import java.net.URLEncoder;
import java.util.HashMap;
/**
- *
* Script Selector GUI, shows all scripts
- *
+ *
* @author Everel
*/
public final class ScriptSelector extends JFrame {
- public static ScriptParser parser;
- private static final long serialVersionUID = 1L;
-
- private HashMap categories;
- private HashMap format;
- private DefaultMutableTreeNode root;
- private DefaultTreeModel model;
- private final int WIDTH;
- private final int HEIGHT;
+ private static final long serialVersionUID = 1L;
+ public static ScriptParser parser;
+ private final int WIDTH;
+ private final int HEIGHT;
+ private HashMap categories;
+ private HashMap format;
+ private DefaultMutableTreeNode root;
+ private DefaultTreeModel model;
+ private Font fontCategory = new Font("Arial", Font.BOLD, 12);
+ private Font fontScript = new Font("Arial", Font.PLAIN, 12);
+ private JTree tree;
+ private JEditorPane scriptInfo;
- public ScriptSelector() {
- this.categories = new HashMap();
- this.format = new HashMap();
- this.root = new DefaultMutableTreeNode("Scripts");
- this.WIDTH = 640;
- this.HEIGHT = 256 + 128;
- this.model = new DefaultTreeModel(root);
- putScripts();
- createUI();
- }
+ public ScriptSelector() {
+ this.categories = new HashMap();
+ this.format = new HashMap();
+ this.root = new DefaultMutableTreeNode("Scripts");
+ this.WIDTH = 640;
+ this.HEIGHT = 256 + 128;
+ this.model = new DefaultTreeModel(root);
+ putScripts();
+ createUI();
+ }
- private void runScript(ScriptDescription desc) {
- dispose();
- final ThreadGroup tg = Context.threadGroups.keySet().iterator()
- .next();
- ScriptParser.SCRIPT_CACHE.get(desc).run(tg);
- }
+ private void runScript(ScriptDescription desc) {
+ dispose();
+ final ThreadGroup tg = Context.threadGroups.keySet().iterator()
+ .next();
+ ScriptParser.SCRIPT_CACHE.get(desc).run(tg);
+ }
- private void putScripts() {
- final ScriptDescription[] descs = ScriptParser.getDescriptions();
- if (descs == null) {
- return;
- }
- for (final ScriptDescription scriptDesc : descs) {
- if (categories.get(scriptDesc.category) == null) {
- DefaultMutableTreeNode cat = new DefaultMutableTreeNode(Category.valueOf(scriptDesc.category.toUpperCase()));
- cat.add(new DefaultMutableTreeNode(scriptDesc.scriptName));
- root.add(cat);
- categories.put(scriptDesc.category, cat);
- } else {
- categories.get(scriptDesc.category).add(
- new DefaultMutableTreeNode(scriptDesc.scriptName));
- }
+ private void putScripts() {
+ final ScriptDescription[] descs = ScriptParser.getDescriptions();
+ if (descs == null) {
+ return;
+ }
+ for (final ScriptDescription scriptDesc : descs) {
+ if (categories.get(scriptDesc.category) == null) {
+ DefaultMutableTreeNode cat = new DefaultMutableTreeNode(Category.valueOf(scriptDesc.category.toUpperCase()));
+ cat.add(new DefaultMutableTreeNode(scriptDesc.scriptName));
+ root.add(cat);
+ categories.put(scriptDesc.category, cat);
+ } else {
+ categories.get(scriptDesc.category).add(
+ new DefaultMutableTreeNode(scriptDesc.scriptName));
+ }
- format.put(scriptDesc.scriptName, scriptDesc);
- }
- }
+ format.put(scriptDesc.scriptName, scriptDesc);
+ }
+ }
+ private String getScriptName(String path) {
+ return path.split(", ")[2].replaceAll("\\]", "");
+ }
- private String getScriptName(String path) {
- return path.split(", ")[2].replaceAll("\\]", "");
- }
+ private String getServerDesc(final String[] servers) {
+ if (servers == null) {
+ return "Unknown";
+ }
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < servers.length; i++) {
+ builder.append(servers[i]);
+ if ((i + 1) < servers.length) {
+ builder.append(", ");
+ }
+ }
+ return builder.toString();
+ }
- private String getServerDesc(final String[] servers) {
- if (servers == null) {
- return "Unknown";
- }
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < servers.length; i++) {
- builder.append(servers[i]);
- if ((i + 1) < servers.length) {
- builder.append(", ");
- }
- }
- return builder.toString();
- }
+ private void createUI() {
- private void createUI() {
+ this.setTitle("Script Selector");
+ this.setLayout(new BorderLayout());
+ this.setResizable(false);
+ this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- this.setTitle("Script Selector");
- this.setLayout(new BorderLayout());
- this.setResizable(false);
- this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+ JPanel panel = new JPanel(null);
+ panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
- JPanel panel = new JPanel(null);
- panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
+ tree = new JTree();
+ tree.setCellRenderer(new ScriptTreeCellRenderer());
+ tree.setRootVisible(false);
+ tree.setShowsRootHandles(true);
+ tree.setModel(model);
+ tree.addTreeSelectionListener(new TreeSelectionListener() {
+ public void valueChanged(TreeSelectionEvent e) {
+ String path = e.getPath().toString();
+ if (path.split(",").length == 3) {
- tree = new JTree();
- tree.setCellRenderer(new ScriptTreeCellRenderer());
- tree.setRootVisible(false);
- tree.setShowsRootHandles(true);
- tree.setModel(model);
- tree.addTreeSelectionListener(new TreeSelectionListener() {
- public void valueChanged(TreeSelectionEvent e) {
- String path = e.getPath().toString();
- if (path.split(",").length == 3) {
+ // local scripts
+ ScriptDescription def = format.get(getScriptName(e
+ .getPath().toString()));
+ if (def != null) {
+ StringBuilder html = new StringBuilder("");
+ html.append("")
+ .append(def.scriptName)
+ .append("
");
+ html.append("Author: ")
+ .append(def.author).append("
");
+ html.append("Servers: ")
+ .append(getServerDesc(def.servers))
+ .append("
");
+ html.append("Version: ")
+ .append(def.version).append("
");
+ html.append(
+ "Description: ")
+ .append(def.description).append("
");
+ html.append("");
+ scriptInfo.setText(new String(html));
+ }
- // local scripts
- ScriptDescription def = format.get(getScriptName(e
- .getPath().toString()));
- if (def != null) {
- StringBuilder html = new StringBuilder("");
- html.append("")
- .append(def.scriptName)
- .append("
");
- html.append("Author: ")
- .append(def.author).append("
");
- html.append("Servers: ")
- .append(getServerDesc(def.servers))
- .append("
");
- html.append("Version: ")
- .append(def.version).append("
");
- html.append(
- "Description: ")
- .append(def.description).append("
");
- html.append("");
- scriptInfo.setText(new String(html));
- }
+ }
+ }
+ });
- }
- }
- });
+ scriptInfo = new JEditorPane();
+ scriptInfo.setContentType("text/html");
+ scriptInfo.setEditable(false);
- scriptInfo = new JEditorPane();
- scriptInfo.setContentType("text/html");
- scriptInfo.setEditable(false);
+ JScrollPane scrlScriptTree = new JScrollPane(tree);
+ scrlScriptTree.setBounds(4, 4, WIDTH / 2 - 4 - 64, HEIGHT - 4 - 28);
- JScrollPane scrlScriptTree = new JScrollPane(tree);
- scrlScriptTree.setBounds(4, 4, WIDTH / 2 - 4 - 64, HEIGHT - 4 - 28);
+ JScrollPane scrlScriptInfo = new JScrollPane(scriptInfo);
+ scrlScriptInfo.setBounds(WIDTH / 2 + 4 - 64, 4, WIDTH / 2 - 8 + 64,
+ HEIGHT - 4 - 28);
- JScrollPane scrlScriptInfo = new JScrollPane(scriptInfo);
- scrlScriptInfo.setBounds(WIDTH / 2 + 4 - 64, 4, WIDTH / 2 - 8 + 64,
- HEIGHT - 4 - 28);
+ JButton cmdStart = new JButton("Start");
+ cmdStart.setBounds(WIDTH - 96 - 4, HEIGHT - 24 - 4, 96, 24);
+ cmdStart.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ String s = getScriptName(tree.getSelectionPath().toString());
+ if (s != null) {
+ try {
+ WebUtil.getContents("http://bdn.parabot.org/api/v2/scripts/local", "script=" + URLEncoder.encode(s, "UTF-8") + "&username=" + URLEncoder.encode(Context.getUsername(), "UTF-8"));
+ } catch (MalformedURLException | UnsupportedEncodingException e1) {
+ e1.printStackTrace();
+ }
+ runScript(format.get(s));
+ }
+ }
+ });
- JButton cmdStart = new JButton("Start");
- cmdStart.setBounds(WIDTH - 96 - 4, HEIGHT - 24 - 4, 96, 24);
- cmdStart.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- String s = getScriptName(tree.getSelectionPath().toString());
- if (s != null) {
- try {
- WebUtil.getContents("http://bdn.parabot.org/api/v2/scripts/local", "script=" + URLEncoder.encode(s, "UTF-8") + "&username=" + URLEncoder.encode(Context.getUsername(), "UTF-8"));
- } catch (MalformedURLException | UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
- runScript(format.get(s));
- }
- }
- });
+ JButton cmdHome = new JButton("Open home");
+ cmdHome.setBounds(WIDTH - (96 * 2) - 4 - 32, HEIGHT - 24 - 4, 96 + 32,
+ 24);
+ cmdHome.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ Desktop.getDesktop().open(Directories.getWorkspace());
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ });
- JButton cmdHome = new JButton("Open home");
- cmdHome.setBounds(WIDTH - (96 * 2) - 4 - 32, HEIGHT - 24 - 4, 96 + 32,
- 24);
- cmdHome.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- Desktop.getDesktop().open(Directories.getWorkspace());
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- });
+ panel.add(scrlScriptTree);
+ panel.add(scrlScriptInfo);
+ panel.add(cmdStart);
+ panel.add(cmdHome);
- panel.add(scrlScriptTree);
- panel.add(scrlScriptInfo);
- panel.add(cmdStart);
- panel.add(cmdHome);
+ this.add(panel);
+ this.pack();
+ this.setLocationRelativeTo(getOwner());
- this.add(panel);
- this.pack();
- this.setLocationRelativeTo(getOwner());
+ }
- }
+ private class ScriptTreeCellRenderer implements TreeCellRenderer {
+ private JLabel label;
- private class ScriptTreeCellRenderer implements TreeCellRenderer {
- private JLabel label;
+ ScriptTreeCellRenderer() {
+ label = new JLabel();
+ }
- ScriptTreeCellRenderer() {
- label = new JLabel();
- }
-
- @Override
- public Component getTreeCellRendererComponent(JTree list, Object value,
- boolean selected, boolean expanded, boolean leaf, int row,
- boolean focused) {
- Object o = ((DefaultMutableTreeNode) value).getUserObject();
- BufferedImage icon = (o instanceof Category ? ((Category) o)
- .getIcon() : Category.getIcon("script"));
- label.setIcon(icon != null ? new ImageIcon(icon) : null);
- label.setFont(o instanceof Category ? fontCategory : fontScript);
- label.setForeground(selected ? Color.DARK_GRAY : Color.BLACK);
- label.setText(String.valueOf(value));
- return label;
- }
- }
-
- private Font fontCategory = new Font("Arial", Font.BOLD, 12);
- private Font fontScript = new Font("Arial", Font.PLAIN, 12);
- private JTree tree;
- private JEditorPane scriptInfo;
+ @Override
+ public Component getTreeCellRendererComponent(JTree list, Object value,
+ boolean selected, boolean expanded, boolean leaf, int row,
+ boolean focused) {
+ Object o = ((DefaultMutableTreeNode) value).getUserObject();
+ BufferedImage icon = (o instanceof Category ? ((Category) o)
+ .getIcon() : Category.getIcon("script"));
+ label.setIcon(icon != null ? new ImageIcon(icon) : null);
+ label.setFont(o instanceof Category ? fontCategory : fontScript);
+ label.setForeground(selected ? Color.DARK_GRAY : Color.BLACK);
+ label.setText(String.valueOf(value));
+ return label;
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/ServerSelector.java b/src/main/java/org/parabot/core/ui/ServerSelector.java
index 3bbaacd..31da8dd 100755
--- a/src/main/java/org/parabot/core/ui/ServerSelector.java
+++ b/src/main/java/org/parabot/core/ui/ServerSelector.java
@@ -11,97 +11,94 @@ import java.util.LinkedList;
import java.util.Queue;
/**
- *
* Shows a list of every supported server which can be started
- *
+ *
* @author Dane, Everel
- *
*/
public class ServerSelector extends JPanel {
- public static String initServer;
- private static final long serialVersionUID = 5238720307271493899L;
- private static ServerSelector instance;
+ private static final long serialVersionUID = 5238720307271493899L;
+ public static String initServer;
+ private static ServerSelector instance;
- public static ServerSelector getInstance() {
- if (instance == null) {
- instance = new ServerSelector();
- }
- return instance;
- }
+ public ServerSelector() {
+ Queue widgets = getServers();
+ if (initServer != null) {
+ if (runServer(widgets)) {
+ initServer = null;
+ return;
+ }
+ }
- public ServerSelector() {
- Queue widgets = getServers();
- if (initServer != null) {
- if (runServer(widgets)) {
- initServer = null;
- return;
- }
- }
+ setLayout(new BorderLayout());
+ setPreferredSize(new Dimension(600, 350));
+ JPanel interior = new JPanel(null);
- setLayout(new BorderLayout());
- setPreferredSize(new Dimension(600, 350));
+ int i = 0;
+ int y = 0;
+ while (widgets != null && !widgets.isEmpty()) {
+ final ServerComponent w = widgets.poll();
+ w.setSize(300, 100);
+ if (i % 2 == 0 && i != 0) {
+ y += 100;
+ }
+ w.setLocation(i % 2 == 0 ? 0 : 300, y);
+ interior.add(w);
+ i++;
+ }
+ y += 100;
+ interior.setPreferredSize(new Dimension(300, y));
- JPanel interior = new JPanel(null);
+ JScrollPane scrlInterior = new JScrollPane(interior);
+ scrlInterior
+ .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+ scrlInterior
+ .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
+ add(scrlInterior);
- int i = 0;
- int y = 0;
- while (widgets != null && !widgets.isEmpty()) {
- final ServerComponent w = widgets.poll();
- w.setSize(300, 100);
- if(i % 2 == 0 && i != 0) {
- y += 100;
- }
- w.setLocation(i % 2 == 0 ? 0 : 300, y);
- interior.add(w);
- i++;
- }
- y += 100;
- interior.setPreferredSize(new Dimension(300, y));
+ }
- JScrollPane scrlInterior = new JScrollPane(interior);
- scrlInterior
- .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
- scrlInterior
- .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
- add(scrlInterior);
+ public static ServerSelector getInstance() {
+ if (instance == null) {
+ instance = new ServerSelector();
+ }
+ return instance;
+ }
- }
+ /**
+ * This method is called when -server argument is given
+ *
+ * @param widgets
+ */
+ private boolean runServer(Queue widgets) {
+ if (widgets == null || widgets.isEmpty()) {
+ return false;
+ }
+ final String serverName = initServer.toLowerCase();
+ for (ServerComponent widget : widgets) {
+ if (widget.desc.getServerName().toLowerCase().equals(serverName)) {
+ Environment.load(widget.desc);
+ return true;
+ }
+ }
+ return false;
+ }
- /**
- * This method is called when -server argument is given
- *
- * @param widgets
- */
- private boolean runServer(Queue widgets) {
- if (widgets == null || widgets.isEmpty()) {
- return false;
- }
- final String serverName = initServer.toLowerCase();
- for (ServerComponent widget : widgets) {
- if (widget.desc.getServerName().toLowerCase().equals(serverName)) {
- Environment.load(widget.desc);
- return true;
- }
- }
- return false;
- }
-
- /**
- * Fetches array of server widgets
- *
- * @return widgets array
- */
- public Queue getServers() {
- final Queue widgets = new LinkedList<>();
- ServerDescription[] servers = ServerParser.getDescriptions();
- if (servers != null) {
- for (ServerDescription desc : servers) {
- widgets.add(new ServerComponent(desc));
- }
- }
- return widgets;
- }
+ /**
+ * Fetches array of server widgets
+ *
+ * @return widgets array
+ */
+ public Queue getServers() {
+ final Queue widgets = new LinkedList<>();
+ ServerDescription[] servers = ServerParser.getDescriptions();
+ if (servers != null) {
+ for (ServerDescription desc : servers) {
+ widgets.add(new ServerComponent(desc));
+ }
+ }
+ return widgets;
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/components/GamePanel.java b/src/main/java/org/parabot/core/ui/components/GamePanel.java
index d319298..166194c 100644
--- a/src/main/java/org/parabot/core/ui/components/GamePanel.java
+++ b/src/main/java/org/parabot/core/ui/components/GamePanel.java
@@ -6,52 +6,50 @@ import javax.swing.*;
import java.awt.*;
/**
- *
* Main panel where applets are added.
- *
+ *
* @author Everel
- *
*/
public class GamePanel extends JPanel {
- private static final long serialVersionUID = 1L;
- private static GamePanel instance;
+ private static final long serialVersionUID = 1L;
+ private static GamePanel instance;
- private GamePanel() {
- setFocusable(true);
- setFocusTraversalKeysEnabled(false);
- setOpaque(true);
- setBackground(Color.black);
- setPreferredSize(new Dimension(770, 503));
- GroupLayout panelLayout = new GroupLayout(this);
- setLayout(panelLayout);
- panelLayout.setHorizontalGroup(panelLayout.createParallelGroup(
- GroupLayout.Alignment.LEADING).addGap(0, 770, Short.MAX_VALUE));
- panelLayout.setVerticalGroup(panelLayout.createParallelGroup(
- GroupLayout.Alignment.LEADING).addGap(0, 418, Short.MAX_VALUE));
- }
+ private GamePanel() {
+ setFocusable(true);
+ setFocusTraversalKeysEnabled(false);
+ setOpaque(true);
+ setBackground(Color.black);
+ setPreferredSize(new Dimension(770, 503));
+ GroupLayout panelLayout = new GroupLayout(this);
+ setLayout(panelLayout);
+ panelLayout.setHorizontalGroup(panelLayout.createParallelGroup(
+ GroupLayout.Alignment.LEADING).addGap(0, 770, Short.MAX_VALUE));
+ panelLayout.setVerticalGroup(panelLayout.createParallelGroup(
+ GroupLayout.Alignment.LEADING).addGap(0, 418, Short.MAX_VALUE));
+ }
- /**
- * Updates context of this panel and adds a different Applet to the panel
- *
- * @param c
- */
- public void setContext(final Context c) {
- add(c.getApplet(), BorderLayout.CENTER);
- }
+ /**
+ * Gets instance of this panel
+ *
+ * @return instance of this panel
+ */
+ public static GamePanel getInstance() {
+ return instance == null ? instance = new GamePanel() : instance;
+ }
- /**
- * Gets instance of this panel
- *
- * @return instance of this panel
- */
- public static GamePanel getInstance() {
- return instance == null ? instance = new GamePanel() : instance;
- }
+ /**
+ * Updates context of this panel and adds a different Applet to the panel
+ *
+ * @param c
+ */
+ public void setContext(final Context c) {
+ add(c.getApplet(), BorderLayout.CENTER);
+ }
- /**
- * Removes all components
- */
- public void removeComponents() {
- removeAll();
- }
+ /**
+ * Removes all components
+ */
+ public void removeComponents() {
+ removeAll();
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/components/PaintComponent.java b/src/main/java/org/parabot/core/ui/components/PaintComponent.java
index 146ee93..c15cbec 100644
--- a/src/main/java/org/parabot/core/ui/components/PaintComponent.java
+++ b/src/main/java/org/parabot/core/ui/components/PaintComponent.java
@@ -1,90 +1,84 @@
package org.parabot.core.ui.components;
-import java.awt.AlphaComposite;
-import java.awt.Dimension;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-
-import javax.swing.JComponent;
-
import org.parabot.core.Context;
import org.parabot.environment.api.interfaces.Paintable;
import org.parabot.environment.api.utils.Time;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+
/**
- *
* The panel that is painted on
- *
- * @author Everel
*
+ * @author Everel
*/
public class PaintComponent extends JComponent implements Runnable {
- private static final long serialVersionUID = 4653612412080038193L;
- private static PaintComponent instance;
-
- private BufferedImage buffer;
- private Graphics2D g2;
- private Dimension dimensions;
- private Context context;
-
- private PaintComponent(Dimension dimensions) {
- this.dimensions = dimensions;
- this.buffer = new BufferedImage(dimensions.width, dimensions.height, BufferedImage.TYPE_INT_ARGB);
- this.g2 = buffer.createGraphics();
-
- setPreferredSize(dimensions);
- setSize(dimensions);
- setOpaque(false);
- setIgnoreRepaint(true);
- }
-
- public void setDimensions(Dimension dimensions) {
- this.dimensions = dimensions;
- this.dimensions = dimensions;
- this.buffer = new BufferedImage(dimensions.width, dimensions.height, BufferedImage.TYPE_INT_ARGB);
- this.g2 = buffer.createGraphics();
-
- setPreferredSize(dimensions);
- setSize(dimensions);
- setOpaque(false);
- setIgnoreRepaint(true);
- }
-
- public static PaintComponent getInstance(Dimension dimensions) {
- return instance == null ? instance = new PaintComponent(dimensions) : instance;
- }
-
- public static PaintComponent getInstance() {
- return getInstance(null);
- }
-
- public void startPainting(Context context) {
- this.context = context;
- new Thread(this).start();
- }
-
- @Override
- public void paintComponent(Graphics g) {
- g2.setComposite(AlphaComposite.Clear);
- g2.fillRect(0, 0, dimensions.width, dimensions.height);
- g2.setComposite(AlphaComposite.SrcOver);
-
- if(context != null) {
- for(Paintable p : context.getPaintables()) {
- p.paint(g);
- }
- context.getPaintDebugger().debug(g2);
- }
- g.drawImage(buffer, 0, 0, null);
- }
+ private static final long serialVersionUID = 4653612412080038193L;
+ private static PaintComponent instance;
- @Override
- public void run() {
- while(true) {
- Time.sleep(100);
- repaint();
- }
- }
+ private BufferedImage buffer;
+ private Graphics2D g2;
+ private Dimension dimensions;
+ private Context context;
+
+ private PaintComponent(Dimension dimensions) {
+ this.dimensions = dimensions;
+ this.buffer = new BufferedImage(dimensions.width, dimensions.height, BufferedImage.TYPE_INT_ARGB);
+ this.g2 = buffer.createGraphics();
+
+ setPreferredSize(dimensions);
+ setSize(dimensions);
+ setOpaque(false);
+ setIgnoreRepaint(true);
+ }
+
+ public static PaintComponent getInstance(Dimension dimensions) {
+ return instance == null ? instance = new PaintComponent(dimensions) : instance;
+ }
+
+ public static PaintComponent getInstance() {
+ return getInstance(null);
+ }
+
+ public void setDimensions(Dimension dimensions) {
+ this.dimensions = dimensions;
+ this.dimensions = dimensions;
+ this.buffer = new BufferedImage(dimensions.width, dimensions.height, BufferedImage.TYPE_INT_ARGB);
+ this.g2 = buffer.createGraphics();
+
+ setPreferredSize(dimensions);
+ setSize(dimensions);
+ setOpaque(false);
+ setIgnoreRepaint(true);
+ }
+
+ public void startPainting(Context context) {
+ this.context = context;
+ new Thread(this).start();
+ }
+
+ @Override
+ public void paintComponent(Graphics g) {
+ g2.setComposite(AlphaComposite.Clear);
+ g2.fillRect(0, 0, dimensions.width, dimensions.height);
+ g2.setComposite(AlphaComposite.SrcOver);
+
+ if (context != null) {
+ for (Paintable p : context.getPaintables()) {
+ p.paint(g);
+ }
+ context.getPaintDebugger().debug(g2);
+ }
+ g.drawImage(buffer, 0, 0, null);
+ }
+
+ @Override
+ public void run() {
+ while (true) {
+ Time.sleep(100);
+ repaint();
+ }
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/components/ProgressBar.java b/src/main/java/org/parabot/core/ui/components/ProgressBar.java
index cfea288..816ab8c 100644
--- a/src/main/java/org/parabot/core/ui/components/ProgressBar.java
+++ b/src/main/java/org/parabot/core/ui/components/ProgressBar.java
@@ -1,92 +1,86 @@
package org.parabot.core.ui.components;
-import java.awt.Color;
-import java.awt.FontMetrics;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
+import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
- *
* ProgressBar
- *
- * @author Everel
*
+ * @author Everel
*/
public class ProgressBar {
- private double value;
- private int width;
- private int height;
- private double locX;
- private Color progColor;
- private Color backColor;
- private FontMetrics fontMetrics;
- private String text;
+ private double value;
+ private int width;
+ private int height;
+ private double locX;
+ private Color progColor;
+ private Color backColor;
+ private FontMetrics fontMetrics;
+ private String text;
- public ProgressBar(int width, int height) {
- this.progColor = new Color(255, 0, 0);
- this.backColor = new Color(74, 74, 72, 100);
- this.width = width;
- this.height = height;
- this.text = "";
- }
-
- public void setText(final String text) {
- this.text = text;
- }
+ public ProgressBar(int width, int height) {
+ this.progColor = new Color(255, 0, 0);
+ this.backColor = new Color(74, 74, 72, 100);
+ this.width = width;
+ this.height = height;
+ this.text = "";
+ }
- public void setValue(double value) {
- if(value < 0 || value > 100) {
- return;
- }
- if(value > 99) {
- value = 100;
- }
- this.value = value;
- this.locX = (width / 100.0D) * value;
+ public void setText(final String text) {
+ this.text = text;
+ }
- int val = (int) value;
- /*if (value <= 50) {
+ public double getValue() {
+ return value;
+ }
+
+ public void setValue(double value) {
+ if (value < 0 || value > 100) {
+ return;
+ }
+ if (value > 99) {
+ value = 100;
+ }
+ this.value = value;
+ this.locX = (width / 100.0D) * value;
+
+ int val = (int) value;
+ /*if (value <= 50) {
this.progColor = new Color(255, (2 * val), 0);
} else {
val -= 50;
this.progColor = new Color((int) (255 - (5.1D * val)),
100 + (2 * val), 0);
}*/
-
- int r = (int) (((double) (225 - 218) * (double) val) / ((double) 100.D));
- int g = (int) (((double) (253 - 165) * (double) val) / ((double) 100.D));
- int b = (int) (((double) (145 - 32) * (double) val) / ((double) 100.D));
- this.progColor = new Color(255 - r, 253 - g, 145 - b);
- }
- public double getValue() {
- return value;
- }
+ int r = (int) (((double) (225 - 218) * (double) val) / ((double) 100.D));
+ int g = (int) (((double) (253 - 165) * (double) val) / ((double) 100.D));
+ int b = (int) (((double) (145 - 32) * (double) val) / ((double) 100.D));
+ this.progColor = new Color(255 - r, 253 - g, 145 - b);
+ }
- public void draw(Graphics g, int x, int y) {
- Graphics2D g2 = (Graphics2D) g;
- g2.setRenderingHint(
- RenderingHints.KEY_TEXT_ANTIALIASING,
- RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- if (fontMetrics == null) {
- fontMetrics = g2.getFontMetrics();
- }
- g2.setColor(backColor);
- g2.fillRect(x, y, width, height);
- g2.setColor(Color.DARK_GRAY);
- g2.drawRect(x - 1, y - 1, width + 1, height + 1);
- g2.setColor(this.progColor);
- g2.fill(new Rectangle2D.Double(x, y, locX, height));
-
- int value = (int) getValue();
- String percent = Integer.toString(value) + "% " + text;
-
- int strX = (x + (width / 2)) - (fontMetrics.stringWidth(percent) / 2);
- g2.setColor(Color.white);
- g2.drawString(percent, strX, y + 13);
- }
+ public void draw(Graphics g, int x, int y) {
+ Graphics2D g2 = (Graphics2D) g;
+ g2.setRenderingHint(
+ RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ if (fontMetrics == null) {
+ fontMetrics = g2.getFontMetrics();
+ }
+ g2.setColor(backColor);
+ g2.fillRect(x, y, width, height);
+ g2.setColor(Color.DARK_GRAY);
+ g2.drawRect(x - 1, y - 1, width + 1, height + 1);
+ g2.setColor(this.progColor);
+ g2.fill(new Rectangle2D.Double(x, y, locX, height));
+
+ int value = (int) getValue();
+ String percent = Integer.toString(value) + "% " + text;
+
+ int strX = (x + (width / 2)) - (fontMetrics.stringWidth(percent) / 2);
+ g2.setColor(Color.white);
+ g2.drawString(percent, strX, y + 13);
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/components/ServerComponent.java b/src/main/java/org/parabot/core/ui/components/ServerComponent.java
index 7fa9c83..c3f47fd 100644
--- a/src/main/java/org/parabot/core/ui/components/ServerComponent.java
+++ b/src/main/java/org/parabot/core/ui/components/ServerComponent.java
@@ -1,131 +1,124 @@
package org.parabot.core.ui.components;
-import java.awt.Color;
-import java.awt.Cursor;
-import java.awt.Font;
-import java.awt.FontMetrics;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-
-import javax.swing.JPanel;
-
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.ui.fonts.Fonts;
import org.parabot.environment.Environment;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+
/**
* A neat looking server component
- *
+ *
* @author Everel
- *
*/
public class ServerComponent extends JPanel implements MouseListener,
- MouseMotionListener {
- private static final long serialVersionUID = 1L;
-
- public ServerDescription desc;
- private String name;
- private boolean hovered;
+ MouseMotionListener {
+ private static final long serialVersionUID = 1L;
- public ServerComponent(final ServerDescription desc) {
- this.desc = desc;
- setLayout(null);
- this.name = desc.getServerName().replaceAll(" ", "");
+ public ServerDescription desc;
+ private String name;
+ private boolean hovered;
- addMouseListener(this);
- addMouseMotionListener(this);
- setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
- }
+ public ServerComponent(final ServerDescription desc) {
+ this.desc = desc;
+ setLayout(null);
+ this.name = desc.getServerName().replaceAll(" ", "");
- @Override
- public String getName() {
- return name;
- }
+ addMouseListener(this);
+ addMouseMotionListener(this);
+ setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+ }
- @Override
- public void paintComponent(Graphics g) {
- Graphics2D g2d = (Graphics2D) g;
- setOpaque(false);
- super.paintComponent(g);
- setOpaque(true);
- int w = getWidth();
- int h = getHeight();
+ @Override
+ public String getName() {
+ return name;
+ }
- Color bgColor = Color.LIGHT_GRAY;
- if (hovered) {
- bgColor = Color.GRAY;
- }
+ @Override
+ public void paintComponent(Graphics g) {
+ Graphics2D g2d = (Graphics2D) g;
+ setOpaque(false);
+ super.paintComponent(g);
+ setOpaque(true);
+ int w = getWidth();
+ int h = getHeight();
- g2d.setColor(bgColor);
- g2d.fillRect(0, 0, w, h);
- g.setColor(Color.black);
- Font title = Fonts.getResource("leelawadee.ttf", 16);
- g.setFont(title);
- String serverName = desc.getServerName();
- int sw = g.getFontMetrics().stringWidth(serverName);
- g.drawString(serverName, (w / 2) - (sw / 2), 30);
+ Color bgColor = Color.LIGHT_GRAY;
+ if (hovered) {
+ bgColor = Color.GRAY;
+ }
- Font normal = Fonts.getResource("leelawadee.ttf");
- g.setFont(normal);
- FontMetrics fm = g.getFontMetrics();
- String author = "Author: " + desc.getAuthor();
- String revision = "Revision: " + desc.getRevision();
+ g2d.setColor(bgColor);
+ g2d.fillRect(0, 0, w, h);
+ g.setColor(Color.black);
+ Font title = Fonts.getResource("leelawadee.ttf", 16);
+ g.setFont(title);
+ String serverName = desc.getServerName();
+ int sw = g.getFontMetrics().stringWidth(serverName);
+ g.drawString(serverName, (w / 2) - (sw / 2), 30);
- g.drawString(author, (w / 2) - (fm.stringWidth(author) / 2), 55);
- g.drawString(revision, (w / 2) - (fm.stringWidth(revision) / 2), 70);
- }
+ Font normal = Fonts.getResource("leelawadee.ttf");
+ g.setFont(normal);
+ FontMetrics fm = g.getFontMetrics();
+ String author = "Author: " + desc.getAuthor();
+ String revision = "Revision: " + desc.getRevision();
- public void load(final ServerDescription desc) {
- VerboseLoader.get().switchState(VerboseLoader.STATE_LOADING);
- new Thread(new Runnable() {
- @Override
- public void run() {
- Environment.load(desc);
+ g.drawString(author, (w / 2) - (fm.stringWidth(author) / 2), 55);
+ g.drawString(revision, (w / 2) - (fm.stringWidth(revision) / 2), 70);
+ }
- }
- }).start();
- }
+ public void load(final ServerDescription desc) {
+ VerboseLoader.get().switchState(VerboseLoader.STATE_LOADING);
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ Environment.load(desc);
- @Override
- public void mouseMoved(MouseEvent e) {
- if (!hovered) {
- hovered = true;
- this.repaint();
- }
- }
+ }
+ }).start();
+ }
- @Override
- public void mouseExited(MouseEvent e) {
- if (hovered) {
- hovered = false;
- this.repaint();
- }
+ @Override
+ public void mouseMoved(MouseEvent e) {
+ if (!hovered) {
+ hovered = true;
+ this.repaint();
+ }
+ }
- }
+ @Override
+ public void mouseExited(MouseEvent e) {
+ if (hovered) {
+ hovered = false;
+ this.repaint();
+ }
- @Override
- public void mousePressed(MouseEvent e) {
- if (hovered) {
- load(desc);
- }
- }
-
- @Override
- public void mouseDragged(MouseEvent e) {
- }
-
- @Override
- public void mouseClicked(MouseEvent e) {
- }
+ }
- @Override
- public void mouseEntered(MouseEvent e) {
- }
+ @Override
+ public void mousePressed(MouseEvent e) {
+ if (hovered) {
+ load(desc);
+ }
+ }
- @Override
- public void mouseReleased(MouseEvent e) {
- }
+ @Override
+ public void mouseDragged(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseEntered(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ }
}
diff --git a/src/main/java/org/parabot/core/ui/components/VerboseLoader.java b/src/main/java/org/parabot/core/ui/components/VerboseLoader.java
index 9d9e102..929bdb8 100755
--- a/src/main/java/org/parabot/core/ui/components/VerboseLoader.java
+++ b/src/main/java/org/parabot/core/ui/components/VerboseLoader.java
@@ -6,8 +6,8 @@ import org.parabot.core.forum.AccountManager;
import org.parabot.core.forum.AccountManagerAccess;
import org.parabot.core.io.ProgressListener;
import org.parabot.core.ui.ServerSelector;
-import org.parabot.core.ui.images.Images;
import org.parabot.core.ui.fonts.Fonts;
+import org.parabot.core.ui.images.Images;
import org.parabot.core.ui.utils.UILog;
import javax.swing.*;
@@ -24,22 +24,13 @@ import java.awt.image.RescaleOp;
* @author Everel, EmmaStone
*/
public class VerboseLoader extends JPanel implements ProgressListener {
+ public static final int STATE_LOADING = 1;
private static final long serialVersionUID = 7412412644921803896L;
+ private static final int STATE_AUTHENTICATION = 0;
+ private static final int STATE_SERVER_SELECT = 2;
private static VerboseLoader current;
private static String state = "Initializing loader...";
-
- private static final int STATE_AUTHENTICATION = 0;
- public static final int STATE_LOADING = 1;
- private static final int STATE_SERVER_SELECT = 2;
- private int currentState;
-
private static AccountManager manager;
-
- private FontMetrics fontMetrics;
- private BufferedImage background, banner, loginBox;
- private ProgressBar progressBar;
- private JPanel loginPanel;
-
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
@@ -48,6 +39,11 @@ public class VerboseLoader extends JPanel implements ProgressListener {
}
};
+ private int currentState;
+ private FontMetrics fontMetrics;
+ private BufferedImage background, banner, loginBox;
+ private ProgressBar progressBar;
+ private JPanel loginPanel;
private VerboseLoader(String username, String password) {
if (current != null) {
@@ -77,10 +73,38 @@ public class VerboseLoader extends JPanel implements ProgressListener {
}
}
+ /**
+ * Gets instance of this panel
+ *
+ * @return instance of this panel
+ */
+ public static VerboseLoader get(String username, String password) {
+ return current == null ? new VerboseLoader(username, password) : current;
+ }
+
+ /**
+ * Gets instance of this panel
+ *
+ * @return instance of this panel
+ */
+ public static VerboseLoader get() {
+ return current == null ? new VerboseLoader(null, null) : current;
+ }
+
+ /**
+ * Updates the status message and repaints the panel
+ *
+ * @param message
+ */
+ public static void setState(final String message) {
+ state = message;
+ current.repaint();
+ }
+
public void addServerPanel() {
- JPanel servers = ServerSelector.getInstance();
- GridBagLayout bagLayout = (GridBagLayout) getLayout();
- GridBagConstraints c = new GridBagConstraints();
+ JPanel servers = ServerSelector.getInstance();
+ GridBagLayout bagLayout = (GridBagLayout) getLayout();
+ GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
@@ -139,7 +163,6 @@ public class VerboseLoader extends JPanel implements ProgressListener {
passwordLabel.setAlignmentX(Box.CENTER_ALIGNMENT);
passwordLabel.setForeground(Color.white);
-
login.setAlignmentX(Box.CENTER_ALIGNMENT);
login.setOpaque(false);
@@ -189,16 +212,15 @@ public class VerboseLoader extends JPanel implements ProgressListener {
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
-
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawImage(background, 0, 0, null);
- float[] scales = {1f, 1f, 1f, 0.9f};
- float[] offsets = new float[4];
- RescaleOp rop = new RescaleOp(scales, offsets, null);
+ float[] scales = { 1f, 1f, 1f, 0.9f };
+ float[] offsets = new float[4];
+ RescaleOp rop = new RescaleOp(scales, offsets, null);
g.drawImage(banner, rop, 0, 0);
g.setStroke(new BasicStroke(5));
@@ -236,7 +258,6 @@ public class VerboseLoader extends JPanel implements ProgressListener {
g.drawString(state, x, 200);
}
-
g.setFont(Fonts.getResource("leelawadee.ttf"));
final String version = Configuration.BOT_VERSION.get();
g.drawString(version,
@@ -244,35 +265,6 @@ public class VerboseLoader extends JPanel implements ProgressListener {
getHeight() - 12);
}
- /**
- * Gets instance of this panel
- *
- * @return instance of this panel
- */
- public static VerboseLoader get(String username, String password) {
- return current == null ? new VerboseLoader(username, password) : current;
- }
-
- /**
- * Gets instance of this panel
- *
- * @return instance of this panel
- */
- public static VerboseLoader get() {
- return current == null ? new VerboseLoader(null, null) : current;
- }
-
-
- /**
- * Updates the status message and repaints the panel
- *
- * @param message
- */
- public static void setState(final String message) {
- state = message;
- current.repaint();
- }
-
@Override
public void onProgressUpdate(double value) {
progressBar.setValue(value);
diff --git a/src/main/java/org/parabot/core/ui/components/script-selector.fxml b/src/main/java/org/parabot/core/ui/components/script-selector.fxml
index 6b52e6f..6f4e6ed 100644
--- a/src/main/java/org/parabot/core/ui/components/script-selector.fxml
+++ b/src/main/java/org/parabot/core/ui/components/script-selector.fxml
@@ -1,86 +1,87 @@
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/parabot/core/ui/fonts/Fonts.java b/src/main/java/org/parabot/core/ui/fonts/Fonts.java
index 378c654..5bb01a2 100644
--- a/src/main/java/org/parabot/core/ui/fonts/Fonts.java
+++ b/src/main/java/org/parabot/core/ui/fonts/Fonts.java
@@ -13,6 +13,7 @@ public class Fonts {
* Calls the getResource with the default size of 12
*
* @param resource
+ *
* @return
*/
public static Font getResource(final String resource) {
diff --git a/src/main/java/org/parabot/core/ui/fonts/ParabotFont.java b/src/main/java/org/parabot/core/ui/fonts/ParabotFont.java
index ebd3d5d..fc8c932 100644
--- a/src/main/java/org/parabot/core/ui/fonts/ParabotFont.java
+++ b/src/main/java/org/parabot/core/ui/fonts/ParabotFont.java
@@ -9,7 +9,7 @@ import java.io.IOException;
public class ParabotFont {
private String location;
- private Font font;
+ private Font font;
public ParabotFont(String location, float size) {
if (!location.toLowerCase().startsWith("/storage/fonts/")) {
diff --git a/src/main/java/org/parabot/core/ui/listeners/PBKeyListener.java b/src/main/java/org/parabot/core/ui/listeners/PBKeyListener.java
index 2883460..d4b077b 100644
--- a/src/main/java/org/parabot/core/ui/listeners/PBKeyListener.java
+++ b/src/main/java/org/parabot/core/ui/listeners/PBKeyListener.java
@@ -2,7 +2,6 @@ package org.parabot.core.ui.listeners;
import org.parabot.core.ui.listeners.key.ActionEventBinding;
import org.parabot.core.ui.listeners.key.Binding;
-import org.parabot.environment.OperatingSystem;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
@@ -31,15 +30,15 @@ public class PBKeyListener implements KeyListener {
}
public void addBinding(Binding binding) {
- for (Binding bind : this.bindings){
- if (bind.getKey() == binding.getKey()){
+ for (Binding bind : this.bindings) {
+ if (bind.getKey() == binding.getKey()) {
return;
}
}
this.bindings.add(binding);
}
- public void resetBindings(){
+ public void resetBindings() {
this.bindings = new ArrayList<>();
this.fillBindings();
}
diff --git a/src/main/java/org/parabot/environment/Environment.java b/src/main/java/org/parabot/environment/Environment.java
index 75b7bf8..88cf093 100644
--- a/src/main/java/org/parabot/environment/Environment.java
+++ b/src/main/java/org/parabot/environment/Environment.java
@@ -10,7 +10,6 @@ import org.parabot.environment.api.utils.WebUtil;
import java.util.LinkedList;
-
/**
* Initializes the bot environment
*
diff --git a/src/main/java/org/parabot/environment/OperatingSystem.java b/src/main/java/org/parabot/environment/OperatingSystem.java
index 2238061..1c5fb5e 100644
--- a/src/main/java/org/parabot/environment/OperatingSystem.java
+++ b/src/main/java/org/parabot/environment/OperatingSystem.java
@@ -1,25 +1,26 @@
package org.parabot.environment;
/**
- *
* This class is used for detecting the user's operating system
- *
+ *
* @author Everel
- *
*/
public enum OperatingSystem {
- WINDOWS, LINUX, MAC, OTHER;
+ WINDOWS, LINUX, MAC, OTHER;
- public static final OperatingSystem getOS() {
- String str = System.getProperty("os.name").toLowerCase();
- if (str.indexOf("win") > -1)
- return OperatingSystem.WINDOWS;
- if (str.indexOf("mac") > -1)
- return OperatingSystem.MAC;
- if (str.indexOf("nix") > -1 || str.indexOf("nux") > -1)
- return OperatingSystem.LINUX;
- return OperatingSystem.OTHER;
- }
+ public static final OperatingSystem getOS() {
+ String str = System.getProperty("os.name").toLowerCase();
+ if (str.indexOf("win") > -1) {
+ return OperatingSystem.WINDOWS;
+ }
+ if (str.indexOf("mac") > -1) {
+ return OperatingSystem.MAC;
+ }
+ if (str.indexOf("nix") > -1 || str.indexOf("nux") > -1) {
+ return OperatingSystem.LINUX;
+ }
+ return OperatingSystem.OTHER;
+ }
}
diff --git a/src/main/java/org/parabot/environment/api/interfaces/Paintable.java b/src/main/java/org/parabot/environment/api/interfaces/Paintable.java
index 29a979c..467c4dd 100644
--- a/src/main/java/org/parabot/environment/api/interfaces/Paintable.java
+++ b/src/main/java/org/parabot/environment/api/interfaces/Paintable.java
@@ -1,17 +1,15 @@
package org.parabot.environment.api.interfaces;
-import java.awt.Graphics;
+import java.awt.*;
/**
- *
* @author Everel
- *
*/
public interface Paintable {
-
- /**
- * @param g
- */
- public void paint(Graphics g);
+
+ /**
+ * @param g
+ */
+ public void paint(Graphics g);
}
diff --git a/src/main/java/org/parabot/environment/api/utils/FileUtil.java b/src/main/java/org/parabot/environment/api/utils/FileUtil.java
index ba7ea9c..ce954d3 100644
--- a/src/main/java/org/parabot/environment/api/utils/FileUtil.java
+++ b/src/main/java/org/parabot/environment/api/utils/FileUtil.java
@@ -13,13 +13,13 @@ import java.security.NoSuchAlgorithmException;
*/
public class FileUtil {
- public static String getChecksum(File file){
+ public static String getChecksum(File file) {
if (file.isFile()) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
if (file.exists()) {
- FileInputStream fis = new FileInputStream(file);
- byte[] dataBytes = new byte[1024];
+ FileInputStream fis = new FileInputStream(file);
+ byte[] dataBytes = new byte[1024];
int nread;
@@ -49,8 +49,8 @@ public class FileUtil {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
if (file.exists()) {
- FileInputStream fis = new FileInputStream(file);
- byte[] dataBytes = new byte[1024];
+ FileInputStream fis = new FileInputStream(file);
+ byte[] dataBytes = new byte[1024];
int nread;
@@ -76,7 +76,7 @@ public class FileUtil {
if (!destFile.exists()) {
destFile.createNewFile();
}
- FileChannel source = null;
+ FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
diff --git a/src/main/java/org/parabot/environment/api/utils/Filter.java b/src/main/java/org/parabot/environment/api/utils/Filter.java
index 2c2c3cf..b06d9fc 100644
--- a/src/main/java/org/parabot/environment/api/utils/Filter.java
+++ b/src/main/java/org/parabot/environment/api/utils/Filter.java
@@ -2,16 +2,18 @@ package org.parabot.environment.api.utils;
/**
* A simple class to filter things out of an collection
- *
- * @author Everel
- *
+ *
* @param
+ *
+ * @author Everel
*/
public interface Filter {
- /**
- * Determines if this object should be accepted
- * @param f
- * @return true to include this object, otherwise false to exclude.
- */
- public boolean accept(F f);
+ /**
+ * Determines if this object should be accepted
+ *
+ * @param f
+ *
+ * @return true to include this object, otherwise false to exclude.
+ */
+ public boolean accept(F f);
}
diff --git a/src/main/java/org/parabot/environment/api/utils/JavaUtil.java b/src/main/java/org/parabot/environment/api/utils/JavaUtil.java
index ad6952b..8bba906 100644
--- a/src/main/java/org/parabot/environment/api/utils/JavaUtil.java
+++ b/src/main/java/org/parabot/environment/api/utils/JavaUtil.java
@@ -6,10 +6,10 @@ package org.parabot.environment.api.utils;
public class JavaUtil {
public static double JAVA_VERSION = getVersion();
- static double getVersion () {
+ static double getVersion() {
String version = System.getProperty("java.version");
- int pos = version.indexOf('.');
- pos = version.indexOf('.', pos+1);
- return Double.parseDouble (version.substring (0, pos));
+ int pos = version.indexOf('.');
+ pos = version.indexOf('.', pos + 1);
+ return Double.parseDouble(version.substring(0, pos));
}
}
diff --git a/src/main/java/org/parabot/environment/api/utils/Multipliers.java b/src/main/java/org/parabot/environment/api/utils/Multipliers.java
index 701449f..7ac8f90 100644
--- a/src/main/java/org/parabot/environment/api/utils/Multipliers.java
+++ b/src/main/java/org/parabot/environment/api/utils/Multipliers.java
@@ -3,44 +3,38 @@ package org.parabot.environment.api.utils;
import java.math.BigInteger;
/**
- *
* Helper class for calculating setters for clients that uses multipliers
- *
- * @author Everel
*
+ * @author Everel
*/
public class Multipliers {
- /**
- *
- * @param multiplier
- * the multiplier
- * @param set
- * the value you want to set
- * @return the correct setter value
- */
- public static int getIntSetter(int multiplier, int set) {
- int bits = 32;
- BigInteger quotient = new BigInteger(Integer.toString(multiplier));
- BigInteger shift = BigInteger.ONE.shiftLeft(bits);
- int value = quotient.modInverse(shift).intValue();
- return value * set;
- }
+ /**
+ * @param multiplier the multiplier
+ * @param set the value you want to set
+ *
+ * @return the correct setter value
+ */
+ public static int getIntSetter(int multiplier, int set) {
+ int bits = 32;
+ BigInteger quotient = new BigInteger(Integer.toString(multiplier));
+ BigInteger shift = BigInteger.ONE.shiftLeft(bits);
+ int value = quotient.modInverse(shift).intValue();
+ return value * set;
+ }
- /**
- *
- * @param multiplier
- * the multiplier
- * @param set
- * the value you want to set
- * @return the correct setter value
- */
- public static long getLongSetter(long multiplier, long set) {
- int bits = 64;
- BigInteger quotient = new BigInteger(Long.toString(multiplier));
- BigInteger shift = BigInteger.ONE.shiftLeft(bits);
- long value = quotient.modInverse(shift).longValue();
- return value * set;
- }
+ /**
+ * @param multiplier the multiplier
+ * @param set the value you want to set
+ *
+ * @return the correct setter value
+ */
+ public static long getLongSetter(long multiplier, long set) {
+ int bits = 64;
+ BigInteger quotient = new BigInteger(Long.toString(multiplier));
+ BigInteger shift = BigInteger.ONE.shiftLeft(bits);
+ long value = quotient.modInverse(shift).longValue();
+ return value * set;
+ }
}
diff --git a/src/main/java/org/parabot/environment/api/utils/PBPreferences.java b/src/main/java/org/parabot/environment/api/utils/PBPreferences.java
index 8d810e2..e7e3ffc 100644
--- a/src/main/java/org/parabot/environment/api/utils/PBPreferences.java
+++ b/src/main/java/org/parabot/environment/api/utils/PBPreferences.java
@@ -19,16 +19,14 @@ import java.util.Properties;
public class PBPreferences {
private static AccountManager manager;
-
- private Properties properties;
- private int scriptID;
-
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
public final void setManager(AccountManager manager) {
PBPreferences.manager = manager;
}
};
+ private Properties properties;
+ private int scriptID;
public PBPreferences(int scriptID) {
this.scriptID = scriptID;
@@ -45,7 +43,7 @@ public class PBPreferences {
JSONArray resultArray;
if ((resultArray = ((JSONArray) result.get("result"))) != null) {
- for(Object rObject : resultArray) {
+ for (Object rObject : resultArray) {
JSONObject resultObject = (JSONObject) rObject;
for (Object map : resultObject.entrySet()) {
Map.Entry, ?> pairs = (Map.Entry, ?>) map;
@@ -60,6 +58,7 @@ public class PBPreferences {
/**
* Change a setting
+ *
* @param key
* @param value
*/
@@ -69,27 +68,32 @@ public class PBPreferences {
/**
* Get a setting value
+ *
* @param key
+ *
* @return
*/
- public Object getSetting(Object key){
+ public Object getSetting(Object key) {
return this.properties.get(key);
}
/**
* Get a setting value as string
+ *
* @param key
+ *
* @return
*/
- public String getSetting(String key){
+ public String getSetting(String key) {
return this.properties.getProperty(key);
}
/**
* Remove a setting
+ *
* @param key
*/
- public void removeSetting(Object key){
+ public void removeSetting(Object key) {
try {
JSONObject result = (JSONObject) WebUtil.getJsonParser().parse(
WebUtil.getContents("http://bdn.parabot.org/api/v2/user/preferences/set/",
@@ -98,7 +102,7 @@ public class PBPreferences {
"&script=" + String.valueOf(scriptID)
)
);
- if ((boolean)result.get("result")){
+ if ((boolean) result.get("result")) {
this.properties.remove(key);
}
} catch (ParseException | MalformedURLException | UnsupportedEncodingException e) {
@@ -108,10 +112,11 @@ public class PBPreferences {
/**
* Add a setting
+ *
* @param key
* @param value
*/
- public void addSetting(Object key, Object value){
+ public void addSetting(Object key, Object value) {
try {
JSONObject result = (JSONObject) WebUtil.getJsonParser().parse(
WebUtil.getContents("http://bdn.parabot.org/api/v2/user/preferences/set/",
@@ -121,7 +126,7 @@ public class PBPreferences {
"&script=" + String.valueOf(scriptID)
)
);
- if ((boolean)result.get("result")){
+ if ((boolean) result.get("result")) {
this.properties.put(key, value);
}
} catch (ParseException | MalformedURLException | UnsupportedEncodingException e) {
diff --git a/src/main/java/org/parabot/environment/api/utils/Random.java b/src/main/java/org/parabot/environment/api/utils/Random.java
index 804983c..f9b63ea 100644
--- a/src/main/java/org/parabot/environment/api/utils/Random.java
+++ b/src/main/java/org/parabot/environment/api/utils/Random.java
@@ -1,28 +1,27 @@
package org.parabot.environment.api.utils;
/**
- *
* A random class is used for generating random numbers
- *
- * @author Everel
*
+ * @author Everel
*/
public class Random {
- private final static java.util.Random RANDOM = new java.util.Random();
-
- /**
- * Randomizes a number between minimum and maximum
- *
- * @param min
- * @param max
- * @return randomized number
- */
- public static int between(final int min, final int max) {
- try {
- return min + (max == min ? 0 : RANDOM.nextInt(max - min));
- } catch (Exception e) {
- return min + (max - min);
- }
- }
+ private final static java.util.Random RANDOM = new java.util.Random();
+
+ /**
+ * Randomizes a number between minimum and maximum
+ *
+ * @param min
+ * @param max
+ *
+ * @return randomized number
+ */
+ public static int between(final int min, final int max) {
+ try {
+ return min + (max == min ? 0 : RANDOM.nextInt(max - min));
+ } catch (Exception e) {
+ return min + (max - min);
+ }
+ }
}
diff --git a/src/main/java/org/parabot/environment/api/utils/Time.java b/src/main/java/org/parabot/environment/api/utils/Time.java
index 40194cd..5418f42 100644
--- a/src/main/java/org/parabot/environment/api/utils/Time.java
+++ b/src/main/java/org/parabot/environment/api/utils/Time.java
@@ -3,66 +3,63 @@ package org.parabot.environment.api.utils;
import org.parabot.environment.scripts.framework.SleepCondition;
/**
- *
* Holds various Time utilities
- *
- * @author Everel
*
+ * @author Everel
*/
public final class Time {
-
- /**
- * Sleeps for a given amount of time
- * @param ms
- */
- public static void sleep(final int ms) {
- try {
- Thread.sleep(ms);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-
- /**
- *
- * @param minumum
- * @param maximum
- */
- public static void sleep(final int minumum, final int maximum) {
- try {
- Thread.sleep(Random.between(minumum, maximum));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Sleeps until the SleepCondition is valid.
- *
- * @param conn
- * the condition.
- * @param timeout
- * the time in miliseconds before it stops sleeping.
- * @return whether it ran successfully without timing out.
- */
- public static boolean sleep(SleepCondition conn, int timeout) {
- long start = System.currentTimeMillis();
- while (!conn.isValid()) {
- if (start + timeout < System.currentTimeMillis()) {
- return false;
- }
- Time.sleep(50);
- }
- return true;
- }
-
- /**
- * Gets current time in milliseconds
- * @return time in ms
- */
- public static long get() {
- return System.currentTimeMillis();
- }
+
+ /**
+ * Sleeps for a given amount of time
+ *
+ * @param ms
+ */
+ public static void sleep(final int ms) {
+ try {
+ Thread.sleep(ms);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @param minumum
+ * @param maximum
+ */
+ public static void sleep(final int minumum, final int maximum) {
+ try {
+ Thread.sleep(Random.between(minumum, maximum));
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Sleeps until the SleepCondition is valid.
+ *
+ * @param conn the condition.
+ * @param timeout the time in miliseconds before it stops sleeping.
+ *
+ * @return whether it ran successfully without timing out.
+ */
+ public static boolean sleep(SleepCondition conn, int timeout) {
+ long start = System.currentTimeMillis();
+ while (!conn.isValid()) {
+ if (start + timeout < System.currentTimeMillis()) {
+ return false;
+ }
+ Time.sleep(50);
+ }
+ return true;
+ }
+
+ /**
+ * Gets current time in milliseconds
+ *
+ * @return time in ms
+ */
+ public static long get() {
+ return System.currentTimeMillis();
+ }
}
diff --git a/src/main/java/org/parabot/environment/api/utils/Timer.java b/src/main/java/org/parabot/environment/api/utils/Timer.java
index d062895..fa3c07e 100644
--- a/src/main/java/org/parabot/environment/api/utils/Timer.java
+++ b/src/main/java/org/parabot/environment/api/utils/Timer.java
@@ -1,120 +1,135 @@
package org.parabot.environment.api.utils;
/**
- *
* A simple timer class
- *
+ *
* @author Everel, Parameter
- *
*/
public class Timer {
- private long start;
- private long end;
+ private long start;
+ private long end;
- /**
- * Timer Constructor
- *
- * @param end
- */
- public Timer(long end) {
+ /**
+ * Timer Constructor
+ *
+ * @param end
+ */
+ public Timer(long end) {
+ start = System.currentTimeMillis();
+ this.end = System.currentTimeMillis() + end;
+ }
- start = System.currentTimeMillis();
- this.end = System.currentTimeMillis() + end;
- }
+ /**
+ * Timer Constructor
+ *
+ * @param end
+ * @param start
+ */
+ public Timer(long end, long start) {
+ this.start = start;
+ this.end = System.currentTimeMillis() + end;
+ }
- /**
- * Timer Constructor
- */
- public Timer() {
- this(0);
- }
+ /**
+ * Timer Constructor
+ */
+ public Timer() {
+ this(0);
+ }
- /**
- * Determines the remaining time left.
- *
- * @return the remaining time.
- */
- public long getRemaining() {
- return end - System.currentTimeMillis();
- }
+ /**
+ * Determines the remaining time left.
+ *
+ * @return the remaining time.
+ */
+ public long getRemaining() {
+ return end - System.currentTimeMillis();
+ }
- /**
- * Determines if the end time has been reached, does not mean it stopped
- * running.
- */
- public boolean isFinished() {
- return System.currentTimeMillis() > end;
- }
+ /**
+ * Determines if the end time has been reached, does not mean it stopped
+ * running.
+ */
+ public boolean isFinished() {
+ return System.currentTimeMillis() > end;
+ }
- /**
- * Stops and resets the timer
- */
- public void restart() {
- stop();
- reset();
- }
+ /**
+ * Stops and resets the timer
+ */
+ public void restart() {
+ stop();
+ reset();
+ }
- /**
- * Resets the timer if stopped
- */
- public void reset() {
- if (start == 0) {
- start = System.currentTimeMillis();
- }
- }
+ /**
+ * Resets the timer if stopped
+ */
+ public void reset() {
+ if (start == 0) {
+ start = System.currentTimeMillis();
+ }
+ }
- /**
- * Resets the timer
- */
- public void stop() {
- end = (end - start) + System.currentTimeMillis();
- start = 0;
- }
+ /**
+ * Resets the timer
+ */
+ public void stop() {
+ end = (end - start) + System.currentTimeMillis();
+ start = 0;
+ }
- /**
- * Determines if timer is running
- *
- * @return true if timer is running
- */
- public boolean isRunning() {
- return start != 0;
- }
+ /**
+ * Determines if timer is running
+ *
+ * @return true if timer is running
+ */
+ public boolean isRunning() {
+ return start != 0;
+ }
- /**
- * Gets the run time in long millis.
- *
- * @return the elapsed time.
- */
- public long getElapsedTime() {
- return System.currentTimeMillis() - start;
- }
+ /**
+ * Gets the run time in long millis.
+ *
+ * @return the elapsed time.
+ */
+ public long getElapsedTime() {
+ return System.currentTimeMillis() - start;
+ }
- /**
- * Calculates hourly gains based on given variable
- *
- * @param gained
- * variable
- * @return hourly gains
- */
- public int getPerHour(final int gained) {
- return (int) ((gained) * 3600000D / (System.currentTimeMillis() - start));
- }
+ /**
+ * Calculates hourly gains based on given variable
+ *
+ * @param gained variable
+ *
+ * @return hourly gains
+ */
+ public int getPerHour(final int gained) {
+ return (int) ((gained) * 3600000D / (System.currentTimeMillis() - start));
+ }
- /**
- * Generates string based on HH:MM:SS
- *
- * @return String
- */
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder();
- long elapsed = getElapsedTime();
- int second = (int) (elapsed / 1000 % 60);
- int minute = (int) (elapsed / 60000 % 60);
- int hour = (int) (elapsed / 3600000 % 60);
- b.append(hour < 10 ? "0" : "").append(hour).append(":");
- b.append(minute < 10 ? "0" : "").append(minute).append(":");
- b.append(second < 10 ? "0" : "").append(second);
- return new String(b);
- }
+ /**
+ * Generates string based on DD:HH:MM:SS
+ *
+ * @return String
+ */
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder();
+ long elapsed = getElapsedTime();
+ int day = (int) (elapsed / 86400000);
+ elapsed -= day * 86400000;
+ int hour = (int) (elapsed / 3600000);
+ elapsed -= hour * 3600000;
+ int minute = (int) (elapsed / 60000);
+ elapsed -= minute * 60000;
+ int second = (int) (elapsed / 1000);
+ if (day > 0) {
+ b.append(day).append("d:");
+ }
+ b.append(hour < 10 ? "0" : "").append(hour).append(":");
+ b.append(minute < 10 ? "0" : "").append(minute).append(":");
+ b.append(second < 10 ? "0" : "").append(second);
+ return new String(b);
+ }
}
diff --git a/src/main/java/org/parabot/environment/api/utils/Version.java b/src/main/java/org/parabot/environment/api/utils/Version.java
index d585171..6cbba9b 100644
--- a/src/main/java/org/parabot/environment/api/utils/Version.java
+++ b/src/main/java/org/parabot/environment/api/utils/Version.java
@@ -4,9 +4,8 @@ import org.parabot.core.ui.utils.UILog;
public class Version implements Comparable {
- private String version;
-
private static boolean notified;
+ private String version;
public Version(String version) {
if (version == null) {
@@ -18,11 +17,24 @@ public class Version implements Comparable {
this.version = version;
}
+ private static void notifyRC() {
+ if (!notified) {
+ UILog.log(
+ "Version warning",
+ "This is an RC version of Parabot\n" +
+ "This could be an unstable version of Parabot, and might crash at anytime\n\n" +
+ "If you find an error within the client, please report any at:\n" +
+ "https://github.com/Parabot/Parabot/issues"
+ );
+ notified = true;
+ }
+ }
+
public final String get() {
return this.version;
}
- public boolean isNightly(){
+ public boolean isNightly() {
return this.version.contains("RC");
}
@@ -39,7 +51,7 @@ public class Version implements Comparable {
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
- int length = Math.max(thisParts.length, thatParts.length);
+ int length = Math.max(thisParts.length, thatParts.length);
for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
@@ -60,17 +72,4 @@ public class Version implements Comparable {
public boolean equals(Object that) {
return this == that || that != null && this.getClass() == that.getClass() && this.compareTo((Version) that) == 0;
}
-
- private static void notifyRC() {
- if (!notified) {
- UILog.log(
- "Version warning",
- "This is an RC version of Parabot\n" +
- "This could be an unstable version of Parabot, and might crash at anytime\n\n" +
- "If you find an error within the client, please report any at:\n" +
- "https://github.com/Parabot/Parabot/issues"
- );
- notified = true;
- }
- }
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/environment/input/Keyboard.java b/src/main/java/org/parabot/environment/input/Keyboard.java
index 0dd389c..5dd3a96 100644
--- a/src/main/java/org/parabot/environment/input/Keyboard.java
+++ b/src/main/java/org/parabot/environment/input/Keyboard.java
@@ -1,225 +1,228 @@
package org.parabot.environment.input;
-import java.awt.Component;
+import org.parabot.core.Context;
+
+import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Random;
-import org.parabot.core.Context;
-
/**
- *
* Virtual keyboard, dispatches key events to a component.
- *
- * @author Everel, Matt, Dane
*
+ * @author Everel, Matt, Dane
*/
public class Keyboard implements KeyListener {
- private static HashMap specialChars;
- private Component component;
- private long pressTime;
+ private static HashMap specialChars;
- public Keyboard(Component component) {
- this.component = component;
- }
-
- public static Keyboard getInstance() {
- return Context.getInstance().getKeyboard();
- }
+ static {
+ char[] spChars = { '~', '!', '@', '#', '%', '^', '&', '*', '(', ')',
+ '_', '+', '{', '}', ':', '<', '>', '?', '"', '|' };
+ char[] replace = { '`', '1', '2', '3', '5', '6', '7', '8', '9', '0',
+ '-', '=', '[', ']', ';', ',', '.', '/', '\'', '\\' };
+ specialChars = new HashMap(spChars.length);
+ for (int x = 0; x < spChars.length; ++x) {
+ specialChars.put(spChars[x], replace[x]);
+ }
+ }
- static {
- char[] spChars = { '~', '!', '@', '#', '%', '^', '&', '*', '(', ')',
- '_', '+', '{', '}', ':', '<', '>', '?', '"', '|' };
- char[] replace = { '`', '1', '2', '3', '5', '6', '7', '8', '9', '0',
- '-', '=', '[', ']', ';', ',', '.', '/', '\'', '\\' };
- specialChars = new HashMap(spChars.length);
- for (int x = 0; x < spChars.length; ++x)
- specialChars.put(spChars[x], replace[x]);
- }
+ private Component component;
+ private long pressTime;
- private static long getRandom() {
- Random rand = new Random();
- return rand.nextInt(100) + 40;
- }
+ public Keyboard(Component component) {
+ this.component = component;
+ }
- public void sendKeys(String s) {
+ public static Keyboard getInstance() {
+ return Context.getInstance().getKeyboard();
+ }
- pressTime = System.currentTimeMillis();
- for (char c : s.toCharArray())
- for (KeyEvent ke : createKeyClick(component, c)) {
- try {
- Thread.sleep(5);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- sendKeyEvent(ke);
- }
- clickKey(10);
- }
+ private static long getRandom() {
+ Random rand = new Random();
+ return rand.nextInt(100) + 40;
+ }
- public void clickKey(char c) {
+ public void sendKeys(String s) {
- pressTime = System.currentTimeMillis();
- for (KeyEvent ke : createKeyClick(component, c))
- sendKeyEvent(ke);
- }
+ pressTime = System.currentTimeMillis();
+ for (char c : s.toCharArray()) {
+ for (KeyEvent ke : createKeyClick(component, c)) {
+ try {
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ sendKeyEvent(ke);
+ }
+ }
+ clickKey(10);
+ }
- public void clickKey(int keyCode) {
+ public void clickKey(char c) {
- pressTime = System.currentTimeMillis();
- for (KeyEvent ke : createKeyClick(component, keyCode))
- sendKeyEvent(ke);
- }
+ pressTime = System.currentTimeMillis();
+ for (KeyEvent ke : createKeyClick(component, c)) {
+ sendKeyEvent(ke);
+ }
+ }
- public void pressKey(int keyCode) {
+ public void clickKey(int keyCode) {
- pressTime = System.currentTimeMillis();
- KeyEvent ke = createKeyPress(component, keyCode);
- sendKeyEvent(ke);
- }
+ pressTime = System.currentTimeMillis();
+ for (KeyEvent ke : createKeyClick(component, keyCode)) {
+ sendKeyEvent(ke);
+ }
+ }
- public void releaseKey(int keyCode) {
+ public void pressKey(int keyCode) {
- pressTime = System.currentTimeMillis();
- KeyEvent ke = createKeyRelease(component, keyCode);
- sendKeyEvent(ke);
- }
+ pressTime = System.currentTimeMillis();
+ KeyEvent ke = createKeyPress(component, keyCode);
+ sendKeyEvent(ke);
+ }
- private KeyEvent[] createKeyClick(Component target, char c) {
+ public void releaseKey(int keyCode) {
- pressTime += 2 * getRandom();
+ pressTime = System.currentTimeMillis();
+ KeyEvent ke = createKeyRelease(component, keyCode);
+ sendKeyEvent(ke);
+ }
- Character newChar = specialChars.get(c);
- int keyCode = Character.toUpperCase((newChar == null) ? c : newChar);
+ private KeyEvent[] createKeyClick(Component target, char c) {
- if (Character.isLowerCase(c)
- || (!Character.isLetter(c) && (newChar == null))) {
- KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
- pressTime, 0, keyCode, c);
- KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
- pressTime, 0, 0, c);
- pressTime += getRandom();
- KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
- pressTime, 0, keyCode, c);
+ pressTime += 2 * getRandom();
- return new KeyEvent[] { pressed, typed, released };
- } else {
- KeyEvent shiftDown = new KeyEvent(target, KeyEvent.KEY_PRESSED,
- pressTime, KeyEvent.SHIFT_MASK, KeyEvent.VK_SHIFT,
- KeyEvent.CHAR_UNDEFINED);
+ Character newChar = specialChars.get(c);
+ int keyCode = Character.toUpperCase((newChar == null) ? c : newChar);
- pressTime += getRandom();
- KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
- pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
- KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
- pressTime, KeyEvent.SHIFT_MASK, 0, c);
- pressTime += getRandom();
- KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
- pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
- pressTime += getRandom();
- KeyEvent shiftUp = new KeyEvent(target, KeyEvent.KEY_RELEASED,
- pressTime, 0, KeyEvent.VK_SHIFT, KeyEvent.CHAR_UNDEFINED);
+ if (Character.isLowerCase(c)
+ || (!Character.isLetter(c) && (newChar == null))) {
+ KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
+ pressTime, 0, keyCode, c);
+ KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
+ pressTime, 0, 0, c);
+ pressTime += getRandom();
+ KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
+ pressTime, 0, keyCode, c);
- return new KeyEvent[] { shiftDown, pressed, typed, released,
- shiftUp };
- }
- }
+ return new KeyEvent[]{ pressed, typed, released };
+ } else {
+ KeyEvent shiftDown = new KeyEvent(target, KeyEvent.KEY_PRESSED,
+ pressTime, KeyEvent.SHIFT_MASK, KeyEvent.VK_SHIFT,
+ KeyEvent.CHAR_UNDEFINED);
- private KeyEvent[] createKeyClick(Component target, int keyCode) {
- int modifier = 0;
- switch (keyCode) {
- case KeyEvent.VK_SHIFT:
- modifier = KeyEvent.SHIFT_MASK;
- break;
- case KeyEvent.VK_ALT:
- modifier = KeyEvent.ALT_MASK;
- break;
- case KeyEvent.VK_CONTROL:
- modifier = KeyEvent.CTRL_MASK;
- break;
- }
- KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
- pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
- KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
- pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
+ pressTime += getRandom();
+ KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
+ pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
+ KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
+ pressTime, KeyEvent.SHIFT_MASK, 0, c);
+ pressTime += getRandom();
+ KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
+ pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
+ pressTime += getRandom();
+ KeyEvent shiftUp = new KeyEvent(target, KeyEvent.KEY_RELEASED,
+ pressTime, 0, KeyEvent.VK_SHIFT, KeyEvent.CHAR_UNDEFINED);
- return new KeyEvent[] { pressed, released };
- }
+ return new KeyEvent[]{ shiftDown, pressed, typed, released,
+ shiftUp };
+ }
+ }
- private KeyEvent createKeyPress(Component target, int keyCode) {
- int modifier = 0;
- switch (keyCode) {
- case KeyEvent.VK_SHIFT:
- modifier = KeyEvent.SHIFT_MASK;
- break;
- case KeyEvent.VK_ALT:
- modifier = KeyEvent.ALT_MASK;
- break;
- case KeyEvent.VK_CONTROL:
- modifier = KeyEvent.CTRL_MASK;
- break;
- }
- KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
- pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
+ private KeyEvent[] createKeyClick(Component target, int keyCode) {
+ int modifier = 0;
+ switch (keyCode) {
+ case KeyEvent.VK_SHIFT:
+ modifier = KeyEvent.SHIFT_MASK;
+ break;
+ case KeyEvent.VK_ALT:
+ modifier = KeyEvent.ALT_MASK;
+ break;
+ case KeyEvent.VK_CONTROL:
+ modifier = KeyEvent.CTRL_MASK;
+ break;
+ }
+ KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
+ pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
+ KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
+ pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
- return pressed;
- }
+ return new KeyEvent[]{ pressed, released };
+ }
- private KeyEvent createKeyRelease(Component target, int keyCode) {
- @SuppressWarnings("unused")
- int modifier = 0;
- switch (keyCode) {
- case KeyEvent.VK_SHIFT:
- modifier = KeyEvent.SHIFT_MASK;
- break;
- case KeyEvent.VK_ALT:
- modifier = KeyEvent.ALT_MASK;
- break;
- case KeyEvent.VK_CONTROL:
- modifier = KeyEvent.CTRL_MASK;
- break;
- }
- KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
- pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
+ private KeyEvent createKeyPress(Component target, int keyCode) {
+ int modifier = 0;
+ switch (keyCode) {
+ case KeyEvent.VK_SHIFT:
+ modifier = KeyEvent.SHIFT_MASK;
+ break;
+ case KeyEvent.VK_ALT:
+ modifier = KeyEvent.ALT_MASK;
+ break;
+ case KeyEvent.VK_CONTROL:
+ modifier = KeyEvent.CTRL_MASK;
+ break;
+ }
+ KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
+ pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
- return released;
- }
+ return pressed;
+ }
- public void sendKeyEvent(KeyEvent e) {
- for (KeyListener kl : component.getKeyListeners()) {
- if(kl instanceof Keyboard) {
- continue;
- }
- if (!e.isConsumed()) {
- switch (e.getID()) {
- case KeyEvent.KEY_PRESSED:
- kl.keyPressed(e);
- break;
- case KeyEvent.KEY_RELEASED:
- kl.keyReleased(e);
- break;
- case KeyEvent.KEY_TYPED:
- kl.keyTyped(e);
- break;
- }
- }
- }
- }
+ private KeyEvent createKeyRelease(Component target, int keyCode) {
+ @SuppressWarnings("unused")
+ int modifier = 0;
+ switch (keyCode) {
+ case KeyEvent.VK_SHIFT:
+ modifier = KeyEvent.SHIFT_MASK;
+ break;
+ case KeyEvent.VK_ALT:
+ modifier = KeyEvent.ALT_MASK;
+ break;
+ case KeyEvent.VK_CONTROL:
+ modifier = KeyEvent.CTRL_MASK;
+ break;
+ }
+ KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
+ pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
- @Override
- public void keyPressed(KeyEvent e) {
+ return released;
+ }
- }
+ public void sendKeyEvent(KeyEvent e) {
+ for (KeyListener kl : component.getKeyListeners()) {
+ if (kl instanceof Keyboard) {
+ continue;
+ }
+ if (!e.isConsumed()) {
+ switch (e.getID()) {
+ case KeyEvent.KEY_PRESSED:
+ kl.keyPressed(e);
+ break;
+ case KeyEvent.KEY_RELEASED:
+ kl.keyReleased(e);
+ break;
+ case KeyEvent.KEY_TYPED:
+ kl.keyTyped(e);
+ break;
+ }
+ }
+ }
+ }
- @Override
- public void keyReleased(KeyEvent e) {
+ @Override
+ public void keyPressed(KeyEvent e) {
- }
+ }
- @Override
- public void keyTyped(KeyEvent e) {
+ @Override
+ public void keyReleased(KeyEvent e) {
- }
+ }
+
+ @Override
+ public void keyTyped(KeyEvent e) {
+
+ }
}
diff --git a/src/main/java/org/parabot/environment/input/Mouse.java b/src/main/java/org/parabot/environment/input/Mouse.java
index 82fbe55..662037f 100644
--- a/src/main/java/org/parabot/environment/input/Mouse.java
+++ b/src/main/java/org/parabot/environment/input/Mouse.java
@@ -9,155 +9,156 @@ import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
- *
* A virtual mouse, dispatches mouse events to a component
- *
- * @author Everel
*
+ * @author Everel
*/
public class Mouse implements MouseListener, MouseMotionListener {
- private Component component;
- private int x;
- private int y;
-
- public Mouse(Component component) {
- this.component = component;
- }
-
- public static Mouse getInstance() {
- return Context.getInstance().getMouse();
- }
-
- /**
- * Moves the mouse to the given point and clicks
- * @param x
- * @param y
- * @param left
- */
- public void click(final int x, final int y, final boolean left) {
-
- moveMouse(x, y);
- Time.sleep(50, 200);
- pressMouse(x, y, left);
- Time.sleep(10, 100);
- releaseMouse(x, y, left);
- Time.sleep(10, 100);
- clickMouse(x, y, left);
- }
-
- public void pressMouse(int x, int y, boolean left) {
- MouseEvent me = new MouseEvent(component,
- MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, x,
- y, 1, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
- for(MouseListener l : component.getMouseListeners()) {
- if(!(l instanceof Mouse)) {
- l.mousePressed(me);
- }
- }
- }
-
- public void click(final Point p, final boolean left) {
- click(p.x, p.y, left);
- }
-
- public void click(final Point p) {
- click(p.x, p.y, true);
- }
-
- public void clickMouse(int x, int y, boolean left) {
- try {
-
- MouseEvent me = new MouseEvent(component,
- MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, x,
- y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
- for(MouseListener l : component.getMouseListeners()) {
- if(!(l instanceof Mouse)) {
- l.mouseClicked(me);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void releaseMouse(int x, int y, boolean left) {
- try {
-
- MouseEvent me = new MouseEvent(component,
- MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(), 0, x,
- y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
- for(MouseListener l : component.getMouseListeners()) {
- if(!(l instanceof Mouse)) {
- l.mouseReleased(me);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
+ private Component component;
+ private int x;
+ private int y;
- /**
- * Moves the mouse cursor to the given location
- * @param x
- * @param y
- */
- public void moveMouse(int x, int y) {
- try {
- MouseEvent me = new MouseEvent(component,
- MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, x,
- y, 0, false);
- for(MouseMotionListener l : component.getMouseMotionListeners()) {
- if(!(l instanceof Mouse)) {
- l.mouseMoved(me);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Mouse cursor current location
- * @return point
- */
- public Point getPoint() {
- return new Point(x, y);
- }
-
- @Override
- public void mouseMoved(MouseEvent e) {
- x = e.getX();
- y = e.getY();
- }
+ public Mouse(Component component) {
+ this.component = component;
+ }
- @Override
- public void mouseDragged(MouseEvent e) {
-
- }
+ public static Mouse getInstance() {
+ return Context.getInstance().getMouse();
+ }
- @Override
- public void mouseClicked(MouseEvent e) {
+ /**
+ * Moves the mouse to the given point and clicks
+ *
+ * @param x
+ * @param y
+ * @param left
+ */
+ public void click(final int x, final int y, final boolean left) {
- }
+ moveMouse(x, y);
+ Time.sleep(50, 200);
+ pressMouse(x, y, left);
+ Time.sleep(10, 100);
+ releaseMouse(x, y, left);
+ Time.sleep(10, 100);
+ clickMouse(x, y, left);
+ }
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
+ public void pressMouse(int x, int y, boolean left) {
+ MouseEvent me = new MouseEvent(component,
+ MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, x,
+ y, 1, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
+ for (MouseListener l : component.getMouseListeners()) {
+ if (!(l instanceof Mouse)) {
+ l.mousePressed(me);
+ }
+ }
+ }
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
+ public void click(final Point p, final boolean left) {
+ click(p.x, p.y, left);
+ }
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
+ public void click(final Point p) {
+ click(p.x, p.y, true);
+ }
- @Override
- public void mouseReleased(MouseEvent e) {
-
- }
+ public void clickMouse(int x, int y, boolean left) {
+ try {
+
+ MouseEvent me = new MouseEvent(component,
+ MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, x,
+ y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
+ for (MouseListener l : component.getMouseListeners()) {
+ if (!(l instanceof Mouse)) {
+ l.mouseClicked(me);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void releaseMouse(int x, int y, boolean left) {
+ try {
+
+ MouseEvent me = new MouseEvent(component,
+ MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(), 0, x,
+ y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
+ for (MouseListener l : component.getMouseListeners()) {
+ if (!(l instanceof Mouse)) {
+ l.mouseReleased(me);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Moves the mouse cursor to the given location
+ *
+ * @param x
+ * @param y
+ */
+ public void moveMouse(int x, int y) {
+ try {
+ MouseEvent me = new MouseEvent(component,
+ MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, x,
+ y, 0, false);
+ for (MouseMotionListener l : component.getMouseMotionListeners()) {
+ if (!(l instanceof Mouse)) {
+ l.mouseMoved(me);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Mouse cursor current location
+ *
+ * @return point
+ */
+ public Point getPoint() {
+ return new Point(x, y);
+ }
+
+ @Override
+ public void mouseMoved(MouseEvent e) {
+ x = e.getX();
+ y = e.getY();
+ }
+
+ @Override
+ public void mouseDragged(MouseEvent e) {
+
+ }
+
+ @Override
+ public void mouseClicked(MouseEvent e) {
+
+ }
+
+ @Override
+ public void mouseEntered(MouseEvent e) {
+
+ }
+
+ @Override
+ public void mouseExited(MouseEvent e) {
+
+ }
+
+ @Override
+ public void mousePressed(MouseEvent e) {
+
+ }
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+
+ }
}
diff --git a/src/main/java/org/parabot/environment/randoms/RandomHandler.java b/src/main/java/org/parabot/environment/randoms/RandomHandler.java
index 1b80903..54d0e6c 100644
--- a/src/main/java/org/parabot/environment/randoms/RandomHandler.java
+++ b/src/main/java/org/parabot/environment/randoms/RandomHandler.java
@@ -48,6 +48,7 @@ public class RandomHandler {
/**
* @param random
+ *
* @deprecated
*/
@Deprecated
@@ -77,15 +78,6 @@ public class RandomHandler {
}
}
- /**
- * Sets the whole random arraylist to the arraylist given as argument
- *
- * @param randoms The new random arraylist
- */
- public void setRandoms(ArrayList randoms) {
- this.randoms = randoms;
- }
-
/**
* Clears all added randoms
*/
@@ -104,15 +96,16 @@ public class RandomHandler {
* Executes a specific random
*
* @param r
+ *
* @return True if the random is executed, false if not
*/
- public boolean executeRandom(Random r){
+ public boolean executeRandom(Random r) {
if (r.activate()) {
Logger.addMessage("Running random '" + r.getName() + "'", true);
try {
r.execute();
return true;
- }catch (Exception e){
+ } catch (Exception e) {
Logger.addMessage("Random failed: '" + r.getName() + "'", false);
e.printStackTrace();
}
@@ -126,7 +119,7 @@ public class RandomHandler {
*
* @param type
*/
- public void runAll(RandomType type){
+ public void runAll(RandomType type) {
for (Random r : this.activeRandoms) {
if (r.getRandomType().getId() == type.getId()) {
executeRandom(r);
@@ -152,6 +145,7 @@ public class RandomHandler {
* Checks if random occurs and runs it
*
* @return returns true if a random has been executed, otherwise false
+ *
* @see RandomHandler#checkAndRun(RandomType)
* @deprecated
*/
@@ -165,6 +159,15 @@ public class RandomHandler {
return this.randoms;
}
+ /**
+ * Sets the whole random arraylist to the arraylist given as argument
+ *
+ * @param randoms The new random arraylist
+ */
+ public void setRandoms(ArrayList randoms) {
+ this.randoms = randoms;
+ }
+
public ArrayList getActiveRandoms() {
return this.activeRandoms;
}
diff --git a/src/main/java/org/parabot/environment/randoms/RandomType.java b/src/main/java/org/parabot/environment/randoms/RandomType.java
index 3743812..7232f23 100644
--- a/src/main/java/org/parabot/environment/randoms/RandomType.java
+++ b/src/main/java/org/parabot/environment/randoms/RandomType.java
@@ -10,7 +10,7 @@ public enum RandomType {
ON_SERVER_START(2, "On server start"),
ON_SCRIPT_FINISH(3, "On script finish");
- private int id;
+ private int id;
private String name;
RandomType(int id, String name) {
@@ -18,6 +18,10 @@ public enum RandomType {
this.name = name;
}
+ public static RandomType getDefault() {
+ return SCRIPT;
+ }
+
public int getId() {
return id;
}
@@ -25,8 +29,4 @@ public enum RandomType {
public String getName() {
return name;
}
-
- public static RandomType getDefault() {
- return SCRIPT;
- }
}
diff --git a/src/main/java/org/parabot/environment/scripts/Category.java b/src/main/java/org/parabot/environment/scripts/Category.java
index 9cad4c4..523b689 100644
--- a/src/main/java/org/parabot/environment/scripts/Category.java
+++ b/src/main/java/org/parabot/environment/scripts/Category.java
@@ -5,54 +5,53 @@ import org.parabot.core.ui.images.Images;
import java.awt.image.BufferedImage;
import java.util.HashMap;
-
/**
- *
* Holds script categories
- *
+ *
* @author Dane, Paradox
- *
*/
-public enum Category
-{
+public enum Category {
- AGILITY, COMBAT, COOKING, CRAFTING, CONSTRUCTION, DUNGEONEERING, FARMING, FIREMAKING, FISHING, FLETCHING, HERBLORE, HUNTER, MAGIC, MINIGAMES, MINING, MONEYMAKING, OTHER, PRAYER, RUNECRAFTING, SLAYER, SMITHING, THIEVING, UTILITY, WOODCUTTING;
+ AGILITY, COMBAT, COOKING, CRAFTING, CONSTRUCTION, DUNGEONEERING, FARMING, FIREMAKING, FISHING, FLETCHING, HERBLORE, HUNTER, MAGIC, MINIGAMES, MINING, MONEYMAKING, OTHER, PRAYER, RUNECRAFTING, SLAYER, SMITHING, THIEVING, UTILITY, WOODCUTTING;
- /**
- * Gets image belonging to this category
- * @return icon
- */
- public BufferedImage getIcon() {
- return Category.getIcon(this.name().toLowerCase());
- }
+ /**
+ * Cache
+ */
+ private static HashMap images = new HashMap<>();
- /**
- * Gets category icon image from filename
- * @param s Name of the image - used for the hashmap index
- * @return icon
- */
- public static BufferedImage getIcon(String s) {
- if (images.get(s) == null) {
- images.put(s, Images.getResource("/storage/images/category/" + s + ".png"));
- }
- return images.get(s);
- }
+ static {
+ images.put("script", Images.getResource("/storage/images/category/script.png"));
+ }
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder();
- b.append(name().charAt(0));
- b.append(name().toLowerCase().substring(1));
- return new String(b);
- }
+ /**
+ * Gets category icon image from filename
+ *
+ * @param s Name of the image - used for the hashmap index
+ *
+ * @return icon
+ */
+ public static BufferedImage getIcon(String s) {
+ if (images.get(s) == null) {
+ images.put(s, Images.getResource("/storage/images/category/" + s + ".png"));
+ }
+ return images.get(s);
+ }
- /**
- * Cache
- */
- private static HashMap images = new HashMap<>();
+ /**
+ * Gets image belonging to this category
+ *
+ * @return icon
+ */
+ public BufferedImage getIcon() {
+ return Category.getIcon(this.name().toLowerCase());
+ }
- static {
- images.put("script", Images.getResource("/storage/images/category/script.png"));
- }
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder();
+ b.append(name().charAt(0));
+ b.append(name().toLowerCase().substring(1));
+ return new String(b);
+ }
}
diff --git a/src/main/java/org/parabot/environment/scripts/Frameworks.java b/src/main/java/org/parabot/environment/scripts/Frameworks.java
index 0f66eea..af5d40f 100644
--- a/src/main/java/org/parabot/environment/scripts/Frameworks.java
+++ b/src/main/java/org/parabot/environment/scripts/Frameworks.java
@@ -1,67 +1,66 @@
package org.parabot.environment.scripts;
-import java.util.Collection;
-
import org.parabot.environment.scripts.framework.AbstractFramework;
import org.parabot.environment.scripts.framework.LoopTask;
import org.parabot.environment.scripts.framework.Strategy;
+import java.util.Collection;
+
/**
- *
* Holds various script frameworks
- *
- * @author Everel
*
+ * @author Everel
*/
public class Frameworks {
-
- public static Looper getLooper(LoopTask loopTask) {
- return new Looper(loopTask);
- }
-
- public static StrategyWorker getStrategyWorker(Collection strategies) {
- return new StrategyWorker(strategies);
- }
+
+ public static Looper getLooper(LoopTask loopTask) {
+ return new Looper(loopTask);
+ }
+
+ public static StrategyWorker getStrategyWorker(Collection strategies) {
+ return new StrategyWorker(strategies);
+ }
}
class Looper extends AbstractFramework {
- private LoopTask loopTask = null;
-
- public Looper(LoopTask loopTask) {
- this.loopTask = loopTask;
- }
- @Override
- public boolean execute() {
- int sleepTime = loopTask.loop();
- if(sleepTime < 0) {
- return false;
- }
- try {
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return true;
- }
+ private LoopTask loopTask = null;
+
+ public Looper(LoopTask loopTask) {
+ this.loopTask = loopTask;
+ }
+
+ @Override
+ public boolean execute() {
+ int sleepTime = loopTask.loop();
+ if (sleepTime < 0) {
+ return false;
+ }
+ try {
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ return true;
+ }
}
class StrategyWorker extends AbstractFramework {
- private Collection strategies;
-
- public StrategyWorker(Collection strategies) {
- this.strategies = strategies;
- }
+ private Collection strategies;
+
+ public StrategyWorker(Collection strategies) {
+ this.strategies = strategies;
+ }
+
+ @Override
+ public boolean execute() {
+ for (Strategy s : strategies) {
+ if (s.activate()) {
+ s.execute();
+ return true;
+ }
+ }
+ return true;
+ }
- @Override
- public boolean execute() {
- for(Strategy s : strategies) {
- if(s.activate()) {
- s.execute();
- return true;
- }
- }
- return true;
- }
-
}
diff --git a/src/main/java/org/parabot/environment/scripts/Script.java b/src/main/java/org/parabot/environment/scripts/Script.java
index 21527b0..b07b0c6 100644
--- a/src/main/java/org/parabot/environment/scripts/Script.java
+++ b/src/main/java/org/parabot/environment/scripts/Script.java
@@ -6,10 +6,10 @@ import org.parabot.core.ui.BotUI;
import org.parabot.core.ui.Logger;
import org.parabot.environment.api.utils.PBPreferences;
import org.parabot.environment.api.utils.Time;
+import org.parabot.environment.randoms.Random;
import org.parabot.environment.randoms.RandomType;
import org.parabot.environment.scripts.framework.*;
import org.parabot.environment.scripts.framework.Frameworks;
-import org.parabot.environment.scripts.randoms.Random;
import java.util.Collection;
@@ -20,19 +20,19 @@ import java.util.Collection;
*/
public class Script implements Runnable {
public static final int TYPE_STRATEGY = 0;
- public static final int TYPE_LOOP = 1;
- public static final int TYPE_OTHER = 2;
+ public static final int TYPE_LOOP = 1;
+ public static final int TYPE_OTHER = 2;
public static final int STATE_RUNNING = 0;
- public static final int STATE_PAUSE = 1;
+ public static final int STATE_PAUSE = 1;
public static final int STATE_STOPPED = 2;
private Collection strategies;
- private PBPreferences preferences;
- private AbstractFramework frameWork;
- private int state;
- private int frameWorkType;
- private int scriptID;
+ private PBPreferences preferences;
+ private AbstractFramework frameWork;
+ private int state;
+ private int frameWorkType;
+ private int scriptID;
public boolean onExecute() {
return true;
@@ -61,6 +61,11 @@ public class Script implements Runnable {
this.frameWork = f;
}
+ @Deprecated
+ public final void addRandom(org.parabot.environment.scripts.randoms.Random random) {
+ new IllegalArgumentException("This type of random is deprecated").printStackTrace();
+ }
+
public final void addRandom(Random random) {
Context.getInstance().getRandomHandler().addRandom(random);
}
@@ -141,6 +146,7 @@ public class Script implements Runnable {
*
* @param conn the condition.
* @param timeout the time in miliseconds before it stops sleeping.
+ *
* @return whether it ran successfully without timing out.
*/
@Deprecated
@@ -148,18 +154,6 @@ public class Script implements Runnable {
return Time.sleep(conn, timeout);
}
- /**
- * Sets the script's state
- *
- * @param state
- */
- public final void setState(final int state) {
- if (state < 0 || state > 2) {
- throw new IllegalArgumentException("Illegal state");
- }
- this.state = state;
- }
-
/**
* Sleeps for an amount of milliseconds
*
@@ -173,6 +167,18 @@ public class Script implements Runnable {
return state;
}
+ /**
+ * Sets the script's state
+ *
+ * @param state
+ */
+ public final void setState(final int state) {
+ if (state < 0 || state > 2) {
+ throw new IllegalArgumentException("Illegal state");
+ }
+ this.state = state;
+ }
+
public PBPreferences getPreferences() {
if (this.preferences == null) {
this.preferences = new PBPreferences(scriptID);
diff --git a/src/main/java/org/parabot/environment/scripts/ScriptManifest.java b/src/main/java/org/parabot/environment/scripts/ScriptManifest.java
index 562ccc5..fcaa090 100644
--- a/src/main/java/org/parabot/environment/scripts/ScriptManifest.java
+++ b/src/main/java/org/parabot/environment/scripts/ScriptManifest.java
@@ -5,26 +5,26 @@ import java.lang.annotation.RetentionPolicy;
/**
* A script manifest, holds all script data
- * @author Everel
*
+ * @author Everel
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ScriptManifest {
- String author();
+ String author();
- String name();
-
- Category category();
+ String name();
- double version();
+ Category category();
- String description();
-
- String[] servers();
-
- boolean vip() default false;
-
- boolean premium() default false;
+ double version();
+
+ String description();
+
+ String[] servers();
+
+ boolean vip() default false;
+
+ boolean premium() default false;
}
\ No newline at end of file
diff --git a/src/main/java/org/parabot/environment/scripts/executers/BDNScriptsExecuter.java b/src/main/java/org/parabot/environment/scripts/executers/BDNScriptsExecuter.java
index fdfc199..80e656c 100644
--- a/src/main/java/org/parabot/environment/scripts/executers/BDNScriptsExecuter.java
+++ b/src/main/java/org/parabot/environment/scripts/executers/BDNScriptsExecuter.java
@@ -15,82 +15,80 @@ import java.net.URL;
import java.net.URLConnection;
/**
- *
* Loads a script from the BDN
- *
- * @author Everel
*
+ * @author Everel
*/
public class BDNScriptsExecuter extends ScriptExecuter {
-
- private static AccountManager manager;
- public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
+ private static AccountManager manager;
- @Override
- public final void setManager(AccountManager manager) {
- BDNScriptsExecuter.manager = manager;
- }
+ public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
- };
-
- private int id = -1;
+ @Override
+ public final void setManager(AccountManager manager) {
+ BDNScriptsExecuter.manager = manager;
+ }
- public BDNScriptsExecuter(final int id) {
- this.id = id;
- }
+ };
- @Override
- public void run(ThreadGroup tg) {
- try {
+ private int id = -1;
+
+ public BDNScriptsExecuter(final int id) {
+ this.id = id;
+ }
+
+ @Override
+ public void run(ThreadGroup tg) {
+ try {
final URLConnection urlConnection = WebUtil.getConnection(new URL(
Configuration.GET_SCRIPT + this.id), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
- final String contentType = urlConnection.getHeaderField("Content-type");
- switch (contentType) {
- case "text/html":
- // failed to fetch script
- UILog.log("Error", "Failed to load BDN script, error: [Page returned: " + WebUtil.getContents(urlConnection) + "]", JOptionPane.ERROR_MESSAGE);
- break;
- case "application/jar":
- //// JAR LOADING PART ////////
- // succesfull request, jar returned
- final ClassPath classPath = new ClassPath();
- classPath.addJar(urlConnection);
+ final String contentType = urlConnection.getHeaderField("Content-type");
+ switch (contentType) {
+ case "text/html":
+ // failed to fetch script
+ UILog.log("Error", "Failed to load BDN script, error: [Page returned: " + WebUtil.getContents(urlConnection) + "]", JOptionPane.ERROR_MESSAGE);
+ break;
+ case "application/jar":
+ //// JAR LOADING PART ////////
+ // succesfull request, jar returned
+ final ClassPath classPath = new ClassPath();
+ classPath.addJar(urlConnection);
- final JavaScriptLoader loader = new JavaScriptLoader(classPath);
- final String[] scriptClasses = loader.getScriptClassNames();
- if (scriptClasses == null || scriptClasses.length == 0) {
- UILog.log("Error", "Failed to load BDN script, error: [No script found in jar file.]", JOptionPane.ERROR_MESSAGE);
- return;
- } else if (scriptClasses.length > 1) {
- UILog.log("Error", "Failed to load BDN script, error: [Multiple scripts found in jar file.]");
- return;
- }
+ final JavaScriptLoader loader = new JavaScriptLoader(classPath);
+ final String[] scriptClasses = loader.getScriptClassNames();
+ if (scriptClasses == null || scriptClasses.length == 0) {
+ UILog.log("Error", "Failed to load BDN script, error: [No script found in jar file.]", JOptionPane.ERROR_MESSAGE);
+ return;
+ } else if (scriptClasses.length > 1) {
+ UILog.log("Error", "Failed to load BDN script, error: [Multiple scripts found in jar file.]");
+ return;
+ }
- final String className = scriptClasses[0];
- try {
- final Class> scriptClass = loader.loadClass(className);
- final Constructor> con = scriptClass.getConstructor();
- final Script script = (Script) con.newInstance();
- script.setScriptID(this.id);
- super.finalize(tg, script);
+ final String className = scriptClasses[0];
+ try {
+ final Class> scriptClass = loader.loadClass(className);
+ final Constructor> con = scriptClass.getConstructor();
+ final Script script = (Script) con.newInstance();
+ script.setScriptID(this.id);
+ super.finalize(tg, script);
- } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
- UILog.log("Error", "Failed to load BDN script, error: [This server provider does not support this script]", JOptionPane.ERROR_MESSAGE);
- } catch (Throwable t) {
- t.printStackTrace();
- UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
- }
- //// END JAR LOADING ////
- break;
- default:
- UILog.log("Error", "Failed to load BDN script, error: [Unknown content type: " + contentType + "]", JOptionPane.ERROR_MESSAGE);
- break;
- }
- } catch (Throwable t) {
- t.printStackTrace();
- UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
- }
- }
+ } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
+ UILog.log("Error", "Failed to load BDN script, error: [This server provider does not support this script]", JOptionPane.ERROR_MESSAGE);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
+ }
+ //// END JAR LOADING ////
+ break;
+ default:
+ UILog.log("Error", "Failed to load BDN script, error: [Unknown content type: " + contentType + "]", JOptionPane.ERROR_MESSAGE);
+ break;
+ }
+ } catch (Throwable t) {
+ t.printStackTrace();
+ UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
+ }
+ }
}
diff --git a/src/main/java/org/parabot/environment/scripts/executers/LocalScriptExecuter.java b/src/main/java/org/parabot/environment/scripts/executers/LocalScriptExecuter.java
index 4b071f4..49a6ca2 100644
--- a/src/main/java/org/parabot/environment/scripts/executers/LocalScriptExecuter.java
+++ b/src/main/java/org/parabot/environment/scripts/executers/LocalScriptExecuter.java
@@ -5,26 +5,24 @@ import org.parabot.environment.scripts.Script;
import java.lang.reflect.Constructor;
/**
- *
* Loads a locally stored script
- *
- * @author Everel
*
+ * @author Everel
*/
public class LocalScriptExecuter extends ScriptExecuter {
- private Constructor> scriptConstructor;
-
- public LocalScriptExecuter(final Constructor> scriptConstructor) {
- this.scriptConstructor = scriptConstructor;
- }
+ private Constructor> scriptConstructor;
- @Override
- public void run(ThreadGroup tg) {
- try {
- super.finalize(tg, (Script) scriptConstructor.newInstance(new Object[] { }));
+ public LocalScriptExecuter(final Constructor> scriptConstructor) {
+ this.scriptConstructor = scriptConstructor;
+ }
+
+ @Override
+ public void run(ThreadGroup tg) {
+ try {
+ super.finalize(tg, (Script) scriptConstructor.newInstance(new Object[]{}));
} catch (Throwable t) {
t.printStackTrace();
}
- }
+ }
}
diff --git a/src/main/java/org/parabot/environment/scripts/executers/ScriptExecuter.java b/src/main/java/org/parabot/environment/scripts/executers/ScriptExecuter.java
index 64723ae..e362884 100644
--- a/src/main/java/org/parabot/environment/scripts/executers/ScriptExecuter.java
+++ b/src/main/java/org/parabot/environment/scripts/executers/ScriptExecuter.java
@@ -3,25 +3,23 @@ package org.parabot.environment.scripts.executers;
import org.parabot.environment.scripts.Script;
/**
- *
* Executes a script
- *
- * @author Everel
*
+ * @author Everel
*/
public abstract class ScriptExecuter {
-
- public abstract void run(final ThreadGroup tg);
-
- /**
- * Start script.
- * @param tg
- * @param script
- */
- public final void finalize(final ThreadGroup tg, final Script script) {
- Thread thread = new Thread(tg, script);
- thread.start();
- }
+ public abstract void run(final ThreadGroup tg);
+
+ /**
+ * Start script.
+ *
+ * @param tg
+ * @param script
+ */
+ public final void finalize(final ThreadGroup tg, final Script script) {
+ Thread thread = new Thread(tg, script);
+ thread.start();
+ }
}
diff --git a/src/main/java/org/parabot/environment/scripts/framework/AbstractFramework.java b/src/main/java/org/parabot/environment/scripts/framework/AbstractFramework.java
index 867e306..156b7ce 100644
--- a/src/main/java/org/parabot/environment/scripts/framework/AbstractFramework.java
+++ b/src/main/java/org/parabot/environment/scripts/framework/AbstractFramework.java
@@ -1,18 +1,17 @@
package org.parabot.environment.scripts.framework;
/**
- *
* Abstract framework for a script
- *
- * @author Everel
*
+ * @author Everel
*/
public abstract class AbstractFramework {
-
- /**
- * Executes this frame
- * @return true if it should keep executing this framework, otherwise false.
- */
- public abstract boolean execute();
+
+ /**
+ * Executes this frame
+ *
+ * @return true if it should keep executing this framework, otherwise false.
+ */
+ public abstract boolean execute();
}
diff --git a/src/main/java/org/parabot/environment/scripts/framework/Frameworks.java b/src/main/java/org/parabot/environment/scripts/framework/Frameworks.java
index 6b600e7..00d3c91 100644
--- a/src/main/java/org/parabot/environment/scripts/framework/Frameworks.java
+++ b/src/main/java/org/parabot/environment/scripts/framework/Frameworks.java
@@ -3,61 +3,60 @@ package org.parabot.environment.scripts.framework;
import java.util.Collection;
/**
- *
* Holds various script frameworks
- *
- * @author Everel
*
+ * @author Everel
*/
public class Frameworks {
-
- public static Looper getLooper(LoopTask loopTask) {
- return new Looper(loopTask);
- }
-
- public static StrategyWorker getStrategyWorker(Collection strategies) {
- return new StrategyWorker(strategies);
- }
+
+ public static Looper getLooper(LoopTask loopTask) {
+ return new Looper(loopTask);
+ }
+
+ public static StrategyWorker getStrategyWorker(Collection strategies) {
+ return new StrategyWorker(strategies);
+ }
}
class Looper extends AbstractFramework {
- private LoopTask loopTask = null;
-
- public Looper(LoopTask loopTask) {
- this.loopTask = loopTask;
- }
- @Override
- public boolean execute() {
- int sleepTime = loopTask.loop();
- if(sleepTime < 0) {
- return false;
- }
- try {
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return true;
- }
+ private LoopTask loopTask = null;
+
+ public Looper(LoopTask loopTask) {
+ this.loopTask = loopTask;
+ }
+
+ @Override
+ public boolean execute() {
+ int sleepTime = loopTask.loop();
+ if (sleepTime < 0) {
+ return false;
+ }
+ try {
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ return true;
+ }
}
class StrategyWorker extends AbstractFramework {
- private Collection strategies;
-
- public StrategyWorker(Collection strategies) {
- this.strategies = strategies;
- }
+ private Collection strategies;
+
+ public StrategyWorker(Collection strategies) {
+ this.strategies = strategies;
+ }
+
+ @Override
+ public boolean execute() {
+ for (Strategy s : strategies) {
+ if (s.activate()) {
+ s.execute();
+ return true;
+ }
+ }
+ return true;
+ }
- @Override
- public boolean execute() {
- for(Strategy s : strategies) {
- if(s.activate()) {
- s.execute();
- return true;
- }
- }
- return true;
- }
-
}
diff --git a/src/main/java/org/parabot/environment/scripts/framework/LoopTask.java b/src/main/java/org/parabot/environment/scripts/framework/LoopTask.java
index 243d1cb..411a9b3 100644
--- a/src/main/java/org/parabot/environment/scripts/framework/LoopTask.java
+++ b/src/main/java/org/parabot/environment/scripts/framework/LoopTask.java
@@ -1,18 +1,15 @@
package org.parabot.environment.scripts.framework;
/**
- *
* A LoopTask interface is used to keep calling the loop method which should return the sleep time
- *
- * @author Everel
*
+ * @author Everel
*/
public interface LoopTask {
-
- /**
- *
- * @return sleepTime in ms
- */
- public int loop();
+
+ /**
+ * @return sleepTime in ms
+ */
+ public int loop();
}
diff --git a/src/main/java/org/parabot/environment/scripts/framework/SleepCondition.java b/src/main/java/org/parabot/environment/scripts/framework/SleepCondition.java
index e2b541a..3c156ec 100644
--- a/src/main/java/org/parabot/environment/scripts/framework/SleepCondition.java
+++ b/src/main/java/org/parabot/environment/scripts/framework/SleepCondition.java
@@ -2,17 +2,17 @@ package org.parabot.environment.scripts.framework;
/**
* Keeps sleeping till a condition is valid
- *
- * @author Everel
*
+ * @author Everel
*/
public interface SleepCondition {
-
- /**
- * Determine if condition is valid
- * @return true if valid, otherwise false.
- */
- public boolean isValid();
+
+ /**
+ * Determine if condition is valid
+ *
+ * @return true if valid, otherwise false.
+ */
+ public boolean isValid();
}
diff --git a/src/main/java/org/parabot/environment/scripts/framework/Strategy.java b/src/main/java/org/parabot/environment/scripts/framework/Strategy.java
index 23413e1..9c31cdb 100644
--- a/src/main/java/org/parabot/environment/scripts/framework/Strategy.java
+++ b/src/main/java/org/parabot/environment/scripts/framework/Strategy.java
@@ -2,21 +2,21 @@ package org.parabot.environment.scripts.framework;
/**
* Strategy framework for scripts
- *
- * @author Everel
*
+ * @author Everel
*/
public interface Strategy {
-
- /**
- * Whether to activate this strategy
- * @return true if this strategy should be executed, otherwise false.
- */
- public boolean activate();
-
- /**
- * Executes this strategy
- */
- public void execute();
+
+ /**
+ * Whether to activate this strategy
+ *
+ * @return true if this strategy should be executed, otherwise false.
+ */
+ public boolean activate();
+
+ /**
+ * Executes this strategy
+ */
+ public void execute();
}
diff --git a/src/main/java/org/parabot/environment/scripts/loader/JavaScriptLoader.java b/src/main/java/org/parabot/environment/scripts/loader/JavaScriptLoader.java
index 664266e..4fd5466 100644
--- a/src/main/java/org/parabot/environment/scripts/loader/JavaScriptLoader.java
+++ b/src/main/java/org/parabot/environment/scripts/loader/JavaScriptLoader.java
@@ -1,43 +1,41 @@
package org.parabot.environment.scripts.loader;
-import java.util.ArrayList;
-import java.util.List;
-
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.scripts.Script;
+import java.util.ArrayList;
+import java.util.List;
+
/**
- *
* An environment to load a script
- *
+ *
* @author Everel
- *
- *
*/
public class JavaScriptLoader extends ASMClassLoader {
- private ClassPath classPath;
+ private ClassPath classPath;
- public JavaScriptLoader(ClassPath classPath) {
- super(classPath);
- this.classPath = classPath;
- }
+ public JavaScriptLoader(ClassPath classPath) {
+ super(classPath);
+ this.classPath = classPath;
+ }
-
- /**
- * Gets all classes that extends ServerProvider
- * @return string array of class names that extends ServerProvider
- */
- public final String[] getScriptClassNames() {
- final List classNames = new ArrayList();
- for (ClassNode c : classPath.classes.values())
- if (c.superName.replace('/', '.').equals(
- Script.class.getName())) {
- classNames.add(c.name.replace('/', '.'));
- }
- return classNames.toArray(new String[classNames.size()]);
- }
+ /**
+ * Gets all classes that extends ServerProvider
+ *
+ * @return string array of class names that extends ServerProvider
+ */
+ public final String[] getScriptClassNames() {
+ final List classNames = new ArrayList();
+ for (ClassNode c : classPath.classes.values()) {
+ if (c.superName.replace('/', '.').equals(
+ Script.class.getName())) {
+ classNames.add(c.name.replace('/', '.'));
+ }
+ }
+ return classNames.toArray(new String[classNames.size()]);
+ }
}
diff --git a/src/main/java/org/parabot/environment/scripts/randoms/Random.java b/src/main/java/org/parabot/environment/scripts/randoms/Random.java
index 07b9e04..772da2d 100644
--- a/src/main/java/org/parabot/environment/scripts/randoms/Random.java
+++ b/src/main/java/org/parabot/environment/scripts/randoms/Random.java
@@ -2,31 +2,34 @@ package org.parabot.environment.scripts.randoms;
/**
* @author Everel
- * @deprecated
* @see org.parabot.environment.randoms.Random
+ * @deprecated
*/
@Deprecated
public interface Random {
- /**
- * Determines whether this random should activate
- * @return true if this random should activate
- */
- public boolean activate();
+ /**
+ * Determines whether this random should activate
+ *
+ * @return true if this random should activate
+ */
+ public boolean activate();
- /**
- * Executes this random
- */
- public void execute();
+ /**
+ * Executes this random
+ */
+ public void execute();
/**
* Returns the name of the random
+ *
* @return Name of the random
*/
public String getName();
/**
* Returns the name of the server which the random is made for
+ *
* @return Name of the server
*/
public String getServer();
diff --git a/src/main/java/org/parabot/environment/scripts/randoms/RandomHandler.java b/src/main/java/org/parabot/environment/scripts/randoms/RandomHandler.java
index 12ffe85..f3a8dd6 100644
--- a/src/main/java/org/parabot/environment/scripts/randoms/RandomHandler.java
+++ b/src/main/java/org/parabot/environment/scripts/randoms/RandomHandler.java
@@ -2,8 +2,8 @@ package org.parabot.environment.scripts.randoms;
/**
* @author Everel
- * @deprecated
* @see org.parabot.environment.randoms.RandomHandler
+ * @deprecated
*/
@Deprecated
public class RandomHandler extends org.parabot.environment.randoms.RandomHandler {
diff --git a/src/main/java/org/parabot/environment/servers/LocalServerExecuter.java b/src/main/java/org/parabot/environment/servers/LocalServerExecuter.java
index 257a9c8..060f1ec 100644
--- a/src/main/java/org/parabot/environment/servers/LocalServerExecuter.java
+++ b/src/main/java/org/parabot/environment/servers/LocalServerExecuter.java
@@ -9,44 +9,42 @@ import org.parabot.environment.servers.executers.ServerExecuter;
import java.net.MalformedURLException;
/**
- *
* Loads locally stored server providers
- *
+ *
* @author Everel
- *
*/
@SuppressWarnings("Duplicates")
@Deprecated
public class LocalServerExecuter extends ServerExecuter {
- private final ServerProvider serverProvider;
- private ClassPath classPath;
- private String serverName;
+ private final ServerProvider serverProvider;
+ private ClassPath classPath;
+ private String serverName;
- public LocalServerExecuter(ServerProvider serverProvider,
- ClassPath classPath, final String serverName) {
- this.serverProvider = serverProvider;
- this.classPath = classPath;
- this.serverName = serverName;
- }
+ public LocalServerExecuter(ServerProvider serverProvider,
+ ClassPath classPath, final String serverName) {
+ this.serverProvider = serverProvider;
+ this.classPath = classPath;
+ this.serverName = serverName;
+ }
- @Override
- public void run() {
- // add jar or directory to buildpath.
- if (this.classPath.isJar()) {
- Core.verbose("Adding server provider jar to buildpath: "
- + this.classPath.lastParsed.toString());
- this.classPath.addToBuildPath();
- } else {
- Core.verbose("Adding server providers directory to buildpath: "
- + Directories.getServerPath().getPath());
- try {
- BuildPath.add(Directories.getServerPath().toURI().toURL());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
- // finalize
- super.finalize(this.serverProvider, this.serverName);
- }
+ @Override
+ public void run() {
+ // add jar or directory to buildpath.
+ if (this.classPath.isJar()) {
+ Core.verbose("Adding server provider jar to buildpath: "
+ + this.classPath.lastParsed.toString());
+ this.classPath.addToBuildPath();
+ } else {
+ Core.verbose("Adding server providers directory to buildpath: "
+ + Directories.getServerPath().getPath());
+ try {
+ BuildPath.add(Directories.getServerPath().toURI().toURL());
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ }
+ // finalize
+ super.finalize(this.serverProvider, this.serverName);
+ }
}
diff --git a/src/main/java/org/parabot/environment/servers/ServerManifest.java b/src/main/java/org/parabot/environment/servers/ServerManifest.java
index 1089625..c45e566 100644
--- a/src/main/java/org/parabot/environment/servers/ServerManifest.java
+++ b/src/main/java/org/parabot/environment/servers/ServerManifest.java
@@ -5,18 +5,18 @@ import java.lang.annotation.RetentionPolicy;
/**
* A server manifest
- * @author Everel
*
+ * @author Everel
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ServerManifest {
- String author();
+ String author();
- String name();
+ String name();
- double version();
+ double version();
- Type type();
+ Type type();
}
diff --git a/src/main/java/org/parabot/environment/servers/ServerProvider.java b/src/main/java/org/parabot/environment/servers/ServerProvider.java
index 6fb090b..da9b465 100644
--- a/src/main/java/org/parabot/environment/servers/ServerProvider.java
+++ b/src/main/java/org/parabot/environment/servers/ServerProvider.java
@@ -10,141 +10,140 @@ import org.parabot.environment.input.Mouse;
import org.parabot.environment.scripts.Script;
import javax.swing.*;
-
import java.applet.Applet;
import java.applet.AppletStub;
-import java.awt.Dimension;
+import java.awt.*;
import java.net.URL;
/**
* Provides a server to the bot
- *
+ *
* @author Everel
- *
*/
public abstract class ServerProvider implements Opcodes {
- /**
- * Get the game/applet dimensions
- * @return game/applet dimensions
- */
- public Dimension getGameDimensions() {
- return new Dimension(765, 503);
- }
+ /**
+ * Get the game/applet dimensions
+ *
+ * @return game/applet dimensions
+ */
+ public Dimension getGameDimensions() {
+ return new Dimension(765, 503);
+ }
/**
- * Hooks to parse
- *
- * @deprecated use getHookFile() now
- * @return URL to hooks file
- */
- @Deprecated
- public URL getHooks() {
- return null;
- }
-
- /**
- * Get hook file to parse
- * @return hook file
- */
- public HookFile getHookFile() {
- return null;
- }
+ * Hooks to parse
+ *
+ * @return URL to hooks file
+ *
+ * @deprecated use getHookFile() now
+ */
+ @Deprecated
+ public URL getHooks() {
+ return null;
+ }
- /**
- * Jar to parse
- *
- * @return URL to client jar
- */
- public abstract URL getJar();
+ /**
+ * Get hook file to parse
+ *
+ * @return hook file
+ */
+ public HookFile getHookFile() {
+ return null;
+ }
- public abstract Applet fetchApplet();
+ /**
+ * Jar to parse
+ *
+ * @return URL to client jar
+ */
+ public abstract URL getJar();
- public String getAccessorsPackage() {
- return null;
- }
+ public abstract Applet fetchApplet();
- public void injectHooks() {
- HookFile hookFile = fetchHookFile();
-
- if(hookFile == null) {
- return;
- }
-
- HookParser parser = hookFile.getParser();
- Injectable[] injectables = parser.getInjectables();
- if (injectables == null) {
- return;
- }
- for (Injectable inj : injectables) {
- inj.inject();
- }
- Context.getInstance().setHookParser(parser);
- }
-
- private HookFile fetchHookFile() {
- HookFile hookFile = getHookFile();
- if(hookFile != null) {
- return hookFile;
- }
-
- URL hookLocation = getHooks();
- if(hookLocation == null) {
- return null;
- }
-
- return new HookFile(hookLocation, HookFile.TYPE_XML);
- }
+ public String getAccessorsPackage() {
+ return null;
+ }
- /**
- * Add custom items to the bot menu bar
- *
- * @param bar
- * menu bar to add items on
- */
- public void addMenuItems(JMenuBar bar) {
- }
+ public void injectHooks() {
+ HookFile hookFile = fetchHookFile();
- public AppletStub getStub() {
- return null;
- }
-
- public void setClientInstance(Object client) {
- Context.getInstance().setClientInstance(client);
- }
+ if (hookFile == null) {
+ return;
+ }
- public void parseJar() {
- Context.getInstance().getClassPath().addJar(getJar());
- }
-
- public void initScript(Script script) {
-
- }
-
- public void init() {
-
- }
-
- public void initMouse() {
- final Context context = Context.getInstance();
- final Applet applet = context.getApplet();
- final Mouse mouse = new Mouse(applet);
- applet.addMouseListener(mouse);
- applet.addMouseMotionListener(mouse);
- context.setMouse(mouse);
- }
-
- public void initKeyboard() {
- final Context context = Context.getInstance();
- final Applet applet = context.getApplet();
- final Keyboard keyboard = new Keyboard(applet);
- applet.addKeyListener(keyboard);
- context.setKeyboard(keyboard);
- }
-
- public void unloadScript(Script script) {
-
- }
+ HookParser parser = hookFile.getParser();
+ Injectable[] injectables = parser.getInjectables();
+ if (injectables == null) {
+ return;
+ }
+ for (Injectable inj : injectables) {
+ inj.inject();
+ }
+ Context.getInstance().setHookParser(parser);
+ }
+ private HookFile fetchHookFile() {
+ HookFile hookFile = getHookFile();
+ if (hookFile != null) {
+ return hookFile;
+ }
+
+ URL hookLocation = getHooks();
+ if (hookLocation == null) {
+ return null;
+ }
+
+ return new HookFile(hookLocation, HookFile.TYPE_XML);
+ }
+
+ /**
+ * Add custom items to the bot menu bar
+ *
+ * @param bar menu bar to add items on
+ */
+ public void addMenuItems(JMenuBar bar) {
+ }
+
+ public AppletStub getStub() {
+ return null;
+ }
+
+ public void setClientInstance(Object client) {
+ Context.getInstance().setClientInstance(client);
+ }
+
+ public void parseJar() {
+ Context.getInstance().getClassPath().addJar(getJar());
+ }
+
+ public void initScript(Script script) {
+
+ }
+
+ public void init() {
+
+ }
+
+ public void initMouse() {
+ final Context context = Context.getInstance();
+ final Applet applet = context.getApplet();
+ final Mouse mouse = new Mouse(applet);
+ applet.addMouseListener(mouse);
+ applet.addMouseMotionListener(mouse);
+ context.setMouse(mouse);
+ }
+
+ public void initKeyboard() {
+ final Context context = Context.getInstance();
+ final Applet applet = context.getApplet();
+ final Keyboard keyboard = new Keyboard(applet);
+ applet.addKeyListener(keyboard);
+ context.setKeyboard(keyboard);
+ }
+
+ public void unloadScript(Script script) {
+
+ }
}
diff --git a/src/main/java/org/parabot/environment/servers/Type.java b/src/main/java/org/parabot/environment/servers/Type.java
index 4ca7ee6..5fd8135 100644
--- a/src/main/java/org/parabot/environment/servers/Type.java
+++ b/src/main/java/org/parabot/environment/servers/Type.java
@@ -1,14 +1,12 @@
package org.parabot.environment.servers;
/**
- *
* Server provider type
- *
- * @author Everel
*
+ * @author Everel
*/
public enum Type {
-
- INJECTION, REFLECTION, COLOR, LOADER, OTHER
+
+ INJECTION, REFLECTION, COLOR, LOADER, OTHER
}
diff --git a/src/main/java/org/parabot/environment/servers/executers/LocalPublicServerExecuter.java b/src/main/java/org/parabot/environment/servers/executers/LocalPublicServerExecuter.java
index 912745c..3f06b14 100644
--- a/src/main/java/org/parabot/environment/servers/executers/LocalPublicServerExecuter.java
+++ b/src/main/java/org/parabot/environment/servers/executers/LocalPublicServerExecuter.java
@@ -1,14 +1,11 @@
package org.parabot.environment.servers.executers;
-import org.parabot.core.Configuration;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.desc.ServerProviderInfo;
-import org.parabot.core.forum.AccountManager;
-import org.parabot.core.forum.AccountManagerAccess;
import org.parabot.core.ui.components.VerboseLoader;
import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.FileUtil;
@@ -22,113 +19,111 @@ import java.lang.reflect.Constructor;
import java.net.URL;
/**
- *
* Fetches a server provider from the local config file
- *
+ *
* @author JKetelaar
- *
*/
public class LocalPublicServerExecuter extends ServerExecuter {
- private String serverName;
- private String serverUrl;
- private String providerUrl;
- private ServerProviderInfo serverProviderInfo;
+ private String serverName;
+ private String serverUrl;
+ private String providerUrl;
+ private ServerProviderInfo serverProviderInfo;
- public LocalPublicServerExecuter(final String serverName, final ServerProviderInfo serverProviderInfo, String serverUrl, String providerUrl) {
- this.serverName = serverName;
- this.serverUrl = serverUrl;
- this.providerUrl = providerUrl;
- this.serverProviderInfo = serverProviderInfo;
- }
+ public LocalPublicServerExecuter(final String serverName, final ServerProviderInfo serverProviderInfo, String serverUrl, String providerUrl) {
+ this.serverName = serverName;
+ this.serverUrl = serverUrl;
+ this.providerUrl = providerUrl;
+ this.serverProviderInfo = serverProviderInfo;
+ }
- @Override
- public void run() {
- try {
- final File destination = new File(Directories.getCachePath(),
- serverProviderInfo.getCRC32() + ".jar");
+ @Override
+ public void run() {
+ try {
+ final File destination = new File(Directories.getCachePath(),
+ serverProviderInfo.getCRC32() + ".jar");
- Core.verbose("Downloading: " + providerUrl + " ...");
-
- if(destination.exists()) {
- Core.verbose("Found cached server provider [CRC32: " + serverProviderInfo.getCRC32() + "]");
- } else {
- File local;
- if ((local = new File(providerUrl)).exists()){
- FileUtil.copyFile(local, destination);
- Core.verbose("Server provider copied...");
- }else {
- WebUtil.downloadFile(new URL(providerUrl), destination, VerboseLoader.get());
- Core.verbose("Server provider downloaded...");
- }
- }
+ Core.verbose("Downloading: " + providerUrl + " ...");
- final File clientDestination = new File(Directories.getCachePath(),
- serverProviderInfo.getClientCRC32() + ".jar");
+ if (destination.exists()) {
+ Core.verbose("Found cached server provider [CRC32: " + serverProviderInfo.getCRC32() + "]");
+ } else {
+ File local;
+ if ((local = new File(providerUrl)).exists()) {
+ FileUtil.copyFile(local, destination);
+ Core.verbose("Server provider copied...");
+ } else {
+ WebUtil.downloadFile(new URL(providerUrl), destination, VerboseLoader.get());
+ Core.verbose("Server provider downloaded...");
+ }
+ }
- Core.verbose("Downloading: " + serverUrl + " ...");
+ final File clientDestination = new File(Directories.getCachePath(),
+ serverProviderInfo.getClientCRC32() + ".jar");
- if(clientDestination.exists()) {
- Core.verbose("Found cached client [CRC32: " + serverProviderInfo.getClientCRC32() + "]");
- } else {
- File local;
- if ((local = new File(serverUrl)).exists()){
- FileUtil.copyFile(local, clientDestination);
- Core.verbose("Server client copied...");
- }else {
- WebUtil.downloadFile(new URL(serverUrl), clientDestination, VerboseLoader.get());
- Core.verbose("Server client downloaded...");
- }
- }
+ Core.verbose("Downloading: " + serverUrl + " ...");
- final ClassPath classPath = new ClassPath();
- classPath.addJar(destination);
+ if (clientDestination.exists()) {
+ Core.verbose("Found cached client [CRC32: " + serverProviderInfo.getClientCRC32() + "]");
+ } else {
+ File local;
+ if ((local = new File(serverUrl)).exists()) {
+ FileUtil.copyFile(local, clientDestination);
+ Core.verbose("Server client copied...");
+ } else {
+ WebUtil.downloadFile(new URL(serverUrl), clientDestination, VerboseLoader.get());
+ Core.verbose("Server client downloaded...");
+ }
+ }
- BuildPath.add(destination.toURI().toURL());
+ final ClassPath classPath = new ClassPath();
+ classPath.addJar(destination);
- ServerLoader serverLoader = new ServerLoader(classPath);
- final String[] classNames = serverLoader.getServerClassNames();
- if (classNames.length == 0) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [No provider found in jar file.]",
- JOptionPane.ERROR_MESSAGE);
- return;
- } else if (classNames.length > 1) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [Multiple providers found in jar file.]");
- return;
- }
+ BuildPath.add(destination.toURI().toURL());
- final String className = classNames[0];
- try {
- final Class> providerClass = serverLoader
- .loadClass(className);
- final Constructor> con = providerClass.getConstructor();
- final ServerProvider serverProvider = (ServerProvider) con
- .newInstance();
- Context.getInstance(serverProvider).setProviderInfo(serverProviderInfo);
- super.finalize(serverProvider, this.serverName);
- } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [This server provider is not compatible with this version of parabot]",
- JOptionPane.ERROR_MESSAGE);
- } catch (Throwable t) {
- t.printStackTrace();
- UILog.log(
- "Error",
- "Failed to load server provider.",
- JOptionPane.ERROR_MESSAGE);
- }
+ ServerLoader serverLoader = new ServerLoader(classPath);
+ final String[] classNames = serverLoader.getServerClassNames();
+ if (classNames.length == 0) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [No provider found in jar file.]",
+ JOptionPane.ERROR_MESSAGE);
+ return;
+ } else if (classNames.length > 1) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [Multiple providers found in jar file.]");
+ return;
+ }
- } catch (Exception e) {
- e.printStackTrace();
- UILog.log(
- "Error",
- "Failed to load server provider, post the stacktrace/error on the parabot forums.",
- JOptionPane.ERROR_MESSAGE);
- }
+ final String className = classNames[0];
+ try {
+ final Class> providerClass = serverLoader
+ .loadClass(className);
+ final Constructor> con = providerClass.getConstructor();
+ final ServerProvider serverProvider = (ServerProvider) con
+ .newInstance();
+ Context.getInstance(serverProvider).setProviderInfo(serverProviderInfo);
+ super.finalize(serverProvider, this.serverName);
+ } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [This server provider is not compatible with this version of parabot]",
+ JOptionPane.ERROR_MESSAGE);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ UILog.log(
+ "Error",
+ "Failed to load server provider.",
+ JOptionPane.ERROR_MESSAGE);
+ }
- }
+ } catch (Exception e) {
+ e.printStackTrace();
+ UILog.log(
+ "Error",
+ "Failed to load server provider, post the stacktrace/error on the parabot forums.",
+ JOptionPane.ERROR_MESSAGE);
+ }
+
+ }
}
diff --git a/src/main/java/org/parabot/environment/servers/executers/LocalServerExecuter.java b/src/main/java/org/parabot/environment/servers/executers/LocalServerExecuter.java
index 135ae02..1ff3a40 100644
--- a/src/main/java/org/parabot/environment/servers/executers/LocalServerExecuter.java
+++ b/src/main/java/org/parabot/environment/servers/executers/LocalServerExecuter.java
@@ -1,55 +1,53 @@
package org.parabot.environment.servers.executers;
-import java.lang.reflect.Constructor;
-import java.net.MalformedURLException;
-
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.servers.ServerProvider;
+import java.lang.reflect.Constructor;
+import java.net.MalformedURLException;
+
/**
- *
* Loads locally stored server providers
- *
+ *
* @author Everel
- *
*/
public class LocalServerExecuter extends ServerExecuter {
- private final Constructor> serverProviderConstructor;
- private ClassPath classPath;
- private String serverName;
+ private final Constructor> serverProviderConstructor;
+ private ClassPath classPath;
+ private String serverName;
- public LocalServerExecuter(Constructor> serverProviderConstructor,
- ClassPath classPath, final String serverName) {
- this.serverProviderConstructor = serverProviderConstructor;
- this.classPath = classPath;
- this.serverName = serverName;
- }
+ public LocalServerExecuter(Constructor> serverProviderConstructor,
+ ClassPath classPath, final String serverName) {
+ this.serverProviderConstructor = serverProviderConstructor;
+ this.classPath = classPath;
+ this.serverName = serverName;
+ }
- @Override
- public void run() {
- // add jar or directory to buildpath.
- if (this.classPath.isJar()) {
- Core.verbose("Adding server provider jar to buildpath: "
- + this.classPath.lastParsed.toString());
- this.classPath.addToBuildPath();
- } else {
- Core.verbose("Adding server providers directory to buildpath: "
- + Directories.getServerPath().getPath());
- try {
- BuildPath.add(Directories.getServerPath().toURI().toURL());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
- // finalize
- try {
- super.finalize((ServerProvider) serverProviderConstructor.newInstance(), this.serverName);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
+ @Override
+ public void run() {
+ // add jar or directory to buildpath.
+ if (this.classPath.isJar()) {
+ Core.verbose("Adding server provider jar to buildpath: "
+ + this.classPath.lastParsed.toString());
+ this.classPath.addToBuildPath();
+ } else {
+ Core.verbose("Adding server providers directory to buildpath: "
+ + Directories.getServerPath().getPath());
+ try {
+ BuildPath.add(Directories.getServerPath().toURI().toURL());
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ }
+ // finalize
+ try {
+ super.finalize((ServerProvider) serverProviderConstructor.newInstance(), this.serverName);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
}
diff --git a/src/main/java/org/parabot/environment/servers/executers/PublicServerExecuter.java b/src/main/java/org/parabot/environment/servers/executers/PublicServerExecuter.java
index 6a54f10..b98bd3c 100644
--- a/src/main/java/org/parabot/environment/servers/executers/PublicServerExecuter.java
+++ b/src/main/java/org/parabot/environment/servers/executers/PublicServerExecuter.java
@@ -16,106 +16,100 @@ import org.parabot.environment.servers.ServerProvider;
import org.parabot.environment.servers.loader.ServerLoader;
import javax.swing.*;
-
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
/**
- *
* Fetches a server provider from the Parabot BDN
- *
+ *
* @author Everel
- *
*/
public class PublicServerExecuter extends ServerExecuter {
- private String serverName;
-
- private static AccountManager manager;
+ private static AccountManager manager;
+ public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
- public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
+ @Override
+ public final void setManager(AccountManager manager) {
+ PublicServerExecuter.manager = manager;
+ }
- @Override
- public final void setManager(AccountManager manager) {
- PublicServerExecuter.manager = manager;
- }
+ };
+ private String serverName;
- };
+ public PublicServerExecuter(final String serverName) {
+ this.serverName = serverName;
+ }
- public PublicServerExecuter(final String serverName) {
- this.serverName = serverName;
- }
+ @Override
+ public void run() {
+ try {
+ ServerProviderInfo serverProviderInfo = new ServerProviderInfo(new URL(Configuration.GET_SERVER_PROVIDER_INFO
+ + this.serverName), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
- @Override
- public void run() {
- try {
- ServerProviderInfo serverProviderInfo = new ServerProviderInfo(new URL(Configuration.GET_SERVER_PROVIDER_INFO
- + this.serverName), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
-
- final File destination = new File(Directories.getCachePath(),
- serverProviderInfo.getCRC32() + ".jar");
- final String jarUrl = String.format(Configuration.GET_SERVER_PROVIDER, Configuration.BOT_VERSION.isNightly(), serverName);
+ final File destination = new File(Directories.getCachePath(),
+ serverProviderInfo.getCRC32() + ".jar");
+ final String jarUrl = String.format(Configuration.GET_SERVER_PROVIDER, Configuration.BOT_VERSION.isNightly(), serverName);
- Core.verbose("Downloading: " + jarUrl + " ...");
-
- if(destination.exists()) {
- Core.verbose("Found cached server provider [CRC32: " + serverProviderInfo.getCRC32() + "]");
- } else {
- WebUtil.downloadFile(new URL(jarUrl), destination,
- VerboseLoader.get());
- Core.verbose("Server provider downloaded...");
- }
+ Core.verbose("Downloading: " + jarUrl + " ...");
+ if (destination.exists()) {
+ Core.verbose("Found cached server provider [CRC32: " + serverProviderInfo.getCRC32() + "]");
+ } else {
+ WebUtil.downloadFile(new URL(jarUrl), destination,
+ VerboseLoader.get());
+ Core.verbose("Server provider downloaded...");
+ }
- final ClassPath classPath = new ClassPath();
- classPath.addJar(destination);
+ final ClassPath classPath = new ClassPath();
+ classPath.addJar(destination);
- BuildPath.add(destination.toURI().toURL());
+ BuildPath.add(destination.toURI().toURL());
- ServerLoader serverLoader = new ServerLoader(classPath);
- final String[] classNames = serverLoader.getServerClassNames();
- if (classNames == null || classNames.length == 0) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [No provider found in jar file.]",
- JOptionPane.ERROR_MESSAGE);
- return;
- } else if (classNames.length > 1) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [Multiple providers found in jar file.]");
- return;
- }
+ ServerLoader serverLoader = new ServerLoader(classPath);
+ final String[] classNames = serverLoader.getServerClassNames();
+ if (classNames == null || classNames.length == 0) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [No provider found in jar file.]",
+ JOptionPane.ERROR_MESSAGE);
+ return;
+ } else if (classNames.length > 1) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [Multiple providers found in jar file.]");
+ return;
+ }
- final String className = classNames[0];
- try {
- final Class> providerClass = serverLoader
- .loadClass(className);
- final Constructor> con = providerClass.getConstructor();
- final ServerProvider serverProvider = (ServerProvider) con
- .newInstance();
- Context.getInstance(serverProvider).setProviderInfo(serverProviderInfo);
- super.finalize(serverProvider, this.serverName);
- } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
- UILog.log(
- "Error",
- "Failed to load server provider, error: [This server provider is not compitable with this version of parabot]",
- JOptionPane.ERROR_MESSAGE);
- } catch (Throwable t) {
- t.printStackTrace();
- UILog.log(
- "Error",
- "Failed to load server provider, post the stacktrace/error on the parabot forums.",
- JOptionPane.ERROR_MESSAGE);
- }
+ final String className = classNames[0];
+ try {
+ final Class> providerClass = serverLoader
+ .loadClass(className);
+ final Constructor> con = providerClass.getConstructor();
+ final ServerProvider serverProvider = (ServerProvider) con
+ .newInstance();
+ Context.getInstance(serverProvider).setProviderInfo(serverProviderInfo);
+ super.finalize(serverProvider, this.serverName);
+ } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
+ UILog.log(
+ "Error",
+ "Failed to load server provider, error: [This server provider is not compitable with this version of parabot]",
+ JOptionPane.ERROR_MESSAGE);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ UILog.log(
+ "Error",
+ "Failed to load server provider, post the stacktrace/error on the parabot forums.",
+ JOptionPane.ERROR_MESSAGE);
+ }
- } catch (Exception e) {
- e.printStackTrace();
- UILog.log(
- "Error",
- "Failed to load server provider, post the stacktrace/error on the parabot forums.",
- JOptionPane.ERROR_MESSAGE);
- }
+ } catch (Exception e) {
+ e.printStackTrace();
+ UILog.log(
+ "Error",
+ "Failed to load server provider, post the stacktrace/error on the parabot forums.",
+ JOptionPane.ERROR_MESSAGE);
+ }
- }
+ }
}
diff --git a/src/main/java/org/parabot/environment/servers/loader/ServerLoader.java b/src/main/java/org/parabot/environment/servers/loader/ServerLoader.java
index 0076800..4ed965b 100644
--- a/src/main/java/org/parabot/environment/servers/loader/ServerLoader.java
+++ b/src/main/java/org/parabot/environment/servers/loader/ServerLoader.java
@@ -1,46 +1,44 @@
package org.parabot.environment.servers.loader;
-import java.util.ArrayList;
-import java.util.List;
-
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.servers.ServerProvider;
+import java.util.ArrayList;
+import java.util.List;
+
/**
- *
* An environment to load a server
- *
+ *
* @author Everel
- *
- *
*/
public class ServerLoader extends ASMClassLoader {
- private ClassPath classPath;
+ private ClassPath classPath;
- public ServerLoader(ClassPath classPath) {
- super(classPath);
- this.classPath = classPath;
- }
+ public ServerLoader(ClassPath classPath) {
+ super(classPath);
+ this.classPath = classPath;
+ }
-
- /**
- * Gets all classes that extends ServerProvider
- * @return string array of class names that extends ServerProvider
- */
- public final String[] getServerClassNames() {
- final List classNames = new ArrayList();
- for (ClassNode c : classPath.classes.values())
- if (c.superName.replace('/', '.').equals(
- ServerProvider.class.getName())) {
- classNames.add(c.name.replace('/', '.'));
- }
- return classNames.toArray(new String[classNames.size()]);
- }
-
- public ClassPath getClassPath() {
- return classPath;
- }
+ /**
+ * Gets all classes that extends ServerProvider
+ *
+ * @return string array of class names that extends ServerProvider
+ */
+ public final String[] getServerClassNames() {
+ final List classNames = new ArrayList();
+ for (ClassNode c : classPath.classes.values()) {
+ if (c.superName.replace('/', '.').equals(
+ ServerProvider.class.getName())) {
+ classNames.add(c.name.replace('/', '.'));
+ }
+ }
+ return classNames.toArray(new String[classNames.size()]);
+ }
+
+ public ClassPath getClassPath() {
+ return classPath;
+ }
}
diff --git a/src/test/java/org/parabot/TimerTest.java b/src/test/java/org/parabot/TimerTest.java
new file mode 100644
index 0000000..8a98b9c
--- /dev/null
+++ b/src/test/java/org/parabot/TimerTest.java
@@ -0,0 +1,26 @@
+package org.parabot;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.parabot.environment.api.utils.Timer;
+
+/**
+ * @author JKetelaar
+ */
+public class TimerTest {
+
+ @Test
+ public void test(){
+ Timer timer1 = new Timer(0, System.currentTimeMillis() - (1000 * 60 * 60 * 24));
+ Assert.assertEquals(timer1.toString(), "1d:00:00:00");
+
+ Timer timer2 = new Timer(0, System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 5));
+ Assert.assertEquals(timer2.toString(), "5d:00:00:00");
+
+ Timer timer3 = new Timer(0, System.currentTimeMillis() - (1000 * 60 * 60));
+ Assert.assertEquals(timer3.toString(), "01:00:00");
+
+ Timer timer4 = new Timer(0, System.currentTimeMillis() - (1000 * 60 * 60 * 12));
+ Assert.assertEquals(timer4.toString(), "12:00:00");
+ }
+}