From 2b2a47a0086eab52b09e5425e75cafb488e51074 Mon Sep 17 00:00:00 2001 From: Maurice Laveaux Date: Thu, 22 May 2014 14:47:03 +0200 Subject: Updated the Requesters to throw RateLimitException. * The exception contains the reset timestamp in unix time. --- src/io/AbstractRequester.java | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'src/io/AbstractRequester.java') 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. -- cgit v1.2.1