PDA

View Full Version : Neopets Programming with Java



Sean
06-04-2012, 10:40 AM
This is just a quick write up with some .java files to help you get started. Joe requested this from me a while ago and I've been slacking on putting it up.

First things first, a few files that may be beneficial to you:

Connection.java

This is the 'wrapper' or what you would use to connect to neopets and interact.
It's simple to use. Once you create a new instance its just neo.get("") and neo.post("", new String[][] { {}, {} });
If you need to set a referer, you can do that manually. Otherwise, the referer is set to the last page. There are a few modifications in this that I added such as proxy support, support for the potential botcheck, etc.


package manager;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JOptionPane;
import java.io.BufferedInputStream;

/**
*
[Only registered and activated users can see links]
*/
public class Connection implements Serializable {
static final long serialVersionUID = 1L;

String domain;

public String referer;
Map<String,String> cookies;

private boolean useProxy;
private String proxyIP;
private int proxyPort;
static String rpUseragent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
static String rpAcceptText = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
static String rpAcceptPng = "image/jpeg,image/*;q=0.8,*/*;q=0.5";
static String rpAcceptLanguage = "en-us,en;q=0.8";
static String rpAcceptEncoding = "gzip, deflate";
static String rpAcceptCharset = "ISO-8859-1,utf-8;q=0.7,*;q=0.3";
static String rpKeepAlive = "300";
static String rpConnection = "keep-alive";
static String rpContentType = "application/x-[Only registered and activated users can see links]";

public Connection(String domain, Map<String,String> cookies, String referer) {
this.domain = domain;
this.cookies = cookies;
this.referer = referer;
}

public Connection(String domain, Map<String,String> cookies) {
this(domain, cookies, null);
}

public Connection(String domain, String referer) {
this(domain, new HashMap<String,String>(), referer);
}

public Connection(String domain) {
this(domain, new HashMap<String,String>(), null);
}

public String get(String url) {
if(url.charAt(0) == '/')
url = domain + url;

try {
[Only registered and activated users can see links] conn;
String strHTML = "";
if (useProxy) {
Proxy proxy = new Proxy(Proxy.Type.[Only registered and activated users can see links] new InetSocketAddress(proxyIP, proxyPort));
conn = ([Only registered and activated users can see links])(new URL(url.replaceAll(" ", "%20")).openConnection(proxy));
} else {
conn = ([Only registered and activated users can see links])(new URL(url.replaceAll(" ", "%20")).openConnection());
}
setRequestProperties(conn);
conn.setRequestMethod("GET");
referer = url;
strHTML = read(conn);
if (url.contains("neopets")) {
if (strHTML.contains("hdrimg.php?srvfile")) {
conn = ([Only registered and activated users can see links])(new URL(Functions.getBetween(strHTML, "hdrimg.php?srvfile=", (char)34 + "")).openConnection());
setRequestProperties(conn);
conn.setRequestMethod("GET");
read(conn);
} else if (strHTML.contains("npaward.php")) {
conn = ([Only registered and activated users can see links])(new URL("[Only registered and activated users can see links]" + Functions.getBetween(strHTML, "[Only registered and activated users can see links]", (char)34 + "")).openConnection());
setRequestProperties(conn);
conn.setRequestMethod("GET");
read(conn);
}
}
return strHTML;
} catch(IOException e1) {
return null;
}
}

public String post(String url, String[][] data) {
if(url.charAt(0) == '/')
url = domain + url;

try {
[Only registered and activated users can see links] conn;
String strHTML = "";
if (useProxy) {
Proxy proxy = new Proxy(Proxy.Type.[Only registered and activated users can see links] new InetSocketAddress(proxyIP, proxyPort));
conn = ([Only registered and activated users can see links])(new URL(url.replaceAll(" ", "%20")).openConnection(proxy));
} else {
conn = ([Only registered and activated users can see links])(new URL(url.replaceAll(" ", "%20")).openConnection());
}
setRequestProperties(conn);
conn.setRequestMethod("POST");
conn.setDoOutput(true);

StringBuilder sb = new StringBuilder();

for(int i = 0; i < data[0].length; i++)
sb.append(URLEncoder.encode(data[0][i], "UTF-8")).append('=').append(URLEncoder.encode(data[1][i], "UTF-8")).append('&');

conn.setRequestProperty("Content-Type", rpContentType);
conn.setRequestProperty("Content-Length", Integer.toString(sb.length()-1));

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())));
out.write(sb.substring(0, sb.length()-1));
out.close();

