diff options
Diffstat (limited to 'src/mining/AbstractRequester.java')
-rw-r--r-- | src/mining/AbstractRequester.java | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/src/mining/AbstractRequester.java b/src/mining/AbstractRequester.java new file mode 100644 index 0000000..a42eb80 --- /dev/null +++ b/src/mining/AbstractRequester.java @@ -0,0 +1,72 @@ +package mining; + +import java.io.IOException; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import org.apache.commons.io.Charsets; +import org.apache.commons.io.IOUtils; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Performs an API Request. + * + * @author Peter Wu + */ +public abstract class AbstractRequester implements Requester { + + @Override + public JSONObject getJSON(String resource) throws IOException { + HttpURLConnection conn = open(buildUrl(resource)); + preconnect(conn); + if (conn.getResponseCode() != 200) { + // TODO: print more helpful details + throw new IOException("Unexpected response code"); + } + return getResponseAsJson(conn); + } + + protected final URL buildUrl(String resource) throws IOException { + String spec = "https://api.twitter.com/1.1/"; + // TODO: detect API version? For example, drop 1.1 for oauth2/token + spec += resource; + return new URL(spec); + } + + /** + * Opens a connection to the URL. + */ + protected final HttpURLConnection open(URL url) throws IOException { + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + // set default param: fail if no response within 5 seconds + conn.setReadTimeout(5000); + return conn; + } + + /** + * Reads the response body from a connection (in JSON format). + */ + protected final JSONObject getResponseAsJson(URLConnection conn) + throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(conn.getInputStream(), writer, Charsets.UTF_8); + try { + return new JSONObject(writer.toString()); + } catch (JSONException ex) { + // treat JSON errors as if an I/O error occurred + throw new IOException(ex); + } + } + + /** + * Prepare the request before it gets send. + * + * @param conn A connection for the request. + * @throws java.io.IOException on failing to prepare the request. + */ + protected abstract void preconnect(URLConnection conn) + throws IOException; +} |