Now using pastebin4j

This commit is contained in:
Jaime Martinez Rincon 2017-08-08 14:38:45 +02:00
parent 8dd1a0c62f
commit 4d25772742
19 changed files with 67 additions and 1522 deletions

View File

@ -16,7 +16,7 @@
- [ ] Make the feature `marker-descs` work per section
- [ ] Unify the code that loads server into a section (duplicated at SectionManager and ServerSection)
- [ ] Unify some of the code used in the FallbackCommand and SectionCommand
- [ ] Use https://github.com/kennedyoliveira/pastebin4j instead of jpaste
- [x] Use https://github.com/kennedyoliveira/pastebin4j instead of jpaste
- [ ] (!) Make the section initialization work in stages instead of being hardcoded
- [ ] (!) Ditch the faucet dependency and use [ConfigMe](https://github.com/AuthMe/ConfigMe) and [DependencyInjector](https://github.com/ljacqu/DependencyInjector) instead
- [ ] Use a separate file for configuring the sections, must be done alongside the previous item

20
pom.xml
View File

@ -4,9 +4,9 @@
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>
<groupId>me.jaimemartz</groupId>
<artifactId>lobbybalancer</artifactId>
<version>2.0.9.9</version>
<groupId>com.jaimemartz</groupId>
<artifactId>playerbalancer</artifactId>
<version>2.1</version>
<name>LobbyBalancer</name>
<properties>
@ -32,7 +32,7 @@
</repository>
<repository>
<id>bstats-repo</id>
<url>https://repo.bstats.org/content/groups/public/</url>
<url>http://repo.bstats.org/content/repositories/releases/</url>
</repository>
</repositories>
<build>
@ -96,6 +96,18 @@
<version>1.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.jalu</groupId>
<artifactId>configme</artifactId>
<version>0.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.kennedyoliveira</groupId>
<artifactId>pastebin4j</artifactId>
<version>1.2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.jaimemartz</groupId>
<artifactId>faucet-bungee</artifactId>

View File

@ -16,7 +16,8 @@ import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import org.bstats.Metrics;
import org.bstats.bungeecord.Metrics;
import org.bstats.bungeecord.Metrics.SingleLineChart;
import org.inventivetalent.update.bungee.BungeeUpdater;
import java.io.IOException;
@ -48,7 +49,7 @@ public class LobbyBalancer extends Plugin {
//Metrics (https://bstats.org/)
Metrics metrics = new Metrics(this);
metrics.addCustomChart(new Metrics.SingleLineChart("configured_sections", () -> sectionManager.getSections().size()));
metrics.addCustomChart(new SingleLineChart("configured_sections", () -> sectionManager.getSections().size()));
}
private void enable() {
@ -60,7 +61,7 @@ public class LobbyBalancer extends Plugin {
String text = ConfigEntries.CONFIG_VERSION.get();
int configVersion = DigitUtils.getDigits(text, 8);
if (configVersion < LAST_VER_CONFIG_UPDATE) {
failed = true;
this.failed = true;
throw new IllegalStateException("Your config is outdated, please reset it and configure it again");
}

View File

@ -7,12 +7,25 @@ import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class MainCommand extends Command {
private final LobbyBalancer plugin;
private final URL hastebin;
public MainCommand(LobbyBalancer plugin) {
super("balancer");
this.plugin = plugin;
try {
this.hastebin = new URL("https://hastebin.com/documents");
} catch (MalformedURLException ignored) {}
}
@Override

View File

@ -1,15 +1,12 @@
package me.jaimemartz.lobbybalancer.manager;
import com.github.kennedyoliveira.pastebin4j.*;
import com.google.common.io.CharStreams;
import me.jaimemartz.lobbybalancer.LobbyBalancer;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.scheduler.ScheduledTask;
import org.jpaste.exceptions.PasteException;
import org.jpaste.pastebin.PasteExpireDate;
import org.jpaste.pastebin.PastebinLink;
import org.jpaste.pastebin.PastebinPaste;
import java.io.File;
import java.io.FileInputStream;
@ -25,21 +22,25 @@ public enum PasteHelper {
return "File does not exist";
}
PastebinPaste paste = new PastebinPaste();
paste.setPasteTitle("{name} ({version} on {bungee_version}) Configuration"
GuestPaste paste = new GuestPaste();
paste.setTitle("{name} ({version} on {bungee_version}) Configuration"
.replace("{name}", plugin.getDescription().getName())
.replace("{version}", plugin.getDescription().getVersion())
.replace("{bungee_version}", plugin.getProxy().getVersion())
);
paste.setDeveloperKey(DEVELOPER_KEY);
paste.setPasteExpireDate(PasteExpireDate.ONE_MONTH);
paste.setVisibility(PastebinPaste.VISIBILITY_UNLISTED);
paste.setPasteFormat("yaml");
paste.setExpiration(PasteExpiration.ONE_MONTH);
paste.setVisibility(PasteVisibility.UNLISTED);
paste.setHighLight(PasteHighLight.YAML);
try (FileInputStream stream = new FileInputStream(file)) {
paste.setContents(CharStreams.toString(new InputStreamReader(stream, "UTF-8")));
try (InputStreamReader reader = new InputStreamReader(stream, "UTF-8")) {
String content = CharStreams.toString(reader);
paste.setContent(content);
}
}
PastebinLink link = paste.paste();
return link.getLink().toString();
return paste.paste(credentials);
}
},
BUNGEE {
@ -50,42 +51,40 @@ public enum PasteHelper {
return "File does not exist";
}
PastebinPaste paste = new PastebinPaste();
paste.setPasteTitle("{name} ({version}) Configuration"
GuestPaste paste = new GuestPaste();
paste.setTitle("{name} ({version}) Configuration"
.replace("{name}", plugin.getProxy().getName())
.replace("{version}", plugin.getProxy().getVersion())
);
paste.setDeveloperKey(DEVELOPER_KEY);
paste.setPasteExpireDate(PasteExpireDate.ONE_MONTH);
paste.setVisibility(PastebinPaste.VISIBILITY_UNLISTED);
paste.setPasteFormat("yaml");
paste.setExpiration(PasteExpiration.ONE_MONTH);
paste.setVisibility(PasteVisibility.UNLISTED);
paste.setHighLight(PasteHighLight.YAML);
try (FileInputStream stream = new FileInputStream(file)) {
paste.setContents(CharStreams.toString(new InputStreamReader(stream, "UTF-8")));
try (InputStreamReader reader = new InputStreamReader(stream, "UTF-8")) {
String content = CharStreams.toString(reader);
content = content.replaceAll("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}", "X.X.X.X");
paste.setContent(content);
}
}
PastebinLink link = paste.paste();
return link.getLink().toString();
return paste.paste(credentials);
}
};
public static final String DEVELOPER_KEY = "e3ff18d8fb001a3ece08ae0d7d4a87bd";
private String link;
private ScheduledTask task = null;
public void send(LobbyBalancer plugin, CommandSender sender, String message) {
try {
sender.sendMessage(new ComponentBuilder(message.replace("{link}", link == null ? link = paste(plugin) : link)
).color(ChatColor.GREEN).create());
sender.sendMessage(new ComponentBuilder(message.replace("{link}", link == null ? link = paste(plugin) : link)).color(ChatColor.GREEN).create());
if (task != null) {
plugin.getProxy().getScheduler().cancel(task);
}
task = plugin.getProxy().getScheduler().schedule(plugin, () -> link = null, 5, TimeUnit.MINUTES);
} catch (PasteException e) {
if (e.getMessage().equals("Failed to generate paste: Post limit, maximum pastes per 24h reached")) {
sender.sendMessage(new ComponentBuilder("The file could not be pasted, your ip has reached the 10 pastes per day limit").color(ChatColor.RED).create());
} else {
sender.sendMessage(new ComponentBuilder("An unexpected error occurred while pasting the file").color(ChatColor.RED).create());
}
e.printStackTrace();
} catch (Exception e) {
sender.sendMessage(new ComponentBuilder("An internal error occurred while attempting to perform this command").color(ChatColor.RED).create());
e.printStackTrace();
@ -93,4 +92,6 @@ public enum PasteHelper {
}
public abstract String paste(LobbyBalancer plugin) throws Exception;
private static final AccountCredentials credentials = new AccountCredentials("e3ff18d8fb001a3ece08ae0d7d4a87bd");
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,175 +0,0 @@
package org.jpaste.pastebin;
import org.jpaste.AbstractPasteLink;
import org.jpaste.exceptions.PasteException;
import org.jpaste.pastebin.account.PastebinAccount;
import org.jpaste.utils.web.Post;
import org.jpaste.utils.web.Web;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
/**
* A representation of an online pastebin paste.
* <p>
* <p>
* <p>
* This class represents an existing pastebin paste URL
* </p>
*
* @author Brian B
*/
public class PastebinLink extends AbstractPasteLink {
private PastebinPaste paste;
private URL link;
private int hits;
private String key;
private Date pasteDate;
/**
* Creates a new <code>PastebinLink</code> object, representing an existing
* paste
*
* @param paste paste details
* @param url link to paste
*/
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
* paste
*
* @param paste paste details
* @param url link to paste
* @param pasteDate date the paste has been pasted
*/
public PastebinLink(PastebinPaste paste, URL url, Date pasteDate) {
this.paste = paste;
this.link = url;
this.pasteDate = pasteDate;
try {
this.key = url.toURI().getPath().substring(1);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
/**
* Fetches a paste text from pastebin
*
* @param pasteKey the unique paste key
* @return contents of the paste
*/
public static String getContents(String pasteKey) {
return Web.getContents("http://pastebin.com/raw.php?i=" + pasteKey);
}
/**
* {@inheritDoc}
*/
@Override
public URL getLink() {
return link;
}
/**
* Gets pastebin paste details
*
* @return paste details
*/
public PastebinPaste getPaste() {
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()));
}
/**
* Gets the paste page hits
*
* @return paste page hits
*/
public int getHits() {
return this.hits;
}
/**
* Sets the paste page hits
*
* @param hits amount of times paste has been visited
*/
public void setHits(int hits) {
if (hits < 0) {
throw new IllegalArgumentException("Hits must be positive: " + hits);
}
this.hits = hits;
}
/**
* Gets the paste date
*
* @return paste date
*/
public Date getPasteDate() {
return this.pasteDate;
}
/**
* 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

@ -1,298 +0,0 @@
package org.jpaste.pastebin;
import org.jpaste.AbstractPaste;
import org.jpaste.exceptions.PasteException;
import org.jpaste.pastebin.account.PastebinAccount;
import org.jpaste.utils.web.Post;
import org.jpaste.utils.web.Web;
import java.net.MalformedURLException;
import java.net.URL;
/**
* A representation of a new or existing paste.
* <p>
* <p>
* This class holds the contents of the paste itself. You can get and modify
* settings and then 'push' this paste onto <a
* href="http://pastebin.com/">pastebin.</a>
* </p>
* <p>
* <p>
* This class has been programmed with the help of the <a
* href="http://pastebin.com/api/">pastebin API manual.</a>
* </p>
*
* @author Brian B
*/
public class PastebinPaste extends AbstractPaste<PastebinLink> {
/**
* Makes a paste public.
*/
public static final int VISIBILITY_PUBLIC = 0;
/**
* Makes a paste unlisted.
*/
public static final int VISIBILITY_UNLISTED = 1;
/**
* Makes a paste private.
* <p>
* Requires an {@link PastebinAccount
* org.jpaste.pastebin.account.PastebinAccount PastebinAccount}
* </p>
*/
public static final int VISIBILITY_PRIVATE = 2;
private String developerKey;
private PastebinAccount account;
private String pasteTitle;
private String pasteFormat;
private PasteExpireDate expireDate;
private int visibility;
/**
* Creates a new empty <code>PastebinPaste</code> instance.
*/
public PastebinPaste() {
this(null, null, null);
}
/**
* Creates a new <code>PastebinPaste</code> instance.
*
* @param contents the paste contents
*/
public PastebinPaste(String contents) {
this(null, contents, null);
}
/**
* Creates a new <code>PastebinPaste</code> instance.
*
* @param account a pastebin account
*/
public PastebinPaste(PastebinAccount account) {
this(account.getDeveloperKey(), null, account);
}
/**
* Creates a new <code>PastebinPaste</code> instance.
*
* @param developerKey a developer key which can be fetched from the pastebin API
* page
* @param contents the contents of the paste
*/
public PastebinPaste(String developerKey, String contents) {
this(developerKey, contents, null);
}
/**
* Creates a new <code>PastebinPaste</code> instance.
*
* @param developerKey a developer key which can be fetched from the pastebin API
* page
* @param contents the contents of the paste
* @param account a pastebin account
*/
public PastebinPaste(String developerKey, String contents,
PastebinAccount account) {
super(contents);
this.developerKey = developerKey;
this.account = account;
}
/**
* Gets the pastebin account
*
* @return pastebin account
*/
public PastebinAccount getAccount() {
return this.account;
}
/**
* Sets the pastebin account If you set an account the pastes will be listed
* on your account.
*
* @param account a pastebin account
*/
public void setAccount(PastebinAccount account) {
this.account = account;
}
/**
* Gets the developer key
*
* @return developer key
*/
public String getDeveloperKey() {
return this.developerKey;
}
/**
* Sets the developer key The developer key is required to paste contents on
* pastebin
*
* @param developerKey a developer key which can be fetched from the pastebin API
* page
*/
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 paste title
*
* @return paste title
*/
public String getPasteTitle() {
return this.pasteTitle;
}
/**
* Sets the paste title
*
* @param title title of the paste
*/
public void setPasteTitle(String title) {
this.pasteTitle = title;
}
/**
* Gets paste expire date
*
* @return paste expire date
*/
public PasteExpireDate getPasteExpireDate() {
return this.expireDate;
}
/**
* Sets the paste expire date
*
* @param date date when the paste will be removed
*/
public void setPasteExpireDate(PasteExpireDate date) {
this.expireDate = date;
}
/**
* Gets paste format
*
* @return paste format
*/
public String getPasteFormat() {
return this.pasteFormat;
}
/**
* Sets the paste format The format is used for syntax highlighting
*
* @param format format of the paste
* @see <a href="http://pastebin.com/api#5">available syntax highlighting
* formats</a>
*/
public void setPasteFormat(String format) {
this.pasteFormat = format;
}
/**
* Gets this paste visibility
* <p>
* <strong>Valid visibilities</strong>
* </p>
* <p>
* {@link PastebinPaste#VISIBILITY_PUBLIC}
* </p>
* <p>
* {@link PastebinPaste#VISIBILITY_UNLISTED}
* </p>
* <p>
* {@link PastebinPaste#VISIBILITY_PRIVATE}
* </p>
*
* @return visibility of this paste
*/
public int getVisibility() {
return this.visibility;
}
/**
* Makes this paste private, unlisted or public Default visibility is public
* <p>
* <strong>Valid visibilities</strong>
* </p>
* <p>
* {@link PastebinPaste#VISIBILITY_PUBLIC}
* </p>
* <p>
* {@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;
}
/**
* {@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.");
}
Post post = new Post();
// required parameters
post.put("api_dev_key", getDeveloperKey());
post.put("api_option", "paste");
post.put("api_paste_code", getContents());
// optional parameters
if (this.account != null && this.account.getUserSessionId() != null) {
post.put("api_user_key", this.account.getUserSessionId());
}
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 {
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

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

View File

@ -1,141 +0,0 @@
package org.jpaste.pastebin.account;
import org.jpaste.utils.xml.XMLUtils;
import org.w3c.dom.Element;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Holds information and settings of a pastebin account.
*
* @author Brian B
*/
public class PastebinAccountDetails {
private String username, format, expiration, avatarURL, website, email, location;
private int userPrivate, accountType;
/**
* Creates a new <code>PastebinAccountDetails</code> instance.
*
* @param userElement the 'user' xml elements received from the pastebin API
*/
public PastebinAccountDetails(Element userElement) {
this.username = XMLUtils.getText(userElement, "user_name");
this.format = XMLUtils.getText(userElement, "user_format_short");
this.expiration = XMLUtils.getText(userElement, "user_expiration");
this.avatarURL = XMLUtils.getText(userElement, "user_avatar_url");
this.userPrivate = Integer.parseInt(XMLUtils.getText(userElement, "user_private"));
this.website = XMLUtils.getText(userElement, "user_website");
this.email = XMLUtils.getText(userElement, "user_email");
this.location = XMLUtils.getText(userElement, "user_location");
this.accountType = Integer.parseInt(XMLUtils.getText(userElement, "user_account_type"));
}
/**
* Gets the username of this account
*
* @return username
*/
public String getUsername() {
return this.username;
}
/**
* Gets user text format
*
* @return user text format
*/
public String getFormat() {
return this.format;
}
/**
* Gets this account expiration time
* <p>
* <code>N = never (default)</code>
* </p>
*
* @return account expiration time
*/
public String getExpiration() {
return this.expiration;
}
/**
* Gets URL to avatar image
*
* @return URL to avatar image
* @throws MalformedURLException
*/
public URL getAvatarURL() throws MalformedURLException {
return new URL(this.avatarURL);
}
/**
* Gets user visibility
* <pre>
* 0 = public
* 1 = unlisted
* 2 = private
* </pre>
*
* @return visibility of account
*/
public int getPrivate() {
return this.userPrivate;
}
/**
* Gets the user's set website
*
* @return url to website
* @throws MalformedURLException
*/
public URL getWebsite() throws MalformedURLException {
if (this.website.isEmpty()) {
return null;
}
return new URL(this.website);
}
/**
* Gets the user e-mail
*
* @return user account e-mail
*/
public String getEmail() {
return this.email;
}
/**
* Gets the user's set location
*
* @return location, city
*/
public String getLocation() {
return this.location;
}
/**
* Determines if this account is a 'pro' account
*
* @return <code>true</code> if this account is a pro account, otherwise <code>false</code>.
*/
public boolean isPro() {
return accountType == 1;
}
/**
* 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 +0,0 @@
package org.jpaste.pastebin.exceptions;
public class LoginException extends Exception {
private static final long serialVersionUID = -4230960075582953775L;
public LoginException() {
}
public LoginException(String message) {
super(message);
}
}

View File

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

View File

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

View File

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

View File

@ -1,23 +0,0 @@
package org.jpaste.utils.xml;
import org.w3c.dom.Element;
/**
* Holds various XML utility methods
*
* @author Brian B
*/
public class XMLUtils {
/**
* Fetches text from a element
*
* @param parent the parent of the element you want to fetch text from
* @param tagName 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();
}
}