referer = url;
strHTML = read(conn);
if (url.contains("neopets")) {
if (strHTML.contains("hdrimg.php?srvfile")) {
conn = ([Only registered and activated users can see links])(new URL(Functions.getBetween(strHTML, "hdrimg.php?srvfile=", (char)34 + "")).openConnection());
setRequestProperties(conn);
conn.setRequestMethod("GET");
read(conn);
} else if (strHTML.contains("npaward.php")) {
conn = ([Only registered and activated users can see links])(new URL("[Only registered and activated users can see links]" + Functions.getBetween(strHTML, "[Only registered and activated users can see links]", (char)34 + "")).openConnection());
setRequestProperties(conn);
conn.setRequestMethod("GET");
read(conn);
}
}
return strHTML;
} catch(IOException e1) {
return null;
}
}


public BufferedImage getImageFromUrl(String url) {
String imgURL = url;
URL url1 = null;
try {
url1 = new URL(imgURL);
[Only registered and activated users can see links] conn = ([Only registered and activated users can see links])(url1).openConnection();
if(cookies != null && cookies.size() != 0)
conn.setRequestProperty("Cookie", getCookieString());
conn.connect();
InputStream in = conn.getInputStream();
Image image = null;
image = ImageIO.read(in);
BufferedImage cpimg=bufferImage(image);
return cpimg;
} catch (Exception e) {
return new BufferedImage(1, 1, 1);
}
}
public BufferedImage bufferImage(Image image) {
return bufferImage(image,BufferedImage.TYPE_INT_RGB);
}
public BufferedImage bufferImage(Image image, int type) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, null, null);
return bufferedImage;
}

public boolean hasCookie(String key) {
return cookies.containsKey(key);
}

public String getCookieString() {
StringBuilder sb = new StringBuilder();

for(String s : cookies.keySet())
sb.append(s).append('=').append(cookies.get(s)).ap pend(';');

return sb.toString();
}

public boolean useProxy(boolean use, String ip, int port) {
useProxy = use;
proxyIP = ip;
proxyPort = port;
return use;
}

private void setRequestProperties([Only registered and activated users can see links] conn) {
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("User-Agent", rpUseragent);
conn.setRequestProperty("Accept", rpAcceptText);
conn.setRequestProperty("Accept-Language", rpAcceptLanguage);
conn.setRequestProperty("Accept-Encoding", rpAcceptEncoding);
conn.setRequestProperty("Accept-Charset", rpAcceptCharset);
conn.setRequestProperty("Keep-Alive", rpKeepAlive);
conn.setRequestProperty("Connection", rpConnection);

if(referer != null && referer.length() != 0)
conn.setRequestProperty("Referer", referer);

if(cookies != null && cookies.size() != 0)
conn.setRequestProperty("Cookie", getCookieString());
}

private void setRequestProperties2([Only registered and activated users can see links] conn) {
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("User-Agent", rpUseragent);
conn.setRequestProperty("Accept", rpAcceptText);
conn.setRequestProperty("Accept-Language", rpAcceptLanguage);
conn.setRequestProperty("Accept-Encoding", rpAcceptEncoding);
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Connection", rpConnection);
conn.setRequestProperty("Cache-Control", "max-age=0");


if(cookies != null && cookies.size() != 0)
conn.setRequestProperty("Cookie", getCookieString());
}

private String read([Only registered and activated users can see links] conn) throws IOException {
BufferedReader in = null;

if(conn.getContentEncoding() == null)
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
else
if(conn.getContentEncoding().equalsIgnoreCase("gzip"))
in = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getInputStream())));
else if(conn.getContentEncoding().equalsIgnoreCase("deflate"))
in = new BufferedReader(new InputStreamReader(new InflaterInputStream(conn.getInputStream(), new Inflater(true))));


StringBuilder sb = new StringBuilder();
String s;

while((s = in.readLine()) != null)
sb.append(s).append('\n');

putCookies(conn.getHeaderFields().get("Set-Cookie"));
return conn.getHeaderFields() + sb.toString();
}

private void putCookies(List<String> cookieList) {
if(cookieList == null)
return;

int index;

for(String cookie : cookieList)
cookies.put(cookie.substring(0, index = cookie.indexOf('=')), cookie.substring(index+1, cookie.indexOf(';', index)));
}

public void clearCookies() {
cookies.clear();
}
}


Functions.java

I've included some basic functions such as getStringBetween, load file, etc.

package manager;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import userInterface.BotGUI;


