Reformat of the source

This commit is contained in:
Jaime Martinez Rincon 2017-01-14 12:24:09 +01:00
parent 355bbcf180
commit a3a760ef08
18 changed files with 1142 additions and 1216 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -12,6 +12,11 @@ import java.util.Map;
public class AdapterFix implements ConfigurationAdapter { public class AdapterFix implements ConfigurationAdapter {
private static final Map<String, ServerInfo> fakeServers = new HashMap<>(); private static final Map<String, ServerInfo> fakeServers = new HashMap<>();
private static AdapterFix instance = null; private static AdapterFix instance = null;
private final ConfigurationAdapter adapter;
public AdapterFix(ConfigurationAdapter adapter) {
this.adapter = adapter;
}
public static void inject(ProxyServer server) { public static void inject(ProxyServer server) {
if (instance == null) { if (instance == null) {
@ -32,12 +37,6 @@ public class AdapterFix implements ConfigurationAdapter {
return fakeServers; return fakeServers;
} }
private final ConfigurationAdapter adapter;
public AdapterFix(ConfigurationAdapter adapter) {
this.adapter = adapter;
}
@Override @Override
public void load() { public void load() {
adapter.load(); adapter.load();

View File

@ -91,8 +91,10 @@ public enum PasteHelper {
} }
}; };
public static final String DEVELOPER_KEY = "e3ff18d8fb001a3ece08ae0d7d4a87bd";
private String link; private String link;
private ScheduledTask task = null; private ScheduledTask task = null;
public void send(Plugin plugin, CommandSender sender, String message) { public void send(Plugin plugin, CommandSender sender, String message) {
try { try {
sender.sendMessage(new ComponentBuilder(message.replace("{link}", link == null ? link = paste(plugin) : link) sender.sendMessage(new ComponentBuilder(message.replace("{link}", link == null ? link = paste(plugin) : link)
@ -108,12 +110,11 @@ public enum PasteHelper {
sender.sendMessage(new ComponentBuilder("An unexpected error occurred while pasting the file").color(ChatColor.RED).create()); sender.sendMessage(new ComponentBuilder("An unexpected error occurred while pasting the file").color(ChatColor.RED).create());
} }
e.printStackTrace(); e.printStackTrace();
} catch(Exception e) { } catch (Exception e) {
sender.sendMessage(new ComponentBuilder("An internal error occurred while attempting to perform this command").color(ChatColor.RED).create()); sender.sendMessage(new ComponentBuilder("An internal error occurred while attempting to perform this command").color(ChatColor.RED).create());
e.printStackTrace(); e.printStackTrace();
} }
} }
public abstract String paste(Plugin plugin) throws Exception; public abstract String paste(Plugin plugin) throws Exception;
public static final String DEVELOPER_KEY = "e3ff18d8fb001a3ece08ae0d7d4a87bd";
} }

View File

@ -13,10 +13,10 @@ import static me.jaimemartz.lobbybalancer.LobbyBalancer.printStartupInfo;
public class PingManager { public class PingManager {
private final LobbyBalancer plugin; private final LobbyBalancer plugin;
private final Map<ServerInfo, ServerStatus> storage = new HashMap<>();
private boolean stopped = true; private boolean stopped = true;
private PingTacticType tactic; private PingTacticType tactic;
private ScheduledTask task; private ScheduledTask task;
private final Map<ServerInfo, ServerStatus> storage = new HashMap<>();
public PingManager(LobbyBalancer plugin) { public PingManager(LobbyBalancer plugin) {
this.plugin = plugin; this.plugin = plugin;

View File

@ -3,57 +3,52 @@ package org.jpaste;
import org.jpaste.exceptions.PasteException; import org.jpaste.exceptions.PasteException;
/** /**
*
* An abstract representation of a paste. * An abstract representation of a paste.
* * <p>
* <p> * <p>
* An abstract paste holds the paste contents and the {@link #paste()} * An abstract paste holds the paste contents and the {@link #paste()}
* operation. * operation.
* </p> * </p>
* *
* @param <P> PasteResult implementation
* @author Brian B * @author Brian B
*
* @param <P>
* PasteResult implementation
*/ */
public abstract class AbstractPaste<P extends AbstractPasteLink> { public abstract class AbstractPaste<P extends AbstractPasteLink> {
private String contents; private String contents;
/** /**
* Creates a new abstract <code>AbstractPaste</code> instance. * Creates a new abstract <code>AbstractPaste</code> instance.
* *
* @param contents * @param contents the contents of the paste
* the contents of the paste */
*/ public AbstractPaste(String contents) {
public AbstractPaste(String contents) { this.contents = contents;
this.contents = contents; }
}
/** /**
* Gets paste contents * Gets paste contents
* *
* @return paste contents * @return paste contents
*/ */
public String getContents() { public String getContents() {
return contents; return contents;
} }
/** /**
* Sets the paste contents * Sets the paste contents
* *
* @param contents * @param contents contents of the paste
* contents of the paste */
*/ public void setContents(String contents) {
public void setContents(String contents) { this.contents = contents;
this.contents = contents; }
}
/** /**
* Attempts to paste this paste and returns the results * Attempts to paste this paste and returns the results
* *
* @return paste result * @return paste result
* @throws PasteException if it failed to paste the paste * @throws PasteException if it failed to paste the paste
*/ */
public abstract P paste() throws PasteException; public abstract P paste() throws PasteException;
} }

View File

@ -3,23 +3,21 @@ package org.jpaste;
import java.net.URL; import java.net.URL;
/** /**
*
* An representation of an abstract PasteLink * An representation of an abstract PasteLink
* * <p>
* <p> * <p>
* An AbstractPasteLink holds the link/URL to a paste. * An AbstractPasteLink holds the link/URL to a paste.
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public abstract class AbstractPasteLink { public abstract class AbstractPasteLink {
/** /**
* Gets the URL to this paste * Gets the URL to this paste
* *
* @return URL to paste * @return URL to paste
*/ */
public abstract URL getLink(); public abstract URL getLink();
} }

View File

@ -1,13 +1,13 @@
package org.jpaste.exceptions; package org.jpaste.exceptions;
public class PasteException extends Exception { public class PasteException extends Exception {
private static final long serialVersionUID = -4230960075582953775L; private static final long serialVersionUID = -4230960075582953775L;
public PasteException() { public PasteException() {
} }
public PasteException(String message) { public PasteException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,60 +1,56 @@
package org.jpaste.pastebin; package org.jpaste.pastebin;
/** /**
*
* Represents a paste's expire date * Represents a paste's expire date
* * <p>
* <p> * <p>
* A list of all expire dates/times can be found at the <a * A list of all expire dates/times can be found at the <a
* href="http://pastebin.com/api">pastebin API manual</a>. * href="http://pastebin.com/api">pastebin API manual</a>.
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public enum PasteExpireDate { public enum PasteExpireDate {
NEVER("N", -1), TEN_MINUTES("10M", 10 * 60), ONE_HOUR("1H", 60 * 60), ONE_DAY( NEVER("N", -1), TEN_MINUTES("10M", 10 * 60), ONE_HOUR("1H", 60 * 60), ONE_DAY(
"1D", 60 * 60 * 24), ONE_WEEK("1W", 60 * 60 * 24 * 7), TWO_WEEKS( "1D", 60 * 60 * 24), ONE_WEEK("1W", 60 * 60 * 24 * 7), TWO_WEEKS(
"2W", 60 * 60 * 24 * 14), ONE_MONTH("1M", -1); "2W", 60 * 60 * 24 * 14), ONE_MONTH("1M", -1);
private String val; private String val;
private int timeSeconds; private int timeSeconds;
/** /**
* Creates a new <code>PasteExpireDate</code> instance. * Creates a new <code>PasteExpireDate</code> instance.
* *
* @param val * @param val a valid expire date value
* a valid expire date value */
*/ PasteExpireDate(String val, int timeSeconds) {
PasteExpireDate(String val, int timeSeconds) { this.val = val;
this.val = val; this.timeSeconds = timeSeconds;
this.timeSeconds = timeSeconds; }
}
/** /**
* Get's the valid value for the 'api_paste_expire_date' parameter * Gets PasteExpireDate based on: paste expire date minus paste date (in
* * seconds)
* @return the valid value for the 'api_paste_expire_date' parameter *
*/ * @param timeSeconds seconds between expire date and paste date
public String getValue() { * @return PasteExpireDate
return val; */
} public static PasteExpireDate getExpireDate(int timeSeconds) {
for (PasteExpireDate date : PasteExpireDate.values()) {
if (date.timeSeconds == timeSeconds) {
return date;
}
}
return ONE_MONTH;
}
/** /**
* Gets PasteExpireDate based on: paste expire date minus paste date (in * Get's the valid value for the 'api_paste_expire_date' parameter
* seconds) *
* * @return the valid value for the 'api_paste_expire_date' parameter
* @param timeSeconds */
* seconds between expire date and paste date public String getValue() {
* @return PasteExpireDate return val;
*/ }
public static PasteExpireDate getExpireDate(int timeSeconds) {
for (PasteExpireDate date : PasteExpireDate.values()) {
if (date.timeSeconds == timeSeconds) {
return date;
}
}
return ONE_MONTH;
}
} }

View File

@ -19,189 +19,172 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
/** /**
*
* A global representation of the pastebin site * A global representation of the pastebin site
* * <p>
* <p> * <p>
* Holds various constants and method shortcuts * Holds various constants and method shortcuts
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public class Pastebin { public class Pastebin {
/** /**
* Used to interact with the pastebin API * Used to interact with the pastebin API
*/ */
public static final String API_POST_LINK = "http://pastebin.com/api/api_post.php"; public static final String API_POST_LINK = "http://pastebin.com/api/api_post.php";
/** /**
* Used for fetching an user session id * Used for fetching an user session id
*/ */
public static final String API_LOGIN_LINK = "http://pastebin.com/api/api_login.php"; public static final String API_LOGIN_LINK = "http://pastebin.com/api/api_login.php";
/** /**
* Fetches a paste text from pastebin * Fetches a paste text from pastebin
* *
* @param pasteKey * @param pasteKey the unique paste key
* the unique paste key * @return contents of the paste
* @return contents of the paste */
*/ public static String getContents(String pasteKey) {
public static String getContents(String pasteKey) { return PastebinLink.getContents(pasteKey);
return PastebinLink.getContents(pasteKey); }
}
/** /**
* Generates a paste on pastebin and returns the URL to it * Generates a paste on pastebin and returns the URL to it
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents contents of the paste
* @param contents * @return URL to paste
* contents of the paste * @throws PasteException if it failed to push the paste
* @return URL to paste */
* @throws PasteException public static URL pastePaste(String developerKey, String contents)
* if it failed to push the paste throws PasteException {
*/ return pastePaste(developerKey, contents, null);
public static URL pastePaste(String developerKey, String contents) }
throws PasteException {
return pastePaste(developerKey, contents, null);
}
/** /**
* Generates a paste on pastebin and returns the URL to it * Generates a paste on pastebin and returns the URL to it
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents contents of the paste
* @param contents * @param title title of the paste
* contents of the paste * @return URL to paste
* @param title * @throws PasteException if it failed to push the paste
* title of the paste */
* @return URL to paste public static URL pastePaste(String developerKey, String contents,
* @throws PasteException String title) throws PasteException {
* if it failed to push the paste return newPaste(developerKey, contents, title).paste().getLink();
*/ }
public static URL pastePaste(String developerKey, String contents,
String title) throws PasteException {
return newPaste(developerKey, contents, title).paste().getLink();
}
/** /**
* Generates a new paste and returns it * Generates a new paste and returns it
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents contents of the paste
* @param contents * @param title title of the paste
* contents of the paste * @return a new paste
* @param title */
* title of the paste public static PastebinPaste newPaste(String developerKey, String contents,
* @return a new paste String title) {
*/ PastebinPaste paste = new PastebinPaste(developerKey, contents);
public static PastebinPaste newPaste(String developerKey, String contents, paste.setPasteTitle(title);
String title) { return paste;
PastebinPaste paste = new PastebinPaste(developerKey, contents); }
paste.setPasteTitle(title);
return paste;
}
/** /**
* Generates a new paste and returns it * Generates a new paste and returns it
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents contents of the paste
* @param contents * @return a new paste
* contents of the paste */
* @return a new paste public static PastebinPaste newPaste(String developerKey, String contents) {
*/ return newPaste(developerKey, contents, null);
public static PastebinPaste newPaste(String developerKey, String contents) { }
return newPaste(developerKey, contents, null);
}
/** /**
* Gets the current trending pastebin pastes * Gets the current trending pastebin pastes
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @return an array of {@link PastebinLink}
* @return an array of {@link PastebinLink} * @throws ParseException if it failed to parse the trending pastes
* @throws ParseException */
* if it failed to parse the trending pastes public static PastebinLink[] getTrending(String developerKey)
*/ throws ParseException {
public static PastebinLink[] getTrending(String developerKey) if (developerKey == null || developerKey.isEmpty()) {
throws ParseException { throw new IllegalArgumentException(
if (developerKey == null || developerKey.isEmpty()) { "Developer key can't be null or empty.");
throw new IllegalArgumentException( }
"Developer key can't be null or empty."); Post post = new Post();
} post.put("api_dev_key", developerKey);
Post post = new Post(); post.put("api_option", "trends");
post.put("api_dev_key", developerKey);
post.put("api_option", "trends");
String response = Web.getContents(API_POST_LINK, post); String response = Web.getContents(API_POST_LINK, post);
if (response.startsWith("<paste>")) { if (response.startsWith("<paste>")) {
// success // success
try { try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance(); .newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
response = "<dummy>" + response + "</dummy>"; // requires root response = "<dummy>" + response + "</dummy>"; // requires root
// element // element
Document doc = dBuilder.parse(new InputSource( Document doc = dBuilder.parse(new InputSource(
new ByteArrayInputStream(response.getBytes("utf-8")))); new ByteArrayInputStream(response.getBytes("utf-8"))));
doc.getDocumentElement().normalize(); doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("paste"); NodeList nodes = doc.getElementsByTagName("paste");
ArrayList<PastebinLink> pastes = new ArrayList<PastebinLink>( ArrayList<PastebinLink> pastes = new ArrayList<PastebinLink>(
nodes.getLength()); nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) { for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i); Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node; Element element = (Element) node;
String pasteFormat = XMLUtils.getText(element, String pasteFormat = XMLUtils.getText(element,
"paste_format_short"); "paste_format_short");
String title = XMLUtils.getText(element, "paste_title"); String title = XMLUtils.getText(element, "paste_title");
int visibility = Integer.parseInt(XMLUtils.getText( int visibility = Integer.parseInt(XMLUtils.getText(
element, "paste_private")); element, "paste_private"));
int hits = Integer.parseInt(XMLUtils.getText(element, int hits = Integer.parseInt(XMLUtils.getText(element,
"paste_hits")); "paste_hits"));
long expireDate = Long.parseLong(XMLUtils.getText( long expireDate = Long.parseLong(XMLUtils.getText(
element, "paste_expire_date")); element, "paste_expire_date"));
long pasteDate = Long.parseLong(XMLUtils.getText( long pasteDate = Long.parseLong(XMLUtils.getText(
element, "paste_date")); element, "paste_date"));
URL pasteURL = new URL(XMLUtils.getText(element, URL pasteURL = new URL(XMLUtils.getText(element,
"paste_url")); "paste_url"));
PastebinPaste paste = new PastebinPaste(); PastebinPaste paste = new PastebinPaste();
paste.setPasteFormat(pasteFormat); paste.setPasteFormat(pasteFormat);
paste.setPasteTitle(title); paste.setPasteTitle(title);
paste.setVisibility(visibility); paste.setVisibility(visibility);
paste.setPasteExpireDate(expireDate == 0L ? PasteExpireDate.NEVER paste.setPasteExpireDate(expireDate == 0L ? PasteExpireDate.NEVER
: PasteExpireDate : PasteExpireDate
.getExpireDate((int) (expireDate - pasteDate))); .getExpireDate((int) (expireDate - pasteDate)));
PastebinLink pastebinLink = new PastebinLink(paste, PastebinLink pastebinLink = new PastebinLink(paste,
pasteURL, new Date(pasteDate * 1000)); pasteURL, new Date(pasteDate * 1000));
pastebinLink.setHits(hits); pastebinLink.setHits(hits);
pastes.add(pastebinLink); pastes.add(pastebinLink);
} }
} }
return pastes.toArray(new PastebinLink[pastes.size()]); return pastes.toArray(new PastebinLink[pastes.size()]);
} catch (Exception e) { } catch (Exception e) {
throw new ParseException("Failed to parse pastes: " throw new ParseException("Failed to parse pastes: "
+ e.getMessage()); + e.getMessage());
} }
} }
throw new ParseException("Failed to parse pastes: " + response); throw new ParseException("Failed to parse pastes: " + response);
} }
} }

View File

@ -11,174 +11,165 @@ import java.net.URL;
import java.util.Date; import java.util.Date;
/** /**
*
* A representation of an online pastebin paste. * A representation of an online pastebin paste.
* * <p>
* * <p>
* <p> * <p>
* This class represents an existing pastebin paste URL * This class represents an existing pastebin paste URL
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public class PastebinLink extends AbstractPasteLink { public class PastebinLink extends AbstractPasteLink {
private PastebinPaste paste; private PastebinPaste paste;
private URL link; private URL link;
private int hits; private int hits;
private String key; private String key;
private Date pasteDate; private Date pasteDate;
/** /**
* Creates a new <code>PastebinLink</code> object, representing an existing * Creates a new <code>PastebinLink</code> object, representing an existing
* paste * paste
* *
* @param paste * @param paste paste details
* paste details * @param url link to paste
* @param url */
* link to paste public PastebinLink(PastebinPaste paste, URL url) {
*/ this(paste, url, new Date((System.currentTimeMillis() / 1000) * 1000));
public PastebinLink(PastebinPaste paste, URL url) { }
this(paste, url, new Date((System.currentTimeMillis() / 1000) * 1000));
}
/** /**
* Creates a new <code>PastebinLink</code> object, representing an existing * Creates a new <code>PastebinLink</code> object, representing an existing
* paste * paste
* *
* @param paste * @param paste paste details
* paste details * @param url link to paste
* @param url * @param pasteDate date the paste has been pasted
* link to paste */
* @param pasteDate public PastebinLink(PastebinPaste paste, URL url, Date pasteDate) {
* date the paste has been pasted this.paste = paste;
*/ this.link = url;
public PastebinLink(PastebinPaste paste, URL url, Date pasteDate) { this.pasteDate = pasteDate;
this.paste = paste; try {
this.link = url; this.key = url.toURI().getPath().substring(1);
this.pasteDate = pasteDate; } catch (URISyntaxException e) {
try { e.printStackTrace();
this.key = url.toURI().getPath().substring(1); }
} catch (URISyntaxException e) { }
e.printStackTrace();
}
}
/** /**
* {@inheritDoc} * Fetches a paste text from pastebin
*/ *
@Override * @param pasteKey the unique paste key
public URL getLink() { * @return contents of the paste
return link; */
} public static String getContents(String pasteKey) {
return Web.getContents("http://pastebin.com/raw.php?i=" + pasteKey);
}
/** /**
* Gets pastebin paste details * {@inheritDoc}
* */
* @return paste details @Override
*/ public URL getLink() {
public PastebinPaste getPaste() { return link;
return paste; }
}
/**
* Gets pastebin unique paste key
* @return unique paste key
*/
public String getKey() {
return this.key;
}
/**
* Fetches the pastebin link content
* <p>
* After parsing use the following methods: {@link #getPaste()} {@link PastebinPaste#getContents()}
*/
public void fetchContent() {
if(getPaste().getContents() != null) {
throw new IllegalStateException("Contents already fetched.");
}
getPaste().setContents(getContents(getKey()));
}
/** /**
* Sets the paste page hits * Gets pastebin paste details
* *
* @param hits * @return paste details
* amount of times paste has been visited */
*/ public PastebinPaste getPaste() {
public void setHits(int hits) { return paste;
if (hits < 0) { }
throw new IllegalArgumentException("Hits must be positive: " + hits);
}
this.hits = hits;
}
/** /**
* Gets the paste page hits * Gets pastebin unique paste key
* *
* @return paste page hits * @return unique paste key
*/ */
public int getHits() { public String getKey() {
return this.hits; return this.key;
} }
/** /**
* Gets the paste date * Fetches the pastebin link content
* * <p>
* @return paste date * After parsing use the following methods: {@link #getPaste()} {@link PastebinPaste#getContents()}
*/ */
public Date getPasteDate() { public void fetchContent() {
return this.pasteDate; if (getPaste().getContents() != null) {
} throw new IllegalStateException("Contents already fetched.");
}
getPaste().setContents(getContents(getKey()));
}
/** /**
* Deletes this paste * Gets the paste page hits
* *
* @param account * @return paste page hits
* the account which was used to create this paste */
* @param developerKey public int getHits() {
* a developer key which can be fetched from the pastebin API return this.hits;
* page }
* @throws PasteException if it failed to delete the paste
*/
public void delete(String developerKey, PastebinAccount account) throws PasteException {
if(developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException("Developer key can't be null or empty.");
}
if(account.getUserSessionId() == null || account.getUserSessionId().isEmpty()) {
throw new IllegalArgumentException("Account user session id is missing.");
}
Post post = new Post();
post.put("api_dev_key", developerKey);
post.put("api_user_key", account.getUserSessionId());
post.put("api_paste_key", getKey());
post.put("api_option", "delete");
String response = Web.getContents(Pastebin.API_POST_LINK, post);
if(response.equals("Paste Removed")) {
return;
}
throw new PasteException("Failed to delete paste: " + response);
}
/** /**
* Deletes this paste * Sets the paste page hits
* @throws PasteException if it failed to delete the paste *
*/ * @param hits amount of times paste has been visited
public void delete() throws PasteException { */
delete(getPaste().getDeveloperKey(), getPaste().getAccount()); public void setHits(int hits) {
} if (hits < 0) {
throw new IllegalArgumentException("Hits must be positive: " + hits);
}
this.hits = hits;
}
/** /**
* Fetches a paste text from pastebin * Gets the paste date
* *
* @param pasteKey * @return paste date
* the unique paste key */
* @return contents of the paste public Date getPasteDate() {
*/ return this.pasteDate;
public static String getContents(String pasteKey) { }
return Web.getContents("http://pastebin.com/raw.php?i=" + pasteKey);
} /**
* Deletes this paste
*
* @param account the account which was used to create this paste
* @param developerKey a developer key which can be fetched from the pastebin API
* page
* @throws PasteException if it failed to delete the paste
*/
public void delete(String developerKey, PastebinAccount account) throws PasteException {
if (developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException("Developer key can't be null or empty.");
}
if (account.getUserSessionId() == null || account.getUserSessionId().isEmpty()) {
throw new IllegalArgumentException("Account user session id is missing.");
}
Post post = new Post();
post.put("api_dev_key", developerKey);
post.put("api_user_key", account.getUserSessionId());
post.put("api_paste_key", getKey());
post.put("api_option", "delete");
String response = Web.getContents(Pastebin.API_POST_LINK, post);
if (response.equals("Paste Removed")) {
return;
}
throw new PasteException("Failed to delete paste: " + response);
}
/**
* Deletes this paste
*
* @throws PasteException if it failed to delete the paste
*/
public void delete() throws PasteException {
delete(getPaste().getDeveloperKey(), getPaste().getAccount());
}
} }

