Revert "Fixed bot dialog"

This reverts commit 000bd80699.
This commit is contained in:
JKetelaar
2015-01-31 02:56:21 +01:00
parent 89f8b3526d
commit ddc65bdfa8
262 changed files with 0 additions and 54509 deletions
@@ -1,50 +0,0 @@
package org.parabot.environment;
import org.parabot.core.Core;
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.lib.Library;
import org.parabot.core.lib.javafx.JavaFX;
import org.parabot.core.parsers.servers.ServerParser;
import org.parabot.core.ui.components.VerboseLoader;
import org.parabot.environment.api.utils.WebUtil;
import java.util.LinkedList;
/**
*
* Initiliazes the bot environment
*
* @author Everel
*
*/
public class Environment {
/**
* Loads a new environment
*
* @param desc
*/
public static void load(final ServerDescription desc) {
LinkedList<Library> libs = new LinkedList<>();
libs.add(new JavaFX());
for(Library lib : libs) {
if(!lib.hasJar()) {
Core.verbose("Downloading " + lib.getLibraryName() + "...");
VerboseLoader.setState("Downloading " + lib.getLibraryName() + "...");
WebUtil.downloadFile(lib.getDownloadLink(), lib.getJarFile(), VerboseLoader.get());
Core.verbose("Downloaded " + lib.getLibraryName() + ".");
}
Core.verbose("Initializing " + lib.getLibraryName());
lib.init();
}
Core.verbose("Loading server: " + desc.toString());
ServerParser.SERVER_CACHE.get(desc).run();
}
}
@@ -1,25 +0,0 @@
package org.parabot.environment;
/**
*
* This class is used for detecting the user's operating system
*
* @author Everel
*
*/
public enum OperatingSystem {
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;
}
}
@@ -1,17 +0,0 @@
package org.parabot.environment.api.interfaces;
import java.awt.Graphics;
/**
*
* @author Everel
*
*/
public interface Paintable {
/**
* @param g
*/
public void paint(Graphics g);
}
@@ -1,17 +0,0 @@
package org.parabot.environment.api.utils;
/**
* A simple class to filter things out of an collection
*
* @author Everel
*
* @param <F>
*/
public interface Filter<F> {
/**
* Determines if this object should be accepted
* @param f
* @return <b>true</b> to include this object, otherwise <b>false</b> to exclude.
*/
public boolean accept(F f);
}
@@ -1,46 +0,0 @@
package org.parabot.environment.api.utils;
import java.math.BigInteger;
/**
*
* Helper class for calculating setters for clients that uses multipliers
*
* @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 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;
}
}
@@ -1,28 +0,0 @@
package org.parabot.environment.api.utils;
/**
*
* A random class is used for generating random numbers
*
* @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);
}
}
}
@@ -1,30 +0,0 @@
package org.parabot.environment.api.utils;
/**
*
* @author mkyong
*
*/
public class StringUtils {
public static String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < hex.length() - 1; i += 2) {
// grab the hex in pairs
String output = hex.substring(i, (i + 2));
// convert hex to decimal
int decimal = Integer.parseInt(output, 16);
// convert the decimal to character
sb.append((char) decimal);
temp.append(decimal);
}
return sb.toString();
}
}
@@ -1,68 +0,0 @@
package org.parabot.environment.api.utils;
import org.parabot.environment.scripts.framework.SleepCondition;
/**
*
* Holds various Time utilities
*
* @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();
}
}
@@ -1,120 +0,0 @@
package org.parabot.environment.api.utils;
/**
*
* A simple timer class
*
* @author Everel, Parameter
*
*/
public class Timer {
private long start;
private long end;
/**
* Timer Constructor
*
* @param start
*/
public Timer(long end) {
start = System.currentTimeMillis();
this.end = System.currentTimeMillis() + end;
}
/**
* Timer Constructor
*/
public Timer() {
this(0);
}
/**
* 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;
}
/**
* 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
*/
public void stop() {
end = (end - start) + System.currentTimeMillis();
start = 0;
}
/**
* Determines if timer is running
*
* @return <b>true</b> 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;
}
/**
* 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);
}
}
@@ -1,270 +0,0 @@
package org.parabot.environment.api.utils;
import org.parabot.core.io.ProgressListener;
import org.parabot.core.io.SizeInputStream;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
*
* A WebUtil class fetches data from an URL
*
* @author Everel
*
*/
public class WebUtil {
private static String agent = "Mozilla/5.0 (Wind0ws NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
/**
* Agent to set at a URL connection
*
* @param userAgent
*/
public static void setUserAgent(final String userAgent) {
agent = userAgent;
}
/**
* Gets useragent
*
* @return useragent
*/
public static String getUserAgent() {
return agent;
}
/**
* Fetches content of a page
*
* @param location
* @return contents of page
* @throws MalformedURLException
*/
public static String getContents(final String location)
throws MalformedURLException {
return getContents(new URL(location));
}
/**
* Get contents from URL
*
* @param url
* @return page contents
*/
public static String getContents(final URL url) {
return getContents(getConnection(url));
}
/**
* Gets contents from URLConnection
*
* @param urlConnection
* @return page contents
*/
public static String getContents(URLConnection urlConnection) {
try {
final BufferedReader in = getReader(urlConnection);
final StringBuilder builder = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
builder.append(line);
}
in.close();
return builder.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Gets buffered reader from string url
*
* @param url
* @return bufferedreader
*/
public static BufferedReader getReader(final String url) {
try {
return getReader(new URL(url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
* Gets BufferedReader from URL
*
* @param url
* @return BufferedReader from URL
*/
public static BufferedReader getReader(final URL url) {
return getReader(getConnection(url));
}
public static BufferedReader getReader(final URLConnection urlConnection) {
try {
return new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Gets inputstream from url
*
* @param url
* @return inputstream from url
*/
public static InputStream getInputStream(final URL url) {
final URLConnection con = getConnection(url);
try {
return con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Opens a connection
*
* @param url
* @return URLConnection to URL
*/
public static URLConnection getConnection(final URL url) {
try {
final URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", agent);
return con;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static BufferedReader getReader(final URL url, String username, String password) {
try {
String data = URLEncoder.encode("username", "UTF-8") + "=" + username;
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + password;
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static URLConnection getConnection(final URL url, String username, String password) {
try {
String data = URLEncoder.encode("username", "UTF-8") + "=" + username;
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + password;
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return connection;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Downloads a file on the internet
* @param url
* @param destination
* @param listener
*/
public static void downloadFile(final URL url, final File destination,
final ProgressListener listener) {
try {
final URLConnection connection = getConnection(url);
int size = connection.getContentLength();
SizeInputStream sizeInputStream = new SizeInputStream(
connection.getInputStream(), size, listener);
BufferedInputStream in = new BufferedInputStream(sizeInputStream);
FileOutputStream fileOut = new FileOutputStream(destination);
try {
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fileOut.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fileOut != null)
fileOut.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Downloads a file on the internet
* @param url
* @param destination
* @param listener
*/
public static void downloadFile(final URL url, final File destination,
final ProgressListener listener, String username, String password) {
try {
final URLConnection connection = getConnection(url, username, password);
int size = connection.getContentLength();
SizeInputStream sizeInputStream = new SizeInputStream(
connection.getInputStream(), size, listener);
BufferedInputStream in = new BufferedInputStream(sizeInputStream);
FileOutputStream fileOut = new FileOutputStream(destination);
try {
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fileOut.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fileOut != null)
fileOut.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Converts file format to url format
* @param file
* @return url to file
*/
public static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
}
@@ -1,225 +0,0 @@
package org.parabot.environment.input;
import java.awt.Component;
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
*
*/
public class Keyboard implements KeyListener {
private static HashMap<Character, Character> specialChars;
private Component component;
private long pressTime;
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<Character, Character>(spChars.length);
for (int x = 0; x < spChars.length; ++x)
specialChars.put(spChars[x], replace[x]);
}
private static long getRandom() {
Random rand = new Random();
return rand.nextInt(100) + 40;
}
public void sendKeys(String s) {
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(char c) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, c))
sendKeyEvent(ke);
}
public void clickKey(int keyCode) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, keyCode))
sendKeyEvent(ke);
}
public void pressKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyPress(component, keyCode);
sendKeyEvent(ke);
}
public void releaseKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyRelease(component, keyCode);
sendKeyEvent(ke);
}
private KeyEvent[] createKeyClick(Component target, char c) {
pressTime += 2 * getRandom();
Character newChar = specialChars.get(c);
int keyCode = Character.toUpperCase((newChar == null) ? c : newChar);
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[] { pressed, typed, released };
} else {
KeyEvent shiftDown = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, KeyEvent.SHIFT_MASK, KeyEvent.VK_SHIFT,
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[] { shiftDown, pressed, typed, released,
shiftUp };
}
}
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 new KeyEvent[] { pressed, released };
}
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 pressed;
}
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);
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 keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
@@ -1,163 +0,0 @@
package org.parabot.environment.input;
import org.parabot.core.Context;
import org.parabot.environment.api.utils.Time;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
*
* A virtual mouse, dispatches mouse events to a component
*
* @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();
}
}
/**
* 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) {
}
}
@@ -1,58 +0,0 @@
package org.parabot.environment.scripts;
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
{
AGILITY, COMBAT, COOKING, CRAFTING, CONSTRUCTION, DUNGEONEERING, FARMING, FIREMAKING, FISHING, FLETCHING, HERBLORE, HUNTER, MAGIC, MINIGAMES, MINING, 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());
}
/**
* 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("/org/parabot/core/ui/images/category/" + s + ".png"));
}
return images.get(s);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(name().charAt(0));
b.append(name().toLowerCase().substring(1));
return new String(b);
}
/**
* Cache
*/
private static HashMap<String, BufferedImage> images = new HashMap<>();
static {
images.put("script", Images.getResource("/org/parabot/core/ui/images/category/script.png"));
}
}
@@ -1,67 +0,0 @@
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;
/**
*
* Holds various script frameworks
*
* @author Everel
*
*/
public class Frameworks {
public static Looper getLooper(LoopTask loopTask) {
return new Looper(loopTask);
}
public static StrategyWorker getStrategyWorker(Collection<Strategy> 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;
}
}
class StrategyWorker extends AbstractFramework {
private Collection<Strategy> strategies;
public StrategyWorker(Collection<Strategy> strategies) {
this.strategies = strategies;
}
@Override
public boolean execute() {
for(Strategy s : strategies) {
if(s.activate()) {
s.execute();
return true;
}
}
return true;
}
}
@@ -1,163 +0,0 @@
package org.parabot.environment.scripts;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.ui.BotUI;
import org.parabot.environment.api.utils.Time;
import org.parabot.environment.scripts.framework.AbstractFramework;
import org.parabot.environment.scripts.framework.Frameworks;
import org.parabot.environment.scripts.framework.LoopTask;
import org.parabot.environment.scripts.framework.SleepCondition;
import org.parabot.environment.scripts.framework.Strategy;
import org.parabot.environment.scripts.randoms.Random;
import java.util.Collection;
/**
*
* Script template, scripts are 'add-ons' which executes various tasks in-game
*
* @author Everel
*
*/
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 STATE_RUNNING = 0;
public static final int STATE_PAUSE = 1;
public static final int STATE_STOPPED = 2;
private Collection<Strategy> strategies;
private AbstractFramework frameWork;
private int state;
private int frameWorkType;
public boolean onExecute() {
return true;
}
public void onFinish() {
}
public final void provide(final Collection<Strategy> strategies) {
this.strategies = strategies;
}
public final int getFrameWorkType() {
return frameWorkType;
}
public final void setFrameWork(int frameWorkType) {
if(frameWorkType < 0 || frameWorkType > 2) {
throw new RuntimeException("Invalid framework type");
}
this.frameWorkType = frameWorkType;
}
public final void setAbstractFrameWork(AbstractFramework f) {
this.frameWork = f;
}
public final void addRandom(Random random) {
Context.getInstance().getRandomHandler().addRandom(random);
}
@Override
public final void run() {
Context context = Context.getInstance();
Core.verbose("Initializing script...");
context.getServerProvider().initScript(this);
Core.verbose("Done.");
if(!onExecute()) {
Core.verbose("Script#onExecute returned false, unloading and stopping script...");
context.getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
Core.verbose("Done.");
return;
}
Core.verbose("Detecting script framework...");
context.setRunningScript(this);
BotUI.getInstance().toggleRun();
if(this instanceof LoopTask) {
Core.verbose("Script framework detected: LoopTask");
frameWorkType = TYPE_LOOP;
frameWork = Frameworks.getLooper((LoopTask) this);
} else if(strategies != null && !strategies.isEmpty()) {
Core.verbose("Script framework detected: Strategies");
frameWorkType = TYPE_STRATEGY;
frameWork = Frameworks.getStrategyWorker(strategies);
} else {
Core.verbose("Unknown script framework: Other");
frameWorkType = TYPE_OTHER;
}
Core.verbose("Running script...");
System.out.println("Script started.");
try {
while(this.state != STATE_STOPPED) {
if(context.getRandomHandler().checkAndRun()) {
continue;
}
if(this.state == STATE_PAUSE) {
sleep(500);
continue;
}
if(!frameWork.execute()) {
break;
}
}
} catch (Throwable t) {
t.printStackTrace();
}
Core.verbose("Script stopped/finished, unloading and stopping...");
onFinish();
System.out.println("Script stopped.");
context.getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
context.setRunningScript(null);
BotUI.getInstance().toggleRun();
Core.verbose("Done.");
}
/**
* Sleeps until the SleepCondition is valid.
*
* <B>DEPRECATED!</b> use {@link Time#sleep(SleepCondition, int)}
*
* @param conn
* the condition.
* @param timeout
* the time in miliseconds before it stops sleeping.
* @return whether it ran successfully without timing out.
*/
@Deprecated
public final boolean sleep(SleepCondition conn, int timeout) {
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
* @param ms
*/
public final void sleep(int ms) {
Time.sleep(ms);
}
}
@@ -1,30 +0,0 @@
package org.parabot.environment.scripts;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A script manifest, holds all script data
* @author Everel
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ScriptManifest {
String author();
String name();
Category category();
double version();
String description();
String[] servers();
boolean vip() default false;
boolean premium() default false;
}
@@ -1,97 +0,0 @@
package org.parabot.environment.scripts.executers;
import org.parabot.core.Configuration;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.forum.AccountManager;
import org.parabot.core.forum.AccountManagerAccess;
import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.WebUtil;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.scripts.loader.JavaScriptLoader;
import javax.swing.*;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLConnection;
/**
*
* Loads a script from the BDN
*
* @author Everel
*
*/
public class BDNScriptsExecuter extends ScriptExecuter {
private static AccountManager manager;
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
public final void setManager(AccountManager manager) {
BDNScriptsExecuter.manager = manager;
}
};
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");
if(contentType.equals("text/html")) {
// failed to fetch script
UILog.log("Error", "Failed to load BDN script, error: [Page returned: " + WebUtil.getContents(urlConnection) + "]", JOptionPane.ERROR_MESSAGE);
} else if(contentType.equals("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 String className = scriptClasses[0];
try {
final Class<?> scriptClass = loader.loadClass(className);
final Constructor<?> con = scriptClass.getConstructor();
final Script script = (Script) con.newInstance();
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 ////
} else {
UILog.log("Error", "Failed to load BDN script, error: [Unknown content type: " + contentType + "]", 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);
}
}
}
@@ -1,30 +0,0 @@
package org.parabot.environment.scripts.executers;
import java.lang.reflect.Constructor;
import org.parabot.environment.scripts.Script;
/**
*
* Loads a locally stored script
*
* @author Everel
*
*/
public class LocalScriptExecuter extends ScriptExecuter {
private Constructor<?> scriptConstructor;
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();
}
}
}
@@ -1,26 +0,0 @@
package org.parabot.environment.scripts.executers;
import org.parabot.environment.scripts.Script;
/**
*
* Executes a script
*
* @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) {
new Thread(tg, script).start();
}
}
@@ -1,18 +0,0 @@
package org.parabot.environment.scripts.framework;
/**
*
* Abstract framework for a script
*
* @author Everel
*
*/
public abstract class AbstractFramework {
/**
* Executes this frame
* @return <b>true</b> if it should keep executing this framework, otherwise <b>false</b>.
*/
public abstract boolean execute();
}
@@ -1,63 +0,0 @@
package org.parabot.environment.scripts.framework;
import java.util.Collection;
/**
*
* Holds various script frameworks
*
* @author Everel
*
*/
public class Frameworks {
public static Looper getLooper(LoopTask loopTask) {
return new Looper(loopTask);
}
public static StrategyWorker getStrategyWorker(Collection<Strategy> 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;
}
}
class StrategyWorker extends AbstractFramework {
private Collection<Strategy> strategies;
public StrategyWorker(Collection<Strategy> strategies) {
this.strategies = strategies;
}
@Override
public boolean execute() {
for(Strategy s : strategies) {
if(s.activate()) {
s.execute();
return true;
}
}
return true;
}
}
@@ -1,18 +0,0 @@
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
*
*/
public interface LoopTask {
/**
*
* @return sleepTime in ms
*/
public int loop();
}
@@ -1,18 +0,0 @@
package org.parabot.environment.scripts.framework;
/**
* Keeps sleeping till a condition is valid
*
* @author Everel
*
*/
public interface SleepCondition {
/**
* Determine if condition is valid
* @return <b>true</b> if valid, otherwise <b>false</b>.
*/
public boolean isValid();
}
@@ -1,22 +0,0 @@
package org.parabot.environment.scripts.framework;
/**
* Strategy framework for scripts
*
* @author Everel
*
*/
public interface Strategy {
/**
* Whether to activate this strategy
* @return <b>true</b> if this strategy should be executed, otherwise <b>false</b>.
*/
public boolean activate();
/**
* Executes this strategy
*/
public void execute();
}
@@ -1,43 +0,0 @@
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;
/**
*
* An environment to load a script
*
* @author Everel
*
*
*/
public class JavaScriptLoader extends ASMClassLoader {
private 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<String> classNames = new ArrayList<String>();
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()]);
}
}
@@ -1,33 +0,0 @@
package org.parabot.environment.scripts.randoms;
/**
*
* @author Everel
*
*/
public interface Random {
/**
* Determines whether this random should activate
* @return <b>true</b> if this random should activate
*/
public boolean activate();
/**
* 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();
}
@@ -1,107 +0,0 @@
package org.parabot.environment.scripts.randoms;
import org.parabot.core.Core;
import java.util.ArrayList;
/**
*
* @author Everel
*
*/
public class RandomHandler {
private ArrayList<Random> randoms;
/**
* The randoms that will actually run
*/
private ArrayList<Random> activeRandoms;
public RandomHandler() {
this.randoms = new ArrayList<>();
this.activeRandoms = new ArrayList<>();
}
/**
* Adds a random to the random list
* @param random The random that will be added to the arraylist
*/
public void addRandom(Random random) {
if(random == null) {
throw new NullPointerException("Null random");
}
for(Random r : randoms) {
if(r.getClass() == random.getClass()) {
Core.verbose("Ignored added random, duplicate.");
return;
}
}
randoms.add(random);
setActive(random);
}
/**
* Adds a random to the active randoms
* @param random
*/
public void setActive(Random random){
this.activeRandoms.add(random);
}
/**
* Adds a random to the active randoms
* @param random
*/
public void setActive(String random){
for (Random r : this.randoms){
if (r.getName().equalsIgnoreCase(random.toLowerCase())){
this.activeRandoms.add(r);
}
}
}
/**
* Sets the whole random arraylist to the arraylist given as argument
* @param randoms The new random arraylist
*/
public void setRandoms(ArrayList<Random> randoms){
this.randoms = randoms;
}
/**
* Clears all added randoms
*/
public void clearRandoms() {
this.randoms.clear();
}
/**
* Clears all active randoms
*/
public void clearActiveRandoms(){
this.activeRandoms.clear();
}
/**
* Checks if random occurs and runs it
* @return returns <b>true</b> if a random has been executed, otherwise <b>false</b>
*/
public boolean checkAndRun() {
for(Random r : this.activeRandoms) {
if(r.activate()) {
Core.verbose("Running random '" + r.getName() + "'.");
r.execute();
return true;
}
}
return false;
}
public ArrayList<Random> getRandoms(){
return this.randoms;
}
public ArrayList<Random> getActiveRandoms(){
return this.activeRandoms;
}
}