From ee17ca3b97091ba6ded8e15e57f67998d63bc7cd Mon Sep 17 00:00:00 2001 From: Paul Walsh Date: Mon, 3 Sep 2012 08:29:30 +0100 Subject: [PATCH] Modified to use GZip --- .../org/scribe/builder/ServiceBuilder.java | 1 + .../exceptions/OAuthConnectionException.java | 1 + .../java/org/scribe/model/OAuthRequest.java | 102 ++- src/main/java/org/scribe/model/Parameter.java | 79 +-- src/main/java/org/scribe/model/Request.java | 663 +++++++++--------- src/main/java/org/scribe/model/Response.java | 206 +++--- .../services/HMACSha1SignatureService.java | 82 +-- 7 files changed, 556 insertions(+), 578 deletions(-) diff --git a/src/main/java/org/scribe/builder/ServiceBuilder.java b/src/main/java/org/scribe/builder/ServiceBuilder.java index 27f3c8f63..fd841adf9 100644 --- a/src/main/java/org/scribe/builder/ServiceBuilder.java +++ b/src/main/java/org/scribe/builder/ServiceBuilder.java @@ -1,6 +1,7 @@ package org.scribe.builder; import java.io.*; + import org.scribe.builder.api.*; import org.scribe.exceptions.*; import org.scribe.model.*; diff --git a/src/main/java/org/scribe/exceptions/OAuthConnectionException.java b/src/main/java/org/scribe/exceptions/OAuthConnectionException.java index 918de810c..348a3ae19 100644 --- a/src/main/java/org/scribe/exceptions/OAuthConnectionException.java +++ b/src/main/java/org/scribe/exceptions/OAuthConnectionException.java @@ -3,6 +3,7 @@ /** * @author: Pablo Fernandez */ +@SuppressWarnings("serial") public class OAuthConnectionException extends OAuthException { private static final String MSG = "There was a problem while creating a connection to the remote service."; diff --git a/src/main/java/org/scribe/model/OAuthRequest.java b/src/main/java/org/scribe/model/OAuthRequest.java index 43892278f..9bd0c2c5b 100644 --- a/src/main/java/org/scribe/model/OAuthRequest.java +++ b/src/main/java/org/scribe/model/OAuthRequest.java @@ -5,65 +5,61 @@ /** * The representation of an OAuth HttpRequest. * - * Adds OAuth-related functionality to the {@link Request} + * Adds OAuth-related functionality to the {@link Request} * * @author Pablo Fernandez */ -public class OAuthRequest extends Request -{ - private static final String OAUTH_PREFIX = "oauth_"; - private Map oauthParameters; +public class OAuthRequest extends Request { + private static final String OAUTH_PREFIX = "oauth_"; + private Map oauthParameters; - /** - * Default constructor. - * - * @param verb Http verb/method - * @param url resource URL - */ - public OAuthRequest(Verb verb, String url) - { - super(verb, url); - this.oauthParameters = new HashMap(); - } + /** + * Default constructor. + * + * @param verb + * Http verb/method + * @param url + * resource URL + */ + public OAuthRequest(Verb verb, String url) { + super(verb, url); + this.oauthParameters = new HashMap(); + } - /** - * Adds an OAuth parameter. - * - * @param key name of the parameter - * @param value value of the parameter - * - * @throws IllegalArgumentException if the parameter is not an OAuth parameter - */ - public void addOAuthParameter(String key, String value) - { - oauthParameters.put(checkKey(key), value); - } + /** + * Adds an OAuth parameter. + * + * @param key + * name of the parameter + * @param value + * value of the parameter + * + * @throws IllegalArgumentException + * if the parameter is not an OAuth parameter + */ + public void addOAuthParameter(String key, String value) { + oauthParameters.put(checkKey(key), value); + } - private String checkKey(String key) - { - if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) - { - return key; - } - else - { - throw new IllegalArgumentException(String.format("OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX)); - } - } + private String checkKey(String key) { + if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) { + return key; + } else { + throw new IllegalArgumentException(String.format("OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX)); + } + } - /** - * Returns the {@link Map} containing the key-value pair of parameters. - * - * @return parameters as map - */ - public Map getOauthParameters() - { - return oauthParameters; - } + /** + * Returns the {@link Map} containing the key-value pair of parameters. + * + * @return parameters as map + */ + public Map getOauthParameters() { + return oauthParameters; + } - @Override - public String toString() - { - return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl()); - } + @Override + public String toString() { + return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl()); + } } diff --git a/src/main/java/org/scribe/model/Parameter.java b/src/main/java/org/scribe/model/Parameter.java index 9fe610b43..5b85c1818 100644 --- a/src/main/java/org/scribe/model/Parameter.java +++ b/src/main/java/org/scribe/model/Parameter.java @@ -1,50 +1,45 @@ package org.scribe.model; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import org.scribe.exceptions.OAuthException; import org.scribe.utils.OAuthEncoder; /** * @author: Pablo Fernandez */ -public class Parameter implements Comparable -{ - private static final String UTF = "UTF8"; - - private final String key; - private final String value; - - public Parameter(String key, String value) - { - this.key = key; - this.value = value; - } - - public String asUrlEncodedPair() - { - return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value)); - } - - public boolean equals(Object other) - { - if(other == null) return false; - if(other == this) return true; - if(!(other instanceof Parameter)) return false; - - Parameter otherParam = (Parameter) other; - return otherParam.key.equals(key) && otherParam.value.equals(value); - } - - public int hashCode() - { - return key.hashCode() + value.hashCode(); - } - - public int compareTo(Parameter parameter) - { - int keyDiff = key.compareTo(parameter.key); - - return keyDiff != 0 ? keyDiff : value.compareTo(parameter.value); - } +public class Parameter implements Comparable { + @SuppressWarnings("unused") + private static final String UTF = "UTF8"; + + private final String key; + private final String value; + + public Parameter(String key, String value) { + this.key = key; + this.value = value; + } + + public String asUrlEncodedPair() { + return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value)); + } + + public boolean equals(Object other) { + if (other == null) + return false; + if (other == this) + return true; + if (!(other instanceof Parameter)) + return false; + + Parameter otherParam = (Parameter) other; + return otherParam.key.equals(key) && otherParam.value.equals(value); + } + + public int hashCode() { + return key.hashCode() + value.hashCode(); + } + + public int compareTo(Parameter parameter) { + int keyDiff = key.compareTo(parameter.key); + + return keyDiff != 0 ? keyDiff : value.compareTo(parameter.value); + } } diff --git a/src/main/java/org/scribe/model/Request.java b/src/main/java/org/scribe/model/Request.java index 81db94eac..76a5733b0 100644 --- a/src/main/java/org/scribe/model/Request.java +++ b/src/main/java/org/scribe/model/Request.java @@ -13,346 +13,325 @@ * * @author Pablo Fernandez */ -class Request -{ - private static final String CONTENT_LENGTH = "Content-Length"; - private static final String CONTENT_TYPE = "Content-Type"; - public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded"; - - private String url; - private Verb verb; - private ParameterList querystringParams; - private ParameterList bodyParams; - private Map headers; - private String payload = null; - private HttpURLConnection connection; - private String charset; - private byte[] bytePayload = null; - private boolean connectionKeepAlive = false; - private Long connectTimeout = null; - private Long readTimeout = null; - - /** - * Creates a new Http Request - * - * @param verb Http Verb (GET, POST, etc) - * @param url url with optional querystring parameters. - */ - public Request(Verb verb, String url) - { - this.verb = verb; - this.url = url; - this.querystringParams = new ParameterList(); - this.bodyParams = new ParameterList(); - this.headers = new HashMap(); - } - - /** - * Execute the request and return a {@link Response} - * - * @return Http Response - * @throws RuntimeException - * if the connection cannot be created. - */ - public Response send() - { - try - { - createConnection(); - return doSend(); - } - catch (Exception e) - { - throw new OAuthConnectionException(e); - } - } - - private void createConnection() throws IOException - { - String completeUrl = getCompleteUrl(); - if (connection == null) - { - System.setProperty("http.keepAlive", connectionKeepAlive ? "true" : "false"); - connection = (HttpURLConnection) new URL(completeUrl).openConnection(); - } - } - - /** - * Returns the complete url (host + resource + encoded querystring parameters). - * - * @return the complete url. - */ - public String getCompleteUrl() - { - return querystringParams.appendTo(url); - } - - Response doSend() throws IOException - { - connection.setRequestMethod(this.verb.name()); - if (connectTimeout != null) - { - connection.setConnectTimeout(connectTimeout.intValue()); - } - if (readTimeout != null) - { - connection.setReadTimeout(readTimeout.intValue()); - } - addHeaders(connection); - if (verb.equals(Verb.PUT) || verb.equals(Verb.POST)) - { - addBody(connection, getByteBodyContents()); - } - return new Response(connection); - } - - void addHeaders(HttpURLConnection conn) - { - for (String key : headers.keySet()) - conn.setRequestProperty(key, headers.get(key)); - } - - void addBody(HttpURLConnection conn, byte[] content) throws IOException - { - conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length)); - - // Set default content type if none is set. - if (conn.getRequestProperty(CONTENT_TYPE) == null) - { - conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); - } - conn.setDoOutput(true); - conn.getOutputStream().write(content); - } - - /** - * Add an HTTP Header to the Request - * - * @param key the header name - * @param value the header value - */ - public void addHeader(String key, String value) - { - this.headers.put(key, value); - } - - /** - * Add a body Parameter (for POST/ PUT Requests) - * - * @param key the parameter name - * @param value the parameter value - */ - public void addBodyParameter(String key, String value) - { - this.bodyParams.add(key, value); - } - - /** - * Add a QueryString parameter - * - * @param key the parameter name - * @param value the parameter value - */ - public void addQuerystringParameter(String key, String value) - { - this.querystringParams.add(key, value); - } - - /** - * Add body payload. - * - * This method is used when the HTTP body is not a form-url-encoded string, - * but another thing. Like for example XML. - * - * Note: The contents are not part of the OAuth signature - * - * @param payload the body of the request - */ - public void addPayload(String payload) - { - this.payload = payload; - } - - /** - * Overloaded version for byte arrays - * - * @param payload - */ - public void addPayload(byte[] payload) - { - this.bytePayload = payload; - } - - /** - * Get a {@link ParameterList} with the query string parameters. - * - * @return a {@link ParameterList} containing the query string parameters. - * @throws OAuthException if the request URL is not valid. - */ - public ParameterList getQueryStringParams() - { - try - { - ParameterList result = new ParameterList(); - String queryString = new URL(url).getQuery(); - result.addQuerystring(queryString); - result.addAll(querystringParams); - return result; - } - catch (MalformedURLException mue) - { - throw new OAuthException("Malformed URL", mue); - } - } - - /** - * Obtains a {@link ParameterList} of the body parameters. - * - * @return a {@link ParameterList}containing the body parameters. - */ - public ParameterList getBodyParams() - { - return bodyParams; - } - - /** - * Obtains the URL of the HTTP Request. - * - * @return the original URL of the HTTP Request - */ - public String getUrl() - { - return url; - } - - /** - * Returns the URL without the port and the query string part. - * - * @return the OAuth-sanitized URL - */ - public String getSanitizedUrl() - { - return url.replaceAll("\\?.*", "").replace("\\:\\d{4}", ""); - } - - /** - * Returns the body of the request - * - * @return form encoded string - * @throws OAuthException if the charset chosen is not supported - */ - public String getBodyContents() - { - try - { - return new String(getByteBodyContents(),getCharset()); - } - catch(UnsupportedEncodingException uee) - { - throw new OAuthException("Unsupported Charset: "+charset, uee); - } - } - - byte[] getByteBodyContents() - { - if (bytePayload != null) return bytePayload; - String body = (payload != null) ? payload : bodyParams.asFormUrlEncodedString(); - try - { - return body.getBytes(getCharset()); - } - catch(UnsupportedEncodingException uee) - { - throw new OAuthException("Unsupported Charset: "+getCharset(), uee); - } - } - - /** - * Returns the HTTP Verb - * - * @return the verb - */ - public Verb getVerb() - { - return verb; - } - - /** - * Returns the connection headers as a {@link Map} - * - * @return map of headers - */ - public Map getHeaders() - { - return headers; - } - - /** - * Returns the connection charset. Defaults to {@link Charset} defaultCharset if not set - * - * @return charset - */ - public String getCharset() - { - return charset == null ? Charset.defaultCharset().name() : charset; - } - - /** - * Sets the connect timeout for the underlying {@link HttpURLConnection} - * - * @param duration duration of the timeout - * - * @param unit unit of time (milliseconds, seconds, etc) - */ - public void setConnectTimeout(int duration, TimeUnit unit) - { - this.connectTimeout = unit.toMillis(duration); - } - - /** - * Sets the read timeout for the underlying {@link HttpURLConnection} - * - * @param duration duration of the timeout - * - * @param unit unit of time (milliseconds, seconds, etc) - */ - public void setReadTimeout(int duration, TimeUnit unit) - { - this.readTimeout = unit.toMillis(duration); - } - - /** - * Set the charset of the body of the request - * - * @param charsetName name of the charset of the request - */ - public void setCharset(String charsetName) - { - this.charset = charsetName; - } - - /** - * Sets whether the underlying Http Connection is persistent or not. - * - * @see http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html - * @param connectionKeepAlive - */ - public void setConnectionKeepAlive(boolean connectionKeepAlive) - { - this.connectionKeepAlive = connectionKeepAlive; - } - - /* - * We need this in order to stub the connection object for test cases - */ - void setConnection(HttpURLConnection connection) - { - this.connection = connection; - } - - @Override - public String toString() - { - return String.format("@Request(%s %s)", getVerb(), getUrl()); - } +class Request { + private static final String CONTENT_LENGTH = "Content-Length"; + private static final String CONTENT_TYPE = "Content-Type"; + public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded"; + + private String url; + private Verb verb; + private ParameterList querystringParams; + private ParameterList bodyParams; + private Map headers; + private String payload = null; + private HttpURLConnection connection; + private String charset; + private byte[] bytePayload = null; + private boolean connectionKeepAlive = false; + private Long connectTimeout = null; + private Long readTimeout = null; + + /** + * Creates a new Http Request + * + * @param verb + * Http Verb (GET, POST, etc) + * @param url + * url with optional querystring parameters. + */ + public Request(Verb verb, String url) { + this.verb = verb; + this.url = url; + this.querystringParams = new ParameterList(); + this.bodyParams = new ParameterList(); + this.headers = new HashMap(); + + addHeader("Accept-Encoding", "gzip"); + } + + /** + * Execute the request and return a {@link Response} + * + * @return Http Response + * @throws RuntimeException + * if the connection cannot be created. + */ + public Response send() { + try { + createConnection(); + return doSend(); + } catch (Exception e) { + throw new OAuthConnectionException(e); + } + } + + private void createConnection() throws IOException { + String completeUrl = getCompleteUrl(); + if (connection == null) { + System.setProperty("http.keepAlive", connectionKeepAlive ? "true" : "false"); + connection = (HttpURLConnection) new URL(completeUrl).openConnection(); + } + } + + /** + * Returns the complete url (host + resource + encoded querystring + * parameters). + * + * @return the complete url. + */ + public String getCompleteUrl() { + return querystringParams.appendTo(url); + } + + Response doSend() throws IOException { + connection.setRequestMethod(this.verb.name()); + if (connectTimeout != null) { + connection.setConnectTimeout(connectTimeout.intValue()); + } + if (readTimeout != null) { + connection.setReadTimeout(readTimeout.intValue()); + } + addHeaders(connection); + if (verb.equals(Verb.PUT) || verb.equals(Verb.POST)) { + addBody(connection, getByteBodyContents()); + } + return new Response(connection); + } + + void addHeaders(HttpURLConnection conn) { + for (String key : headers.keySet()) + conn.setRequestProperty(key, headers.get(key)); + } + + void addBody(HttpURLConnection conn, byte[] content) throws IOException { + conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length)); + + // Set default content type if none is set. + if (conn.getRequestProperty(CONTENT_TYPE) == null) { + conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); + } + conn.setDoOutput(true); + conn.getOutputStream().write(content); + } + + /** + * Add an HTTP Header to the Request + * + * @param key + * the header name + * @param value + * the header value + */ + public void addHeader(String key, String value) { + this.headers.put(key, value); + } + + /** + * Add a body Parameter (for POST/ PUT Requests) + * + * @param key + * the parameter name + * @param value + * the parameter value + */ + public void addBodyParameter(String key, String value) { + this.bodyParams.add(key, value); + } + + /** + * Add a QueryString parameter + * + * @param key + * the parameter name + * @param value + * the parameter value + */ + public void addQuerystringParameter(String key, String value) { + this.querystringParams.add(key, value); + } + + /** + * Add body payload. + * + * This method is used when the HTTP body is not a form-url-encoded string, + * but another thing. Like for example XML. + * + * Note: The contents are not part of the OAuth signature + * + * @param payload + * the body of the request + */ + public void addPayload(String payload) { + this.payload = payload; + } + + /** + * Overloaded version for byte arrays + * + * @param payload + */ + public void addPayload(byte[] payload) { + this.bytePayload = payload; + } + + /** + * Get a {@link ParameterList} with the query string parameters. + * + * @return a {@link ParameterList} containing the query string parameters. + * @throws OAuthException + * if the request URL is not valid. + */ + public ParameterList getQueryStringParams() { + try { + ParameterList result = new ParameterList(); + String queryString = new URL(url).getQuery(); + result.addQuerystring(queryString); + result.addAll(querystringParams); + return result; + } catch (MalformedURLException mue) { + throw new OAuthException("Malformed URL", mue); + } + } + + /** + * Obtains a {@link ParameterList} of the body parameters. + * + * @return a {@link ParameterList}containing the body parameters. + */ + public ParameterList getBodyParams() { + return bodyParams; + } + + /** + * Obtains the URL of the HTTP Request. + * + * @return the original URL of the HTTP Request + */ + public String getUrl() { + return url; + } + + /** + * Returns the URL without the port and the query string part. + * + * @return the OAuth-sanitized URL + */ + public String getSanitizedUrl() { + return url.replaceAll("\\?.*", "").replace("\\:\\d{4}", ""); + } + + /** + * Returns the body of the request + * + * @return form encoded string + * @throws OAuthException + * if the charset chosen is not supported + */ + public String getBodyContents() { + try { + return new String(getByteBodyContents(), getCharset()); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Unsupported Charset: " + charset, uee); + } + } + + byte[] getByteBodyContents() { + if (bytePayload != null) + return bytePayload; + String body = (payload != null) ? payload : bodyParams.asFormUrlEncodedString(); + try { + return body.getBytes(getCharset()); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Unsupported Charset: " + getCharset(), uee); + } + } + + /** + * Returns the HTTP Verb + * + * @return the verb + */ + public Verb getVerb() { + return verb; + } + + /** + * Returns the connection headers as a {@link Map} + * + * @return map of headers + */ + public Map getHeaders() { + return headers; + } + + /** + * Returns the connection charset. Defaults to {@link Charset} + * defaultCharset if not set + * + * @return charset + */ + public String getCharset() { + return charset == null ? Charset.defaultCharset().name() : charset; + } + + /** + * Sets the connect timeout for the underlying {@link HttpURLConnection} + * + * @param duration + * duration of the timeout + * + * @param unit + * unit of time (milliseconds, seconds, etc) + */ + public void setConnectTimeout(int duration, TimeUnit unit) { + this.connectTimeout = unit.toMillis(duration); + } + + /** + * Sets the read timeout for the underlying {@link HttpURLConnection} + * + * @param duration + * duration of the timeout + * + * @param unit + * unit of time (milliseconds, seconds, etc) + */ + public void setReadTimeout(int duration, TimeUnit unit) { + this.readTimeout = unit.toMillis(duration); + } + + /** + * Set the charset of the body of the request + * + * @param charsetName + * name of the charset of the request + */ + public void setCharset(String charsetName) { + this.charset = charsetName; + } + + /** + * Sets whether the underlying Http Connection is persistent or not. + * + * @see http + * ://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive + * .html + * @param connectionKeepAlive + */ + public void setConnectionKeepAlive(boolean connectionKeepAlive) { + this.connectionKeepAlive = connectionKeepAlive; + } + + /* + * We need this in order to stub the connection object for test cases + */ + void setConnection(HttpURLConnection connection) { + this.connection = connection; + } + + @Override + public String toString() { + return String.format("@Request(%s %s)", getVerb(), getUrl()); + } + } diff --git a/src/main/java/org/scribe/model/Response.java b/src/main/java/org/scribe/model/Response.java index 9835a05a6..bf2107012 100644 --- a/src/main/java/org/scribe/model/Response.java +++ b/src/main/java/org/scribe/model/Response.java @@ -3,6 +3,7 @@ import java.io.*; import java.net.*; import java.util.*; +import java.util.zip.GZIPInputStream; import org.scribe.exceptions.*; import org.scribe.utils.*; @@ -12,102 +13,113 @@ * * @author Pablo Fernandez */ -public class Response -{ - private static final String EMPTY = ""; - - private int code; - private String body; - private InputStream stream; - private Map headers; - - Response(HttpURLConnection connection) throws IOException - { - try - { - connection.connect(); - code = connection.getResponseCode(); - headers = parseHeaders(connection); - stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream(); - } - catch (UnknownHostException e) - { - throw new OAuthException("The IP address of a host could not be determined.", e); - } - } - - private String parseBodyContents() - { - body = StreamUtils.getStreamContents(getStream()); - return body; - } - - private Map parseHeaders(HttpURLConnection conn) - { - Map headers = new HashMap(); - for (String key : conn.getHeaderFields().keySet()) - { - headers.put(key, conn.getHeaderFields().get(key).get(0)); - } - return headers; - } - - public boolean isSuccessful() - { - return getCode() >= 200 && getCode() < 400; - } - - /** - * Obtains the HTTP Response body - * - * @return response body - */ - public String getBody() - { - return body != null ? body : parseBodyContents(); - } - - /** - * Obtains the meaningful stream of the HttpUrlConnection, either inputStream - * or errorInputStream, depending on the status code - * - * @return input stream / error stream - */ - public InputStream getStream() - { - return stream; - } - - /** - * Obtains the HTTP status code - * - * @return the status code - */ - public int getCode() - { - return code; - } - - /** - * Obtains a {@link Map} containing the HTTP Response Headers - * - * @return headers - */ - public Map getHeaders() - { - return headers; - } - - /** - * Obtains a single HTTP Header value, or null if undefined - * - * @param name the header name. - * - * @return header value or null. - */ - public String getHeader(String name) - { - return headers.get(name); - } +public class Response { + @SuppressWarnings("unused") + private static final String EMPTY = ""; + + private int code; + private String body; + private InputStream stream; + private Map headers; + + Response(HttpURLConnection connection) throws IOException { + try { + connection.connect(); + code = connection.getResponseCode(); + headers = parseHeaders(connection); + + if (isGZipped(headers)) + stream = isSuccessful() ? new GZIPInputStream(connection.getInputStream()) : connection.getErrorStream(); + else + stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream(); + + } catch (UnknownHostException e) { + throw new OAuthException("The IP address of a host could not be determined.", e); + } + } + + private boolean isGZipped(Map headers) { + + try { + + String gzipKey = "Content-Encoding"; + String gzipValue = "gzip"; + + if (headers.containsKey(gzipKey) && headers.get(gzipKey).equalsIgnoreCase(gzipValue)) + return true; + + } catch (Exception e) { + e.printStackTrace(); + } + + return false; + + } + + private String parseBodyContents() { + body = StreamUtils.getStreamContents(getStream()); + return body; + } + + private Map parseHeaders(HttpURLConnection conn) { + Map headers = new HashMap(); + for (String key : conn.getHeaderFields().keySet()) { + headers.put(key, conn.getHeaderFields().get(key).get(0)); + } + return headers; + } + + public boolean isSuccessful() { + return getCode() >= 200 && getCode() < 400; + } + + /** + * Obtains the HTTP Response body + * + * @return response body + */ + public String getBody() { + return body != null ? body : parseBodyContents(); + } + + /** + * Obtains the meaningful stream of the HttpUrlConnection, either + * inputStream or errorInputStream, depending on the status code + * + * @return input stream / error stream + */ + public InputStream getStream() { + return stream; + } + + /** + * Obtains the HTTP status code + * + * @return the status code + */ + public int getCode() { + return code; + } + + /** + * Obtains a {@link Map} containing the HTTP Response Headers + * + * @return headers + */ + public Map getHeaders() { + return headers; + } + + /** + * Obtains a single HTTP Header value, or null if undefined + * + * @param name + * the header name. + * + * @return header value or null. + */ + public String getHeader(String name) { + return headers.get(name); + } } \ No newline at end of file diff --git a/src/main/java/org/scribe/services/HMACSha1SignatureService.java b/src/main/java/org/scribe/services/HMACSha1SignatureService.java index cadda6812..15fb29ea8 100644 --- a/src/main/java/org/scribe/services/HMACSha1SignatureService.java +++ b/src/main/java/org/scribe/services/HMACSha1SignatureService.java @@ -1,57 +1,51 @@ package org.scribe.services; -import javax.crypto.*; -import javax.crypto.spec.*; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; -import org.apache.commons.codec.binary.*; -import org.scribe.exceptions.*; -import org.scribe.utils.*; +import org.apache.commons.codec.binary.Base64; +import org.scribe.exceptions.OAuthSignatureException; +import org.scribe.utils.OAuthEncoder; +import org.scribe.utils.Preconditions; /** * HMAC-SHA1 implementation of {@SignatureService} * * @author Pablo Fernandez - * + * */ -public class HMACSha1SignatureService implements SignatureService -{ - private static final String EMPTY_STRING = ""; - private static final String CARRIAGE_RETURN = "\r\n"; - private static final String UTF8 = "UTF-8"; - private static final String HMAC_SHA1 = "HmacSHA1"; - private static final String METHOD = "HMAC-SHA1"; +public class HMACSha1SignatureService implements SignatureService { + private static final String EMPTY_STRING = ""; + private static final String CARRIAGE_RETURN = "\r\n"; + private static final String UTF8 = "UTF-8"; + private static final String HMAC_SHA1 = "HmacSHA1"; + private static final String METHOD = "HMAC-SHA1"; - /** - * {@inheritDoc} - */ - public String getSignature(String baseString, String apiSecret, String tokenSecret) - { - try - { - Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); - Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); - return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret)); - } - catch (Exception e) - { - throw new OAuthSignatureException(baseString, e); - } - } + /** + * {@inheritDoc} + */ + public String getSignature(String baseString, String apiSecret, String tokenSecret) { + try { + Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); + Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); + return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret)); + } catch (Exception e) { + throw new OAuthSignatureException(baseString, e); + } + } - private String doSign(String toSign, String keyString) throws Exception - { - SecretKeySpec key = new SecretKeySpec((keyString).getBytes(UTF8), HMAC_SHA1); - Mac mac = Mac.getInstance(HMAC_SHA1); - mac.init(key); - byte[] bytes = mac.doFinal(toSign.getBytes(UTF8)); - return new String(Base64.encodeBase64(bytes)).replace(CARRIAGE_RETURN, EMPTY_STRING); - } + private String doSign(String toSign, String keyString) throws Exception { + SecretKeySpec key = new SecretKeySpec((keyString).getBytes(UTF8), HMAC_SHA1); + Mac mac = Mac.getInstance(HMAC_SHA1); + mac.init(key); + byte[] bytes = mac.doFinal(toSign.getBytes(UTF8)); + return new String(Base64.encodeBase64(bytes)).replace(CARRIAGE_RETURN, EMPTY_STRING); + } - /** - * {@inheritDoc} - */ - public String getSignatureMethod() - { - return METHOD; - } + /** + * {@inheritDoc} + */ + public String getSignatureMethod() { + return METHOD; + } }