PageRenderTime 110ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/devopstom/socallmemaybe/TwitterAuth.java

https://bitbucket.org/devopstom/socallmemaybe
Java | 199 lines | 147 code | 37 blank | 15 comment | 13 complexity | e5343ff9b46bfb30ca7ab0efd5780dcd MD5 | raw file
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.devopstom.socallmemaybe;
  6. import com.google.gson.Gson;
  7. import com.mongodb.*;
  8. import java.awt.Desktop;
  9. import java.io.BufferedReader;
  10. import java.io.InputStreamReader;
  11. import java.net.URI;
  12. import java.net.URL;
  13. import java.net.UnknownHostException;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. import twitter4j.auth.AccessToken;
  17. import java.util.Arrays;
  18. import java.util.logging.Level;
  19. import twitter4j.Twitter;
  20. import twitter4j.TwitterException;
  21. import twitter4j.TwitterFactory;
  22. import twitter4j.auth.RequestToken;
  23. /**
  24. *
  25. * @author tom
  26. */
  27. public class TwitterAuth {
  28. public static String twitterUsername = "";
  29. private static final Logger logger = LoggerFactory.getLogger(TwitterAuth.class);
  30. private static final String OauthConsumerKey = "hBAWCkpfcCFAgxIRQWDBA";
  31. private static final String OauthConsumerSecret = "3U9js9XQjauGWLSuew9OStGfAqlWhnVtHSrvCSgXhU";
  32. private DBCollection coll;
  33. public TwitterAuth() throws Exception{
  34. try {
  35. //MongoURI mURI = new MongoURI("mongodb://tom@twinhelix.org:m6t6AENbKG7B@linus.mongohq.com:10081/SoCallMeMaybe");
  36. Mongo mongoClient = new Mongo("linus.mongohq.com",10081);
  37. DB db = mongoClient.getDB( "SoCallMeMaybe" );
  38. char[] pass = new String("m6t6AENbKG7B").toCharArray();
  39. boolean auth = db.authenticate("serviceuser", pass);
  40. if (!auth){
  41. throw new Exception("Authentication failed");
  42. }
  43. coll = db.getCollection("TwitterAuth");
  44. } catch (MongoException ex) {
  45. logger.error(ex.getLocalizedMessage(), ex);
  46. } catch (UnknownHostException ex) {
  47. logger.error(ex.getLocalizedMessage(), ex);
  48. }
  49. }
  50. public static void openWebpageURI(URI uri) {
  51. Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
  52. if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
  53. try {
  54. desktop.browse(uri);
  55. } catch (Exception e) {
  56. logger.error(e.getLocalizedMessage(), e);
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. public static void openWebpage(URL url) {
  62. try {
  63. openWebpageURI(url.toURI());
  64. } catch (Exception e) {
  65. logger.error(e.getLocalizedMessage(), e);
  66. e.printStackTrace();
  67. }
  68. }
  69. public boolean storeAccessToken(long userId, AccessToken accessToken){
  70. TwitterAccessDetail ad = new TwitterAccessDetail(userId,accessToken.getToken(),
  71. accessToken.getTokenSecret(),accessToken.getScreenName());
  72. String username = ad.getScreenName();
  73. Gson gson = new Gson();
  74. String jsonString = gson.toJson(ad);
  75. try {
  76. //mongo linus.mongohq.com:10081/SoCallMeMaybe -u <user> -p<password>
  77. BasicDBObject authToken = new BasicDBObject();
  78. authToken.append("username", username);
  79. authToken.append("TwitterAccessDetail",jsonString);
  80. coll.insert(authToken);
  81. //write converted json data to a file named "file.json"
  82. // FileWriter writer = new FileWriter(username + "_accessDetails.json");
  83. // writer.write(jsonString);
  84. // writer.close();
  85. return true;
  86. } catch (Exception e) {
  87. logger.error(e.getLocalizedMessage(), e);
  88. e.printStackTrace();
  89. return false;
  90. }
  91. }
  92. public boolean generateAndStoreNewTwitterToken(String username) throws TwitterException, Exception{
  93. try{
  94. TwitterFactory _factory = new TwitterFactory();
  95. Twitter _twitter = TwitterFactory.getSingleton();
  96. _twitter.setOAuthConsumer(OauthConsumerKey, OauthConsumerSecret);
  97. RequestToken requestToken = _twitter.getOAuthRequestToken();
  98. AccessToken accessToken = null;
  99. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  100. while (null == accessToken) {
  101. System.out.println("Open the following URL and grant access to your account:");
  102. URL authURL = new URL(requestToken.getAuthorizationURL());
  103. openWebpage(authURL);
  104. System.out.print("Enter the PIN:");
  105. String pin = br.readLine();
  106. try{
  107. if(pin.length() > 0){
  108. accessToken = _twitter.getOAuthAccessToken(requestToken, pin);
  109. }else{
  110. accessToken = _twitter.getOAuthAccessToken();
  111. }
  112. } catch (TwitterException te) {
  113. logger.error(te.getLocalizedMessage(), te);
  114. if(401 == te.getStatusCode()){
  115. System.out.println("Unable to get the access token.");
  116. }else{
  117. te.printStackTrace();
  118. }
  119. }
  120. }
  121. //persist to the accessToken for future reference.
  122. Boolean stored = storeAccessToken(_twitter.verifyCredentials().getId(),
  123. accessToken);
  124. if (stored){
  125. return true;
  126. }else{
  127. return false;
  128. }
  129. }catch (Exception ex){
  130. logger.error(ex.getLocalizedMessage(), ex);
  131. ex.printStackTrace();
  132. return false;
  133. }
  134. }
  135. public AccessToken loadAccessToken(String username){
  136. Gson gson = new Gson();
  137. BasicDBObject query = new BasicDBObject("username", username);
  138. DBCursor cursor = coll.find(query);
  139. DBObject result = null;
  140. try {
  141. if (cursor.count() == 0){
  142. generateAndStoreNewTwitterToken(username);
  143. return loadAccessToken(username);
  144. } else {
  145. while(cursor.hasNext()) {
  146. result = cursor.next();
  147. }
  148. cursor.close();
  149. TwitterAccessDetail obj = gson.fromJson((String)result.get("TwitterAccessDetail"),
  150. TwitterAccessDetail.class);
  151. return new AccessToken(obj.getKey(),obj.getSecret());
  152. }
  153. } catch (TwitterException te){
  154. logger.error(te.getLocalizedMessage(),te);
  155. return new AccessToken("","");
  156. } catch (Exception e) {
  157. logger.error(e.getLocalizedMessage(), e);
  158. e.printStackTrace();
  159. return new AccessToken("","");
  160. }
  161. }
  162. }