/src/main/java/com/devopstom/socallmemaybe/TwitterAuth.java
Java | 199 lines | 147 code | 37 blank | 15 comment | 13 complexity | e5343ff9b46bfb30ca7ab0efd5780dcd MD5 | raw file
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.devopstom.socallmemaybe;
- import com.google.gson.Gson;
- import com.mongodb.*;
- import java.awt.Desktop;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.URI;
- import java.net.URL;
- import java.net.UnknownHostException;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import twitter4j.auth.AccessToken;
- import java.util.Arrays;
- import java.util.logging.Level;
- import twitter4j.Twitter;
- import twitter4j.TwitterException;
- import twitter4j.TwitterFactory;
- import twitter4j.auth.RequestToken;
- /**
- *
- * @author tom
- */
- public class TwitterAuth {
- public static String twitterUsername = "";
- private static final Logger logger = LoggerFactory.getLogger(TwitterAuth.class);
- private static final String OauthConsumerKey = "hBAWCkpfcCFAgxIRQWDBA";
- private static final String OauthConsumerSecret = "3U9js9XQjauGWLSuew9OStGfAqlWhnVtHSrvCSgXhU";
- private DBCollection coll;
-
- public TwitterAuth() throws Exception{
- try {
- //MongoURI mURI = new MongoURI("mongodb://tom@twinhelix.org:m6t6AENbKG7B@linus.mongohq.com:10081/SoCallMeMaybe");
-
- Mongo mongoClient = new Mongo("linus.mongohq.com",10081);
-
- DB db = mongoClient.getDB( "SoCallMeMaybe" );
-
- char[] pass = new String("m6t6AENbKG7B").toCharArray();
-
- boolean auth = db.authenticate("serviceuser", pass);
- if (!auth){
- throw new Exception("Authentication failed");
- }
- coll = db.getCollection("TwitterAuth");
-
- } catch (MongoException ex) {
- logger.error(ex.getLocalizedMessage(), ex);
- } catch (UnknownHostException ex) {
- logger.error(ex.getLocalizedMessage(), ex);
- }
- }
- public static void openWebpageURI(URI uri) {
- Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
- if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
- try {
- desktop.browse(uri);
- } catch (Exception e) {
- logger.error(e.getLocalizedMessage(), e);
- e.printStackTrace();
- }
- }
- }
- public static void openWebpage(URL url) {
- try {
- openWebpageURI(url.toURI());
- } catch (Exception e) {
- logger.error(e.getLocalizedMessage(), e);
- e.printStackTrace();
- }
- }
-
- public boolean storeAccessToken(long userId, AccessToken accessToken){
- TwitterAccessDetail ad = new TwitterAccessDetail(userId,accessToken.getToken(),
- accessToken.getTokenSecret(),accessToken.getScreenName());
-
- String username = ad.getScreenName();
-
- Gson gson = new Gson();
- String jsonString = gson.toJson(ad);
- try {
- //mongo linus.mongohq.com:10081/SoCallMeMaybe -u <user> -p<password>
-
- BasicDBObject authToken = new BasicDBObject();
- authToken.append("username", username);
- authToken.append("TwitterAccessDetail",jsonString);
-
- coll.insert(authToken);
-
- //write converted json data to a file named "file.json"
- // FileWriter writer = new FileWriter(username + "_accessDetails.json");
- // writer.write(jsonString);
- // writer.close();
- return true;
-
- } catch (Exception e) {
- logger.error(e.getLocalizedMessage(), e);
- e.printStackTrace();
- return false;
- }
- }
-
- public boolean generateAndStoreNewTwitterToken(String username) throws TwitterException, Exception{
- try{
- TwitterFactory _factory = new TwitterFactory();
-
- Twitter _twitter = TwitterFactory.getSingleton();
- _twitter.setOAuthConsumer(OauthConsumerKey, OauthConsumerSecret);
- RequestToken requestToken = _twitter.getOAuthRequestToken();
- AccessToken accessToken = null;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- while (null == accessToken) {
- System.out.println("Open the following URL and grant access to your account:");
- URL authURL = new URL(requestToken.getAuthorizationURL());
- openWebpage(authURL);
- System.out.print("Enter the PIN:");
- String pin = br.readLine();
- try{
- if(pin.length() > 0){
- accessToken = _twitter.getOAuthAccessToken(requestToken, pin);
- }else{
- accessToken = _twitter.getOAuthAccessToken();
- }
- } catch (TwitterException te) {
- logger.error(te.getLocalizedMessage(), te);
- if(401 == te.getStatusCode()){
- System.out.println("Unable to get the access token.");
- }else{
- te.printStackTrace();
- }
- }
- }
- //persist to the accessToken for future reference.
- Boolean stored = storeAccessToken(_twitter.verifyCredentials().getId(),
- accessToken);
-
- if (stored){
- return true;
- }else{
- return false;
- }
- }catch (Exception ex){
- logger.error(ex.getLocalizedMessage(), ex);
- ex.printStackTrace();
- return false;
- }
- }
- public AccessToken loadAccessToken(String username){
- Gson gson = new Gson();
- BasicDBObject query = new BasicDBObject("username", username);
- DBCursor cursor = coll.find(query);
- DBObject result = null;
- try {
- if (cursor.count() == 0){
- generateAndStoreNewTwitterToken(username);
- return loadAccessToken(username);
- } else {
- while(cursor.hasNext()) {
- result = cursor.next();
- }
- cursor.close();
- TwitterAccessDetail obj = gson.fromJson((String)result.get("TwitterAccessDetail"),
- TwitterAccessDetail.class);
- return new AccessToken(obj.getKey(),obj.getSecret());
- }
- } catch (TwitterException te){
- logger.error(te.getLocalizedMessage(),te);
- return new AccessToken("","");
-
- } catch (Exception e) {
- logger.error(e.getLocalizedMessage(), e);
- e.printStackTrace();
- return new AccessToken("","");
- }
-
-
-
-
- }
-
- }
-