View File

@ -10,303 +10,289 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
/** /**
*
* A representation of a new or existing paste. * A representation of a new or existing paste.
* * <p>
* <p> * <p>
* This class holds the contents of the paste itself. You can get and modify * This class holds the contents of the paste itself. You can get and modify
* settings and then 'push' this paste onto <a * settings and then 'push' this paste onto <a
* href="http://pastebin.com/">pastebin.</a> * href="http://pastebin.com/">pastebin.</a>
* </p> * </p>
* * <p>
* <p> * <p>
* This class has been programmed with the help of the <a * This class has been programmed with the help of the <a
* href="http://pastebin.com/api/">pastebin API manual.</a> * href="http://pastebin.com/api/">pastebin API manual.</a>
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public class PastebinPaste extends AbstractPaste<PastebinLink> { public class PastebinPaste extends AbstractPaste<PastebinLink> {
/** /**
* Makes a paste public. * Makes a paste public.
*/ */
public static final int VISIBILITY_PUBLIC = 0; public static final int VISIBILITY_PUBLIC = 0;
/** /**
* Makes a paste unlisted. * Makes a paste unlisted.
*/ */
public static final int VISIBILITY_UNLISTED = 1; public static final int VISIBILITY_UNLISTED = 1;
/** /**
* Makes a paste private. * Makes a paste private.
* <p> * <p>
* Requires an {@link PastebinAccount * Requires an {@link PastebinAccount
* org.jpaste.pastebin.account.PastebinAccount PastebinAccount} * org.jpaste.pastebin.account.PastebinAccount PastebinAccount}
* </p> * </p>
*/ */
public static final int VISIBILITY_PRIVATE = 2; public static final int VISIBILITY_PRIVATE = 2;
private String developerKey; private String developerKey;
private PastebinAccount account; private PastebinAccount account;
private String pasteTitle; private String pasteTitle;
private String pasteFormat; private String pasteFormat;
private PasteExpireDate expireDate; private PasteExpireDate expireDate;
private int visibility; private int visibility;
/** /**
* Creates a new empty <code>PastebinPaste</code> instance. * Creates a new empty <code>PastebinPaste</code> instance.
*/ */
public PastebinPaste() { public PastebinPaste() {
this(null, null, null); this(null, null, null);
} }
/** /**
* Creates a new <code>PastebinPaste</code> instance. * Creates a new <code>PastebinPaste</code> instance.
* *
* @param contents * @param contents the paste contents
* the paste contents */
*/ public PastebinPaste(String contents) {
public PastebinPaste(String contents) { this(null, contents, null);
this(null, contents, null); }
}
/** /**
* Creates a new <code>PastebinPaste</code> instance. * Creates a new <code>PastebinPaste</code> instance.
* *
* @param account * @param account a pastebin account
* a pastebin account */
*/ public PastebinPaste(PastebinAccount account) {
public PastebinPaste(PastebinAccount account) { this(account.getDeveloperKey(), null, account);
this(account.getDeveloperKey(), null, account); }
}
/** /**
* Creates a new <code>PastebinPaste</code> instance. * Creates a new <code>PastebinPaste</code> instance.
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents the contents of the paste
* @param contents */
* the contents of the paste public PastebinPaste(String developerKey, String contents) {
*/ this(developerKey, contents, null);
public PastebinPaste(String developerKey, String contents) { }
this(developerKey, contents, null);
}
/** /**
* Creates a new <code>PastebinPaste</code> instance. * Creates a new <code>PastebinPaste</code> instance.
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param contents the contents of the paste
* @param contents * @param account a pastebin account
* the contents of the paste */
* @param account public PastebinPaste(String developerKey, String contents,
* a pastebin account PastebinAccount account) {
*/ super(contents);
public PastebinPaste(String developerKey, String contents, this.developerKey = developerKey;
PastebinAccount account) { this.account = account;
super(contents); }
this.developerKey = developerKey;
this.account = account;
}
/** /**
* Sets the pastebin account If you set an account the pastes will be listed * Gets the pastebin account
* on your account. *
* * @return pastebin account
* @param account */
* a pastebin account public PastebinAccount getAccount() {
*/ return this.account;
public void setAccount(PastebinAccount account) { }
this.account = account;
}
/** /**
* Gets the pastebin account * Sets the pastebin account If you set an account the pastes will be listed
* * on your account.
* @return pastebin account *
*/ * @param account a pastebin account
public PastebinAccount getAccount() { */
return this.account; public void setAccount(PastebinAccount account) {
} this.account = account;
}
/** /**
* Sets the developer key The developer key is required to paste contents on * Gets the developer key
* pastebin *
* * @return developer key
* @param developerKey */
* a developer key which can be fetched from the pastebin API public String getDeveloperKey() {
* page return this.developerKey;
*/ }
public void setDeveloperKey(String developerKey) {
if (developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException(
"Developer key can not be null or empty.");
}
this.developerKey = developerKey;
}
/** /**
* Sets the paste expire date * Sets the developer key The developer key is required to paste contents on
* * pastebin
* @param date *
* date when the paste will be removed * @param developerKey a developer key which can be fetched from the pastebin API
*/ * page
public void setPasteExpireDate(PasteExpireDate date) { */
this.expireDate = date; public void setDeveloperKey(String developerKey) {
} if (developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException(
"Developer key can not be null or empty.");
}
this.developerKey = developerKey;
}
/** /**
* Gets the developer key * Gets paste title
* *
* @return developer key * @return paste title
*/ */
public String getDeveloperKey() { public String getPasteTitle() {
return this.developerKey; return this.pasteTitle;
} }
/** /**
* Sets the paste title * Sets the paste title
* *
* @param title * @param title title of the paste
* title of the paste */
*/ public void setPasteTitle(String title) {
public void setPasteTitle(String title) { this.pasteTitle = title;
this.pasteTitle = title; }
}
/** /**
* Gets paste title * Gets paste expire date
* *
* @return paste title * @return paste expire date
*/ */
public String getPasteTitle() { public PasteExpireDate getPasteExpireDate() {
return this.pasteTitle; return this.expireDate;
} }
/**
* Gets paste expire date
* @return paste expire date
*/
public PasteExpireDate getPasteExpireDate() {
return this.expireDate;
}
/** /**
* Sets the paste format The format is used for syntax highlighting * Sets the paste expire date
* *
* @see <a href="http://pastebin.com/api#5">available syntax highlighting * @param date date when the paste will be removed
* formats</a> */
* @param format public void setPasteExpireDate(PasteExpireDate date) {
* format of the paste this.expireDate = date;
*/ }
public void setPasteFormat(String format) {
this.pasteFormat = format;
}
/** /**
* Gets paste format * Gets paste format
* *
* @return paste format * @return paste format
*/ */
public String getPasteFormat() { public String getPasteFormat() {
return this.pasteFormat; return this.pasteFormat;
} }
/** /**
* Makes this paste private, unlisted or public Default visibility is public * Sets the paste format The format is used for syntax highlighting
* <p> *
* <strong>Valid visibilities</strong> * @param format format of the paste
* </p> * @see <a href="http://pastebin.com/api#5">available syntax highlighting
* <p> * formats</a>
* {@link PastebinPaste#VISIBILITY_PUBLIC} */
* </p> public void setPasteFormat(String format) {
* <p> this.pasteFormat = format;
* {@link PastebinPaste#VISIBILITY_UNLISTED} }
* </p>
* <p>
* {@link PastebinPaste#VISIBILITY_PRIVATE}
* </p>
*
* @param visibility
* the paste it's visibility
*/
public void setVisibility(int visibility) {
if (visibility < 0 || visibility > 2) {
throw new IllegalArgumentException("Unknown visibility: "
+ visibility);
}
this.visibility = visibility;
}
/** /**
* Gets this paste visibility * Gets this paste visibility
* <p> * <p>
* <strong>Valid visibilities</strong> * <strong>Valid visibilities</strong>
* </p> * </p>
* <p> * <p>
* {@link PastebinPaste#VISIBILITY_PUBLIC} * {@link PastebinPaste#VISIBILITY_PUBLIC}
* </p> * </p>
* <p> * <p>
* {@link PastebinPaste#VISIBILITY_UNLISTED} * {@link PastebinPaste#VISIBILITY_UNLISTED}
* </p> * </p>
* <p> * <p>
* {@link PastebinPaste#VISIBILITY_PRIVATE} * {@link PastebinPaste#VISIBILITY_PRIVATE}
* </p> * </p>
* *
* @return visibility of this paste * @return visibility of this paste
*/ */
public int getVisibility() { public int getVisibility() {
return this.visibility; return this.visibility;
} }
/** /**
* {@inheritDoc} * Makes this paste private, unlisted or public Default visibility is public
*/ * <p>
@Override * <strong>Valid visibilities</strong>
public PastebinLink paste() throws PasteException { * </p>
if (getContents() == null || getContents().isEmpty()) { * <p>
throw new IllegalStateException("Paste can not be null or empty."); * {@link PastebinPaste#VISIBILITY_PUBLIC}
} * </p>
if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) { * <p>
throw new IllegalStateException("Developer key is missing."); * {@link PastebinPaste#VISIBILITY_UNLISTED}
} * </p>
* <p>
* {@link PastebinPaste#VISIBILITY_PRIVATE}
* </p>
*
* @param visibility the paste it's visibility
*/
public void setVisibility(int visibility) {
if (visibility < 0 || visibility > 2) {
throw new IllegalArgumentException("Unknown visibility: "
+ visibility);
}
this.visibility = visibility;
}
Post post = new Post(); /**
* {@inheritDoc}
*/
@Override
public PastebinLink paste() throws PasteException {
if (getContents() == null || getContents().isEmpty()) {
throw new IllegalStateException("Paste can not be null or empty.");
}
if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) {
throw new IllegalStateException("Developer key is missing.");
}
// required parameters Post post = new Post();
post.put("api_dev_key", getDeveloperKey());
post.put("api_option", "paste");
post.put("api_paste_code", getContents());
// optional parameters // required parameters
if (this.account != null && this.account.getUserSessionId() != null) { post.put("api_dev_key", getDeveloperKey());
post.put("api_user_key", this.account.getUserSessionId()); post.put("api_option", "paste");
} post.put("api_paste_code", getContents());
if (this.pasteTitle != null) {
post.put("api_paste_name", getPasteTitle());
}
if (this.pasteFormat != null) {
post.put("api_paste_format", getPasteFormat());
}
post.put("api_paste_private", Integer.toString(getVisibility()));
if (this.expireDate != null) {
post.put("api_paste_expire_date", expireDate.getValue());
}
try { // optional parameters
String pageResponse = Web.getContents(Pastebin.API_POST_LINK, post); if (this.account != null && this.account.getUserSessionId() != null) {
if (pageResponse.startsWith("http")) { post.put("api_user_key", this.account.getUserSessionId());
// success }
PastebinLink result = new PastebinLink(this, new URL( if (this.pasteTitle != null) {
pageResponse)); post.put("api_paste_name", getPasteTitle());
return result; }
} if (this.pasteFormat != null) {
throw new PasteException("Failed to generate paste: " post.put("api_paste_format", getPasteFormat());
+ pageResponse); }
} catch (MalformedURLException e) { post.put("api_paste_private", Integer.toString(getVisibility()));
// shouldn't happen if (this.expireDate != null) {
throw new PasteException("Failed to generate paste: " + e); post.put("api_paste_expire_date", expireDate.getValue());
} }
}
try {
String pageResponse = Web.getContents(Pastebin.API_POST_LINK, post);
if (pageResponse.startsWith("http")) {
// success
PastebinLink result = new PastebinLink(this, new URL(
pageResponse));
return result;
}
throw new PasteException("Failed to generate paste: "
+ pageResponse);
} catch (MalformedURLException e) {
// shouldn't happen
throw new PasteException("Failed to generate paste: " + e);
}
}
} }

View File

@ -23,347 +23,330 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
/** /**
*
* Represents an account on <a href="http://pastebin.com/">Pastebin</a>. * Represents an account on <a href="http://pastebin.com/">Pastebin</a>.
* * <p>
* <p> * <p>
* This class can fetch a non-expiring user session id. This session id is used * This class can fetch a non-expiring user session id. This session id is used
* for generating private pasted, fetching user details, fetching user his * for generating private pasted, fetching user details, fetching user his
* pastes, adding pastes to his account & more account based interactions. * pastes, adding pastes to his account & more account based interactions.
* </p> * </p>
* * <p>
* <p> * <p>
* A reference manual for generating a user session id can be found <a * A reference manual for generating a user session id can be found <a
* href="http://pastebin.com/api#8">here</a>. * href="http://pastebin.com/api#8">here</a>.
* *
* @author Brian B * @author Brian B
*
*/ */
public class PastebinAccount { public class PastebinAccount {
private String username, password, userSessionId, developerKey; private String username, password, userSessionId, developerKey;
/** /**
* Creates a new empty <code>PastebinAccount</code> instance. * Creates a new empty <code>PastebinAccount</code> instance.
*/ */
public PastebinAccount() { public PastebinAccount() {
this(null, null, null); this(null, null, null);
} }
/** /**
* Creates a new <code>PastebinAccount</code> instance. * Creates a new <code>PastebinAccount</code> instance.
* * <p>
* When you use this constructor, you'll need to use the {@link #login()} to * When you use this constructor, you'll need to use the {@link #login()} to
* fetch an user session id * fetch an user session id
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param username the username of the pastebin account
* @param username * @param password the password of the pastebin account
* the username of the pastebin account */
* @param password public PastebinAccount(String developerKey, String username, String password) {
* the password of the pastebin account this.developerKey = developerKey;
*/ this.username = username;
public PastebinAccount(String developerKey, String username, String password) { this.password = password;
this.developerKey = developerKey; }
this.username = username;
this.password = password;
}
/** /**
* Creates a new <code>PastebinAccount</code> instance. * Creates a new <code>PastebinAccount</code> instance.
* *
* @param userSessionId * @param userSessionId the user session id of the pastebin account.
* the user session id of the pastebin account. */
*/ public PastebinAccount(String userSessionId) {
public PastebinAccount(String userSessionId) { this(null, userSessionId);
this(null, userSessionId); }
}
/** /**
* Creates a new <code>PastebinAccount</code> instance. * Creates a new <code>PastebinAccount</code> instance.
* *
* @param developerKey * @param developerKey a developer key which can be fetched from the pastebin API
* a developer key which can be fetched from the pastebin API * page
* page * @param userSessionId the user session id of the pastebin account.
* @param userSessionId */
* the user session id of the pastebin account. public PastebinAccount(String developerKey, String userSessionId) {
*/ this.developerKey = developerKey;
public PastebinAccount(String developerKey, String userSessionId) { this.userSessionId = userSessionId;
this.developerKey = developerKey; }
this.userSessionId = userSessionId;
}
/** /**
* Sets the user session id The user session id can be used to paste private * Gets the user session id
* pastes and will add pastes to your account *
* * @return user session id
* @param userSessionId */
* the user session id of the pastebin account public String getUserSessionId() {
*/ return this.userSessionId;
public void setUserSessionId(String userSessionId) { }
this.userSessionId = userSessionId;
}
/** /**
* Gets the user session id * Sets the user session id The user session id can be used to paste private
* * pastes and will add pastes to your account
* @return user session id *
*/ * @param userSessionId the user session id of the pastebin account
public String getUserSessionId() { */
return this.userSessionId; public void setUserSessionId(String userSessionId) {
} this.userSessionId = userSessionId;
}
/** /**
* Sets the username * Gets username of the pastebin account
* *
* @param username * @return username of the pastebin account. Could be null if only an user
* the username of the pastebin account * session is was provided.
*/ */
public void setUsername(String username) { public String getUsername() {
this.username = username; return this.username;
} }
/** /**
* Gets username of the pastebin account * Sets the username
* *
* @return username of the pastebin account. Could be null if only an user * @param username the username of the pastebin account
* session is was provided. */
*/ public void setUsername(String username) {
public String getUsername() { this.username = username;
return this.username; }
}
/** /**
* Sets the password * Gets password of the pastebin account
* *
* @param password * @return password of the pastebin account. Could be null if only an user
* the password of the pastebin account * session id was provided.
*/ */
public void setPassword(String password) { public String getPassword() {
this.password = password; return this.password;
} }
/** /**
* Gets password of the pastebin account * Sets the password
* *
* @return password of the pastebin account. Could be null if only an user * @param password the password of the pastebin account
* session id was provided. */
*/ public void setPassword(String password) {
public String getPassword() { this.password = password;
return this.password; }
}
/** /**
* Sets the developer key The developer key is required to paste contents on * Gets the developer key
* pastebin *
* * @return developer key
* @param developerKey */
* a developer key which can be fetched from the pastebin API public String getDeveloperKey() {
* page return this.developerKey;
*/ }
public void setDeveloperKey(String developerKey) {
if (developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException(
"Developer key can not be null or empty.");
}
this.developerKey = developerKey;
}
/** /**
* Gets the developer key * Sets the developer key The developer key is required to paste contents on
* * pastebin
* @return developer key *
*/ * @param developerKey a developer key which can be fetched from the pastebin API
public String getDeveloperKey() { * page
return this.developerKey; */
} public void setDeveloperKey(String developerKey) {
if (developerKey == null || developerKey.isEmpty()) {
throw new IllegalArgumentException(
"Developer key can not be null or empty.");
}
this.developerKey = developerKey;
}
/** /**
* Fetches an user session id. * Fetches an user session id.
* *
* @throws LoginException * @throws LoginException if fetching the user session id failed
* if fetching the user session id failed */
*/ public void login() throws LoginException {
public void login() throws LoginException { if (getUserSessionId() != null) {
if (getUserSessionId() != null) { throw new IllegalStateException("Already logged in.");
throw new IllegalStateException("Already logged in."); }
} if (getUsername() == null || getPassword() == null) {
if (getUsername() == null || getPassword() == null) { throw new IllegalStateException("Username or password null.");
throw new IllegalStateException("Username or password null."); }
} if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) {
if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) { throw new IllegalStateException("Developer key is missing.");
throw new IllegalStateException("Developer key is missing."); }
}
Post post = new Post(); Post post = new Post();
post.put("api_dev_key", getDeveloperKey()); post.put("api_dev_key", getDeveloperKey());
post.put("api_user_name", username); post.put("api_user_name", username);
post.put("api_user_password", password); post.put("api_user_password", password);
String response = Web.getContents(Pastebin.API_LOGIN_LINK, post); String response = Web.getContents(Pastebin.API_LOGIN_LINK, post);
if (response == null || response.isEmpty()) { if (response == null || response.isEmpty()) {
throw new LoginException("Empty response from login API server."); throw new LoginException("Empty response from login API server.");
} }
if (response.toLowerCase().startsWith("bad")) { if (response.toLowerCase().startsWith("bad")) {
throw new LoginException("Failed to login: " + response); throw new LoginException("Failed to login: " + response);
} }
this.userSessionId = response; this.userSessionId = response;
} }
/** /**
* Gets all pasted pastes by this user * Gets all pasted pastes by this user
* *
* @param limit * @param limit maximum amount of pastes to receive
* maximum amount of pastes to receive * <p>
* <p> * <code>0 > limit > 1000</code>
* <code>0 > limit > 1000</code> * </p>
* </p> * @return all pasted pastes made by this user/account
* @return all pasted pastes made by this user/account * @throws ParseException if it failed to parse the pastes
* @throws ParseException */
* if it failed to parse the pastes public PastebinLink[] getPastes(int limit) throws ParseException {
*/ if (limit > 1000) {
public PastebinLink[] getPastes(int limit) throws ParseException { limit = 1000;
if (limit > 1000) { }
limit = 1000; if (limit < 1) {
} limit = 1;
if (limit < 1) { }
limit = 1; if (getUserSessionId() == null) {
} throw new IllegalStateException("User session id missing.");
if (getUserSessionId() == null) { }
throw new IllegalStateException("User session id missing."); if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) {
} throw new IllegalStateException("Developer key is missing.");
if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) { }
throw new IllegalStateException("Developer key is missing.");
}
Post post = new Post(); Post post = new Post();
post.put("api_dev_key", getDeveloperKey()); post.put("api_dev_key", getDeveloperKey());
post.put("api_user_key", getUserSessionId()); post.put("api_user_key", getUserSessionId());
post.put("api_results_limit", Integer.toString(limit)); post.put("api_results_limit", Integer.toString(limit));
post.put("api_option", "list"); post.put("api_option", "list");
String response = Web.getContents(Pastebin.API_POST_LINK, post); String response = Web.getContents(Pastebin.API_POST_LINK, post);
if (response.equals("No pastes found.")) { if (response.equals("No pastes found.")) {
return null; return null;
} }
if (response.startsWith("<paste>")) { if (response.startsWith("<paste>")) {
// success // success
try { try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance(); .newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
response = "<dummy>" + response + "</dummy>"; // requires root response = "<dummy>" + response + "</dummy>"; // requires root
// element // element
Document doc = dBuilder.parse(new InputSource( Document doc = dBuilder.parse(new InputSource(
new ByteArrayInputStream(response.getBytes("utf-8")))); new ByteArrayInputStream(response.getBytes("utf-8"))));
doc.getDocumentElement().normalize(); doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("paste"); NodeList nodes = doc.getElementsByTagName("paste");
ArrayList<PastebinLink> pastes = new ArrayList<PastebinLink>( ArrayList<PastebinLink> pastes = new ArrayList<PastebinLink>(
nodes.getLength()); nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) { for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i); Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node; Element element = (Element) node;
String pasteFormat = XMLUtils.getText(element, String pasteFormat = XMLUtils.getText(element,
"paste_format_short"); "paste_format_short");
String title = XMLUtils.getText(element, "paste_title"); String title = XMLUtils.getText(element, "paste_title");
int visibility = Integer.parseInt(XMLUtils.getText( int visibility = Integer.parseInt(XMLUtils.getText(
element, "paste_private")); element, "paste_private"));
int hits = Integer.parseInt(XMLUtils.getText(element, int hits = Integer.parseInt(XMLUtils.getText(element,
"paste_hits")); "paste_hits"));
long expireDate = Long.parseLong(XMLUtils.getText( long expireDate = Long.parseLong(XMLUtils.getText(
element, "paste_expire_date")); element, "paste_expire_date"));
long pasteDate = Long.parseLong(XMLUtils.getText( long pasteDate = Long.parseLong(XMLUtils.getText(
element, "paste_date")); element, "paste_date"));
URL pasteURL = new URL(XMLUtils.getText(element, URL pasteURL = new URL(XMLUtils.getText(element,
"paste_url")); "paste_url"));
PastebinPaste paste = new PastebinPaste(this); PastebinPaste paste = new PastebinPaste(this);
paste.setPasteFormat(pasteFormat); paste.setPasteFormat(pasteFormat);
paste.setPasteTitle(title); paste.setPasteTitle(title);
paste.setVisibility(visibility); paste.setVisibility(visibility);
paste.setPasteExpireDate(expireDate == 0L ? PasteExpireDate.NEVER paste.setPasteExpireDate(expireDate == 0L ? PasteExpireDate.NEVER
: PasteExpireDate : PasteExpireDate
.getExpireDate((int) (expireDate - pasteDate))); .getExpireDate((int) (expireDate - pasteDate)));
PastebinLink pastebinLink = new PastebinLink(paste, PastebinLink pastebinLink = new PastebinLink(paste,
pasteURL, new Date(pasteDate * 1000)); pasteURL, new Date(pasteDate * 1000));
pastebinLink.setHits(hits); pastebinLink.setHits(hits);
pastes.add(pastebinLink); pastes.add(pastebinLink);
} }
} }
return pastes.toArray(new PastebinLink[pastes.size()]); return pastes.toArray(new PastebinLink[pastes.size()]);
} catch (Exception e) { } catch (Exception e) {
throw new ParseException("Failed to parse pastes: " throw new ParseException("Failed to parse pastes: "
+ e.getMessage()); + e.getMessage());
} }
} }
throw new ParseException("Failed to parse pastes: " + response); throw new ParseException("Failed to parse pastes: " + response);
} }
/** /**
* Gets pasted pastes (max 50) by this user * Gets pasted pastes (max 50) by this user
* *
* @return all pasted pastes made by this user/account * @return all pasted pastes made by this user/account
* @throws ParseException * @throws ParseException if it failed to parse the pastes
* if it failed to parse the pastes */
*/ public PastebinLink[] getPastes() throws ParseException {
public PastebinLink[] getPastes() throws ParseException { return getPastes(50);
return getPastes(50); }
}
/** /**
* Fetches the account details of this account * Fetches the account details of this account
* *
* @return account details * @return account details
* @throws ParseException * @throws ParseException if it failed to parse the account details
* if it failed to parse the account details */
*/ public PastebinAccountDetails getAccountDetails() throws ParseException {
public PastebinAccountDetails getAccountDetails() throws ParseException { if (getUserSessionId() == null) {
if (getUserSessionId() == null) { throw new IllegalStateException("User session id missing.");
throw new IllegalStateException("User session id missing."); }
} if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) {
if (getDeveloperKey() == null || getDeveloperKey().isEmpty()) { throw new IllegalStateException("Developer key is missing.");
throw new IllegalStateException("Developer key is missing."); }
}
Post post = new Post(); Post post = new Post();
post.put("api_dev_key", getDeveloperKey()); post.put("api_dev_key", getDeveloperKey());
post.put("api_user_key", getUserSessionId()); post.put("api_user_key", getUserSessionId());
post.put("api_option", "userdetails"); post.put("api_option", "userdetails");
String response = Web.getContents(Pastebin.API_POST_LINK, post); String response = Web.getContents(Pastebin.API_POST_LINK, post);
if (!response.startsWith("<user>")) { if (!response.startsWith("<user>")) {
throw new ParseException("Failed to parse account details: " throw new ParseException("Failed to parse account details: "
+ response); + response);
} }
try { try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance(); .newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource( Document doc = dBuilder.parse(new InputSource(
new ByteArrayInputStream(response.getBytes("utf-8")))); new ByteArrayInputStream(response.getBytes("utf-8"))));
doc.getDocumentElement().normalize(); doc.getDocumentElement().normalize();
return new PastebinAccountDetails((Element) doc return new PastebinAccountDetails((Element) doc
.getElementsByTagName("user").item(0)); .getElementsByTagName("user").item(0));
} catch (Exception e) { } catch (Exception e) {
throw new ParseException("Failed to parse account details: " + e); throw new ParseException("Failed to parse account details: " + e);
} }
} }
} }

