Skip to content

Commit

Permalink
Refactor/clean up OAuth and REST method work
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy-livefront committed Feb 6, 2012
1 parent 26a555f commit e0e7296
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 189 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,19 @@
import com.jeremyhaberman.restfulandroid.rest.RestMethodFactory.Method;
import com.jeremyhaberman.restfulandroid.rest.resource.Profile;
import com.jeremyhaberman.restfulandroid.security.AuthorizationManager;
import com.jeremyhaberman.restfulandroid.security.RequestSigner;

public class GetProfileRestMethod extends AbstractRestMethod<Profile>{

private static final URI PROFILE_URI = URI.create("https://api.twitter.com/1/account/verify_credentials.json");

public GetProfileRestMethod(){

}

@Override
protected Request buildRequest() {

AuthorizationManager authManager = AuthorizationManager.getInstance();
Request request = new Request(Method.GET, PROFILE_URI, null, null);
authManager.signRequest(request);

RequestSigner signer = AuthorizationManager.getInstance();
signer.authorize(request);

return request;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected Request buildRequest() {

AuthorizationManager authManager = AuthorizationManager.getInstance();
Request request = new Request(Method.GET, TIMELINE_URI, headers, null);
authManager.signRequest(request);
authManager.authorize(request);

return request;
}
Expand Down
7 changes: 3 additions & 4 deletions src/com/jeremyhaberman/restfulandroid/rest/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,12 @@ public byte[] getBody() {
return body;
}

public void setAuthorizationHeader(String value) {
List<String> authValue = new ArrayList<String>();
authValue.add(value);
public void addHeader(String key, List<String> value) {

if (headers == null) {
headers = new HashMap<String, List<String>>();
}
headers.put("Authorization", authValue);
headers.put(key, value);
}


Expand Down
123 changes: 24 additions & 99 deletions src/com/jeremyhaberman/restfulandroid/rest/RestClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,103 +6,15 @@
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.jeremyhaberman.restfulandroid.rest.RestMethodFactory.Method;

public class RestClient {

// public Response get(URL uri, Map<String, List<String>> headers) {
// GET get = new GET(uri, headers);
// return getOrPost(get);
// }
//
// public Response post(URL uri, Map<String, List<String>> headers, byte[]
// body) {
// POST post = new POST(uri, headers, body);
// return getOrPost(post);
// }
//
// private Response getOrPost(Request request) {
//
// HttpURLConnection conn = null;
// Response response = null;
// try {
// conn = (HttpURLConnection) request.uri.openConnection();
// if (request.headers != null) {
// for (String header : request.headers.keySet()) {
// for (String value : request.headers.get(header)) {
// conn.addRequestProperty(header, value);
// }
// }
// }
// if (request instanceof POST) {
// byte[] payload = ((POST) request).body;
// conn.setDoOutput(true);
// conn.setFixedLengthStreamingMode(payload.length);
// conn.getOutputStream().write(payload);
// int status = conn.getResponseCode();
// if (status / 100 != 2)
// response = new Response(status, new Hashtable<String, List<String>>(),
// conn.getResponseMessage().getBytes());
// }
// if (response == null) {
// BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
// byte[] body = readStream(in);
// response = new Response(conn.getResponseCode(), conn.getHeaderFields(),
// body);
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (conn != null)
// conn.disconnect();
// }
// return response;
// }

// private class Request {
// public URL uri;
// public Map<String, List<String>> headers;
// public Method method;
// public Request(URL uri, Map<String, List<String>> headers) {
// this.uri = uri; this.headers = headers;
// }
// }
// private class POST extends Request {
// public byte[] body;
// public POST(URL uri, Map<String, List<String>> headers, byte[] body) {
// super(uri, headers);
// this.body = body;
// this.method = Method.POST;
// }
// }
// private class GET extends Request {
// public GET(URL uri, Map<String, List<String>> headers) {
// super(uri, headers);
// }
// }

// utilities
private static byte[] readStream(InputStream in) throws IOException {
byte[] buf = new byte[1024];
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
while ((count = in.read(buf)) != -1)
out.write(buf, 0, count);
return out.toByteArray();
}

public Response execute(Request request) {
HttpURLConnection conn = null;
Response response = null;
try {

URL url = request.getRequestUri().toURL();

conn = (HttpURLConnection) url.openConnection();
if (request.getHeaders() != null) {
for (String header : request.getHeaders().keySet()) {
Expand All @@ -111,26 +23,30 @@ public Response execute(Request request) {
}
}
}
if (request.getMethod() == Method.GET) {

int status = -1;
switch (request.getMethod()) {
case GET:
conn.setDoOutput(false);
int status = conn.getResponseCode();
if (status / 100 != 2)
response = new Response(status, new Hashtable<String, List<String>>(), conn
.getResponseMessage().getBytes());
} else if (request.getMethod() == Method.POST) {
break;
case POST:
byte[] payload = request.getBody();
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(payload.length);
conn.getOutputStream().write(payload);
int status = conn.getResponseCode();
if (status / 100 != 2)
response = new Response(status, new Hashtable<String, List<String>>(), conn
.getResponseMessage().getBytes());
status = conn.getResponseCode();
default:
break;
}
if (response == null) {

status = conn.getResponseCode();

if (conn.getContentLength() > 0) {
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
byte[] body = readStream(in);
response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
} else {
response = new Response(status, conn.getHeaderFields(), new byte[] {});
}

} catch (IOException e) {
Expand All @@ -141,4 +57,13 @@ public Response execute(Request request) {
}
return response;
}

private static byte[] readStream(InputStream in) throws IOException {
byte[] buf = new byte[1024];
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
while ((count = in.read(buf)) != -1)
out.write(buf, 0, count);
return out.toByteArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,23 @@
* Facade representing the Twitter Timeline data
*
* @author hashbrown
*
*
*/
public class TwitterTimeline implements Resource{

private static final Uri CONTENT_URI = Uri.parse("content://" + ProfileConstants.AUTHORITY + "/" + ProfileConstants.TIMELINE_TABLE_NAME);

public class TwitterTimeline implements Resource {

private static final Uri CONTENT_URI = Uri.parse("content://" + ProfileConstants.AUTHORITY
+ "/" + ProfileConstants.TIMELINE_TABLE_NAME);

private JSONObject timelineData;

public TwitterTimeline(JSONObject timelineData) {
this.timelineData = timelineData;
}
public List<Tweet> getTweets(){
//TODO

public List<Tweet> getTweets() {
// TODO

return Collections.emptyList();
}



}
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package com.jeremyhaberman.restfulandroid.security;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
Expand Down Expand Up @@ -233,27 +232,6 @@ public boolean loggedIn() {
return getAccessToken() != null;
}

/**
* Signs a request
*
* @param request
* the OAuthRequest to sign
*/
public void signRequest(OAuthRequest request) {
mOAuthService.signRequest(getAccessToken(), request);
}

/**
* Signs an HttpUrlConnection
*
* @param conn
* the HttpURLConnectionto sign
*/
@Override
public void signConnection(HttpURLConnection conn) {
// TODO Jeremy implementing this
}

/**
* Log out of the application
*/
Expand All @@ -264,19 +242,14 @@ public void logout() {
saveAccessToken(mAccessToken);
}

public void signRequest(Request request) {

// These values need to be encoded into a single string which will be
// used later on. The process to build the string is very specific:

// 1. Percent encode every key and value that will be signed.
// 2. Sort the list of parameters alphabetically[1] by encoded key[2].
// 3. For each key/value pair:
// 4. Append the encoded key to the output string.
// 5. Append the '=' character to the output string.
// 6. Append the encoded value to the output string.
// 7. If there are more key/value pairs remaining, append a '&'
// character to the output string.
/**
* Authorizes a Twitter request.
*
* See <a href="https://dev.twitter.com/docs/auth/authorizing-request">
* Authorizing a Request</a> for authorization requirements and methods.
*/
@Override
public void authorize(Request request) {

Map<String, String> oauthParams = new HashMap<String, String>();

Expand All @@ -289,45 +262,44 @@ public void signRequest(Request request) {
oauthParams.put("oauth_token", getAccessToken().getToken());
oauthParams.put("oauth_version", "1.0");

// generating the signature

String verb = URLUtils.percentEncode(request.getMethod().name());
String url = URLUtils
.percentEncode(getSanitizedUrl(request.getRequestUri().toASCIIString()));
String params = getSortedAndEncodedParams(request, oauthParams);
String baseString = String.format(AMPERSAND_SEPARATED_STRING, verb, url, params);

// 3. oauth_signature tnnArxj06cWHq44gCs1OSKk/jLY=

String signature = mTwitterApi.getSignatureService().getSignature(baseString,
TWITTER_API_SECRET, getAccessToken().getSecret());

oauthParams.put("oauth_signature", signature);

String oauthHeaderValue = getAuthorizationHeaderValue(oauthParams);
List<String> oauthHeaderValue = getAuthorizationHeaderValue(oauthParams);

request.setAuthorizationHeader(oauthHeaderValue);
request.addHeader("Authorization", oauthHeaderValue);

}

private String getAuthorizationHeaderValue(Map<String, String> params) {
private List<String> getAuthorizationHeaderValue(Map<String, String> params) {

String authValue = "OAuth ";
String authValueString = "OAuth ";

int count = params.size();
int position = 1;

for (String key : params.keySet()) {
authValue += URLUtils.percentEncode(key);
authValue += '=';
authValue += '"';
authValue += URLUtils.percentEncode(params.get(key));
authValue += '"';
authValueString += URLUtils.percentEncode(key);
authValueString += '=';
authValueString += '"';
authValueString += URLUtils.percentEncode(params.get(key));
authValueString += '"';
if (position != count) {
authValue += ", ";
authValueString += ", ";
}
position++;
}

List<String> authValue = new ArrayList<String>();
authValue.add(authValueString);

return authValue;
}
Expand Down
Loading

0 comments on commit e0e7296

Please sign in to comment.