public class Functions {

static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rnd = new Random();

public static String randomString( int len )
{
StringBuilder sb = new StringBuilder( len );
for( int i = 0; i < len; i++ )
sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
return sb.toString();
}

public static void copyStringToClipboard(String str) {
StringSelection stringSelection = new StringSelection(str);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}

public static final int NOT_FOUND_INDEX = -1;
public static String getStringBetween(String theString, String start, String end) {
if(theString == null || start == null || end == null) {
return null;
}
int startIndex = theString.indexOf(start);
if(startIndex != NOT_FOUND_INDEX) {
int endIndex = theString.indexOf(end, startIndex + start.length());
if(endIndex != NOT_FOUND_INDEX) {
return theString.substring(startIndex + start.length(), endIndex);
}
}
return null;
}

public static void wait (int n){
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < n);
}

public static String[] loadFile(final String f) {
String thisLine;
final List<String> s = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
while ((thisLine = br.readLine()) != null)
s.add(thisLine.trim());
} catch (IOException ioe) {
System.err.println("Error reading file " + f);
throw new RuntimeException(ioe);
} finally {
if(br!=null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return s.toArray(new String[s.size()]);
}


public static PrintStream getOutputPrintStream(){
PrintStream outStream = null;
while (outStream == null) {
File f = new File("Settings/Accounts.nbf");
try {
outStream = new PrintStream(f);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Unable to Save Accounts - Please try again.");
}
}
return outStream;
}

}







Apart from this, what joe really wanted was the gui creator for eclipse that I use.

Currently, I am using google's WindowBuilder Pro. It's a simple eclipse add-on that allows for quick gui creation. There are some bugs that i've found with it but nothing major and it should work for whatever you want to make.

Link:
[Only registered and activated users can see links]


That's all I'm going to post for now but if you have any other questions then feel free to ask.

Zachafer
06-09-2012, 04:37 PM
I highly recommend this post to anyone wanting to learn Java programming or programming in general.

Java is a cross-platform programming language meaning your programs can be ran on any operating system.

Becka

Becka
06-09-2012, 08:49 PM
I highly recommend this post to anyone wanting to learn Java programming or programming in general.

Java is a cross-platform programming language meaning your programs can be ran on any operating system.

Becka

Ahh that's good so if I go back to my windows XP computer someday I can use them on there, awesome :*

deathwish42
06-09-2012, 08:57 PM
wow thats amazing nice job im currently trying to learn java on codecademy im stuck on it though so ya nice topic i will come back to this once i learn how to do some major coding

davebold370
07-12-2012, 10:52 PM
Coolness. It's a little more advance than what I know of java right now. What are the portals you use to access different things throughout neopets and how would i find those portals myself so i don't have to ask over and over again. lol Thank you so much. I love learning new things about programing and more involved i become with internet programing the better.

BEDDOEDv
10-11-2012, 06:30 AM
im trying to learn about java, i find its slow though a times

npm
11-14-2012, 07:24 PM
I'm studying java at school and this will really help me. I hope someday I can do a simple program for neopets by myself without asking anything and this is a really good begining for me (you know trying to learn about all the functions used on this and that :rolleyes:). So thank you :)

Jesusinn
11-14-2012, 07:37 PM
I just learn java in the school too.
but I noob compared with him u.u
thanks so much for the tutorial :3

eliphasleviathan
10-19-2013, 05:56 AM
WB is a bit buggy, yes. In the sense that you drag and drop a window/widget/whatever (I forget the technical term WBPro uses) and it auto-places the code for you in your existing program in a place that isn't exactly organized (or as organized as you'd want it to be)... which means you may have to manually put it somewhere else, every single time you drop a window/widget onto the screen.

There is always straight coding via AWT and SWING, which I prefer; but am recently taking to JavaFX as a means to create a more attractive GUI for potential users... and JavaFX is, to me, a bit ghetto in the sense that its still new- and yes- there are several known bugs.

Couple on top of all this, any time plug-ins are being installed with eclipse; you may have some kind of unexpected or unwarranted behaviour (such as the well-known "R" or Resource bug commonplace with Google's ADT Plug-In for Android Developers)

I feel that Java is kinda' wanting when it comes to GUI development ( lacking the sheer simplicity of VB ); though every language/platform seems to have its own advantages over others, and simply familiarizing yourself with every language/platform's nuances will indeed make the process a lot more comfortable, as you get used to experiencing these same nuances over time and can work around or fix them via personal experience, effortlessly. But that all comes with familiarity and practice.

eggloo
07-22-2014, 10:39 PM
is java the best program for np bots?

hamstergleufje
08-27-2014, 03:23 AM
LOL wow looks so hard

ozfe
11-10-2014, 07:04 AM
This is amazing! Thanks so much!