Skip to content

Instantly share code, notes, and snippets.

@dirkmc
Created March 25, 2011 16:29
Show Gist options
  • Save dirkmc/887137 to your computer and use it in GitHub Desktop.
Save dirkmc/887137 to your computer and use it in GitHub Desktop.
import org.scribe.extractors.UrlParameterExtractor;
// import ...
public class TwitterAuth extends Controller {
public static void signInWithTwitter() throws Exception {
Token requestToken = Twitter.getService().getRequestToken();
Cache.set(requestToken.getToken(), requestToken, "60min");
String authorizationUrl = Twitter.getService()
.getAuthorizationUrl(requestToken);
redirect(authorizationUrl);
}
public static void signInWithTwitterReturn(String oauth_token,
String oauth_verifier) throws Exception {
Verifier verifier = new Verifier(oauth_verifier);
Token requestToken = (Token) Cache.get(oauth_token);
Token accessToken = Twitter.getService().getAccessToken(requestToken,
verifier);
Map<String, String> params = UrlParameterExtractor.extract(accessToken.getRawResponse());
String token = accessToken.getToken();
String secret = accessToken.getSecret();
String screenName = params.get("screen_name");
Long userId = Long.parseLong(params.get("user_id"));
// Here you should save the token and secret in the database so you can use them later on.
// I use the TwitterAccount class (see below) to store Twitter related info, so I can pass
// it around easily when making API calls.
Application.index();
}
}
public class Twitter {
private static OAuthService service = null;
public static OAuthService getService() {
if (service == null) {
String callback = getCallback();
service = new ServiceBuilder().provider(TwitterApi.class).callback(
callback).apiKey(
(String) Play.configuration.get("twitter.consumerKey"))
.apiSecret(
(String) Play.configuration
.get("twitter.consumerSecret")).build();
}
return service;
}
private static String getCallback() {
String action = "auth.TwitterAuth.signInWithTwitterReturn";
if (Play.id.equals("test")) {
return "http://localhost:" + Play.configuration.get("http.port")
+ Router.reverse(action).toString();
}
return Router.getFullUrl(action);
}
public static void postMessage(TwitterAccount account, String message) {
try {
String url = "http://api.twitter.com/1/statuses/update.json";
OAuthRequest request = new OAuthRequest(Verb.POST, url);
request.addQuerystringParameter("status", message);
sendRequest(account, request);
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public static TwitterMessage getLastMessage(TwitterAccount account) {
try {
String url = "http://api.twitter.com/1/statuses/user_timeline.json";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("count", "1");
request.addQuerystringParameter("trim_user", "true");
Response response = sendRequest(account, request);
TwitterMessage[] message = new Gson().fromJson(response.getBody(),
TwitterMessage[].class);
if (message.length == 0) {
return null;
}
return message[0];
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public static void verifyCredentials(TwitterAccount account) {
String url = "http://api.twitter.com/1/account/verify_credentials.json";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
sendRequest(account, request);
}
private static Response sendRequest(TwitterAccount account,
OAuthRequest request) {
Token accessToken = new Token(account.token, account.secret);
getService().signRequest(accessToken, request);
Response response = request.send();
if (response.getCode() != Http.StatusCode.OK) {
throw new TwitterException(response.getCode(), response.getBody());
}
return response;
}
}
public class TwitterAccount extends Model {
public Long userId;
public String screenName;
public String secret;
public String token;
}
public class TwitterMessage {
public String text;
}
public class TwitterException extends RuntimeException {
private int code;
private String body;
public TwitterException(int code, String body) {
super(getMessage(code, body));
this.code = code;
this.body = body;
}
public static String getMessage(int code, String body) {
return "Bad response code from twitter: " + code + "\n" + body;
}
public String getMessage() {
return getMessage(code, body);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment