summaryrefslogtreecommitdiff
path: root/src/io/AbstractRequester.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/io/AbstractRequester.java')
-rw-r--r--src/io/AbstractRequester.java22
1 files changed, 15 insertions, 7 deletions
diff --git a/src/io/AbstractRequester.java b/src/io/AbstractRequester.java
index 239e75d..913e9bd 100644
--- a/src/io/AbstractRequester.java
+++ b/src/io/AbstractRequester.java
@@ -1,6 +1,8 @@
package io;
+import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -24,28 +26,35 @@ public abstract class AbstractRequester implements Requester {
private static final String API_URL = "https://api.twitter.com/";
@Override
- public Response getJSON(String resource) throws IOException {
+ public Response getJSON(String resource)
+ throws IOException, RateLimitException {
HttpURLConnection conn = open(buildUrl(resource));
try {
preconnect(conn);
JsonElement resp = getResponseAsJson(conn);
-
- if(resp.isJsonObject() && resp.getAsJsonObject().has("errors")) {
+
+ if (resp.isJsonObject() && resp.getAsJsonObject().has("errors")) {
/* print response to stderr for debugging */
String errors = resp.getAsJsonObject().get("errors").toString();
getLogger().log(Level.INFO, "Request failed: {0}", errors);
}
+
+
// TODO: what if there is an internal server error? Technically we
// should always treat that as "don't know what the server thinks".
if (conn.getResponseCode() != 200) {
+ if (conn.getResponseCode() == 429) {
+ //TODO: wait for real time and not 15 minutes.
+ throw new RateLimitException(Integer.parseInt(conn.getHeaderField("X-Rate-Limit-Reset")));
+ }
// TODO: print more helpful details
throw new IOException("Unexpected response code");
- }
+ }
int rateLimit = Integer.parseInt(conn.getHeaderField("X-Rate-Limit-Limit"));
int rateLimitRemaining = Integer.parseInt(conn.getHeaderField("X-Rate-Limit-Remaining"));
int rateLimitReset = Integer.parseInt(conn.getHeaderField("X-Rate-Limit-Reset"));
-
+
return new Response(resp, rateLimit, rateLimitRemaining, rateLimitReset);
} finally {
conn.disconnect();
@@ -116,11 +125,10 @@ public abstract class AbstractRequester implements Requester {
throw new IOException("Failed to fetch response");
}
IOUtils.copy(is, writer, Charsets.UTF_8);
-
+
JsonParser parser = new JsonParser();
return parser.parse(writer.toString());
}
-
/**
* Prepare the request before it gets send.