View File

@ -10,125 +10,132 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
/** /**
*
* Holds information and settings of a pastebin account. * Holds information and settings of a pastebin account.
* *
* @author Brian B * @author Brian B
*
*/ */
public class PastebinAccountDetails { public class PastebinAccountDetails {
private String username, format, expiration, avatarURL, website, email, location; private String username, format, expiration, avatarURL, website, email, location;
private int userPrivate, accountType; private int userPrivate, accountType;
/** /**
* Creates a new <code>PastebinAccountDetails</code> instance. * Creates a new <code>PastebinAccountDetails</code> instance.
* *
* @param userElement * @param userElement the 'user' xml elements received from the pastebin API
* the 'user' xml elements received from the pastebin API */
*/ public PastebinAccountDetails(Element userElement) {
public PastebinAccountDetails(Element userElement) { this.username = XMLUtils.getText(userElement, "user_name");
this.username = XMLUtils.getText(userElement, "user_name"); this.format = XMLUtils.getText(userElement, "user_format_short");
this.format = XMLUtils.getText(userElement, "user_format_short"); this.expiration = XMLUtils.getText(userElement, "user_expiration");
this.expiration = XMLUtils.getText(userElement, "user_expiration"); this.avatarURL = XMLUtils.getText(userElement, "user_avatar_url");
this.avatarURL = XMLUtils.getText(userElement, "user_avatar_url"); this.userPrivate = Integer.parseInt(XMLUtils.getText(userElement, "user_private"));
this.userPrivate = Integer.parseInt(XMLUtils.getText(userElement, "user_private")); this.website = XMLUtils.getText(userElement, "user_website");
this.website = XMLUtils.getText(userElement, "user_website"); this.email = XMLUtils.getText(userElement, "user_email");
this.email = XMLUtils.getText(userElement, "user_email"); this.location = XMLUtils.getText(userElement, "user_location");
this.location = XMLUtils.getText(userElement, "user_location"); this.accountType = Integer.parseInt(XMLUtils.getText(userElement, "user_account_type"));
this.accountType = Integer.parseInt(XMLUtils.getText(userElement, "user_account_type")); }
}
/**
/** * Gets the username of this account
* Gets the username of this account *
* @return username * @return username
*/ */
public String getUsername() { public String getUsername() {
return this.username; return this.username;
} }
/** /**
* Gets user text format * Gets user text format
* @return user text format *
*/ * @return user text format
public String getFormat() { */
return this.format; public String getFormat() {
} return this.format;
}
/**
* Gets this account expiration time /**
* <p> * Gets this account expiration time
* <code>N = never (default)</code> * <p>
* </p> * <code>N = never (default)</code>
* @return account expiration time * </p>
*/ *
public String getExpiration() { * @return account expiration time
return this.expiration; */
} public String getExpiration() {
return this.expiration;
/** }
* Gets URL to avatar image
* @return URL to avatar image /**
* @throws MalformedURLException * Gets URL to avatar image
*/ *
public URL getAvatarURL() throws MalformedURLException { * @return URL to avatar image
return new URL(this.avatarURL); * @throws MalformedURLException
} */
public URL getAvatarURL() throws MalformedURLException {
/** return new URL(this.avatarURL);
* Gets user visibility }
* <pre>
* 0 = public /**
* 1 = unlisted * Gets user visibility
* 2 = private * <pre>
* </pre> * 0 = public
* @return visibility of account * 1 = unlisted
*/ * 2 = private
public int getPrivate() { * </pre>
return this.userPrivate; *
} * @return visibility of account
*/
/** public int getPrivate() {
* Gets the user's set website return this.userPrivate;
* @return url to website }
* @throws MalformedURLException
*/ /**
public URL getWebsite() throws MalformedURLException { * Gets the user's set website
if(this.website.isEmpty()) { *
return null; * @return url to website
} * @throws MalformedURLException
return new URL(this.website); */
} public URL getWebsite() throws MalformedURLException {
if (this.website.isEmpty()) {
/** return null;
* Gets the user e-mail }
* @return user account e-mail return new URL(this.website);
*/ }
public String getEmail() {
return this.email; /**
} * Gets the user e-mail
*
/** * @return user account e-mail
* Gets the user's set location */
* @return location, city public String getEmail() {
*/ return this.email;
public String getLocation() { }
return this.location;
} /**
* Gets the user's set location
/** *
* Determines if this account is a 'pro' account * @return location, city
* @return <code>true</code> if this account is a pro account, otherwise <code>false</code>. */
*/ public String getLocation() {
public boolean isPro() { return this.location;
return accountType == 1; }
}
/**
/** * Determines if this account is a 'pro' account
* Fetches the user his avatar from {@link #getAvatarURL()} *
* @return image * @return <code>true</code> if this account is a pro account, otherwise <code>false</code>.
* @throws IOException if image was not read */
*/ public boolean isPro() {
public BufferedImage getAvatar() throws IOException { return accountType == 1;
return ImageIO.read(getAvatarURL()); }
}
/**
* Fetches the user his avatar from {@link #getAvatarURL()}
*
* @return image
* @throws IOException if image was not read
*/
public BufferedImage getAvatar() throws IOException {
return ImageIO.read(getAvatarURL());
}
} }

View File

@ -1,12 +1,12 @@
package org.jpaste.pastebin.exceptions; package org.jpaste.pastebin.exceptions;
public class LoginException extends Exception { public class LoginException extends Exception {
private static final long serialVersionUID = -4230960075582953775L; private static final long serialVersionUID = -4230960075582953775L;
public LoginException() { public LoginException() {
} }
public LoginException(String message) { public LoginException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,13 +1,13 @@
package org.jpaste.pastebin.exceptions; package org.jpaste.pastebin.exceptions;
public class ParseException extends Exception { public class ParseException extends Exception {
private static final long serialVersionUID = -4230960075582953775L; private static final long serialVersionUID = -4230960075582953775L;
public ParseException() { public ParseException() {
} }
public ParseException(String message) { public ParseException(String message) {
super(message); super(message);
} }
} }

View File

@ -6,61 +6,57 @@ import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
/** /**
*
* A representation of a HTTP post * A representation of a HTTP post
* * <p>
* <p> * <p>
* Encodes parameters with the UTF-8 Charset. * Encodes parameters with the UTF-8 Charset.
* </p> * </p>
* * <p>
* <p> * <p>
* <a href="http://en.wikipedia.org/wiki/POST_(HTTP)">Reference manual</a> * <a href="http://en.wikipedia.org/wiki/POST_(HTTP)">Reference manual</a>
* </p> * </p>
* *
* @author Brian B * @author Brian B
*
*/ */
public class Post { public class Post {
private static final String ENCODING = "UTF-8"; private static final String ENCODING = "UTF-8";
private HashMap<String, String> post; private HashMap<String, String> post;
/** /**
* Creates a new <code>Post</code> instance. * Creates a new <code>Post</code> instance.
*/ */
public Post() { public Post() {
post = new HashMap<String, String>(); post = new HashMap<String, String>();
} }
/** /**
* Adds a key value pair to the post parameters * Adds a key value pair to the post parameters
* *
* @param key * @param key the key
* the key * @param value the value
* @param value */
* the value public void put(String key, String value) {
*/ try {
public void put(String key, String value) { this.post.put(URLEncoder.encode(key, ENCODING),
try { URLEncoder.encode(value, ENCODING));
this.post.put(URLEncoder.encode(key, ENCODING), } catch (UnsupportedEncodingException e) {
URLEncoder.encode(value, ENCODING)); e.printStackTrace();
} catch (UnsupportedEncodingException e) { }
e.printStackTrace(); }
}
}
/** /**
* The HTTP post string representation * The HTTP post string representation
* *
* @return HTTP Post contents * @return HTTP Post contents
*/ */
public String getPost() { public String getPost() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (Entry<String, String> entry : post.entrySet()) { for (Entry<String, String> entry : post.entrySet()) {
builder.append(entry.getKey()).append('=').append(entry.getValue()) builder.append(entry.getKey()).append('=').append(entry.getValue())
.append('&'); .append('&');
} }
builder.deleteCharAt(builder.length() - 1); builder.deleteCharAt(builder.length() - 1);
return new String(builder); return new String(builder);
} }
} }

View File

@ -9,67 +9,62 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
/** /**
*
* Web utility class * Web utility class
* *
* @author Brian B * @author Brian B
*
*/ */
public class Web { public class Web {
/** /**
* Submits a HTTP post and fetches and returns the response * Submits a HTTP post and fetches and returns the response
* *
* @param link * @param link The link/URL
* The link/URL * @param post the HTTP post representation
* @param post * @return response of the web page
* the HTTP post representation */
* @return response of the web page public static String getContents(String link, Post post) {
*/ try {
public static String getContents(String link, Post post) { URL url = new URL(link);
try {
URL url = new URL(link);
URLConnection connection = url.openConnection(); URLConnection connection = url.openConnection();
if(post != null) { if (post != null) {
connection.setDoOutput(true); connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter( OutputStreamWriter wr = new OutputStreamWriter(
connection.getOutputStream()); connection.getOutputStream());
wr.write(post.getPost()); wr.write(post.getPost());
wr.flush(); wr.flush();
wr.close(); wr.close();
} }
BufferedReader reader = new BufferedReader(new InputStreamReader( BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream())); connection.getInputStream()));
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
if (builder.length() > 0) { if (builder.length() > 0) {
builder.append('\n'); builder.append('\n');
} }
builder.append(line); builder.append(line);
} }
reader.close(); reader.close();
return new String(builder); return new String(builder);
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed link: " + e); throw new IllegalArgumentException("Malformed link: " + e);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to fetch contents from link: " throw new RuntimeException("Failed to fetch contents from link: "
+ e); + e);
} }
} }
/** /**
* Gets text from a link * Gets text from a link
* *
* @param link * @param link The link/URL
* The link/URL * @return response of the web page
* @return response of the web page */
*/ public static String getContents(String link) {
public static String getContents(String link) { return getContents(link, null);
return getContents(link, null); }
}
} }

View File

@ -3,25 +3,21 @@ package org.jpaste.utils.xml;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
*
* Holds various XML utility methods * Holds various XML utility methods
* *
* @author Brian B * @author Brian B
*
*/ */
public class XMLUtils { public class XMLUtils {
/** /**
* Fetches text from a element * Fetches text from a element
* *
* @param parent * @param parent the parent of the element you want to fetch text from
* the parent of the element you want to fetch text from * @param tagName name of the element you want to fetch text from
* @param tagName * @return text of tag
* name of the element you want to fetch text from */
* @return text of tag public static String getText(Element parent, String tagName) {
*/ return parent.getElementsByTagName(tagName).item(0).getTextContent();
public static String getText(Element parent, String tagName) { }
return parent.getElementsByTagName(tagName).item(0).getTextContent();
}
} }