List of usage examples for twitter4j Twitter setOAuthConsumer
void setOAuthConsumer(String consumerKey, String consumerSecret);
From source file:com.appspot.bitlyminous.standalone.TwitterExample.java
License:Apache License
/** * The main method.//from ww w . ja v a 2s . co m * * @param args the arguments * * @throws Exception the exception */ public static void main(String[] args) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("671O1zUicFBCYHHYVp0XA", "cP7WvfAtxXGSaf1Sz0ksZtWGcENosFcRr46WR7a9jU"); 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:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } // persist to the accessToken for future reference. System.out.println("Screen name:" + accessToken.getScreenName()); System.out.println("Token:" + accessToken.getToken()); System.out.println("Secret:" + accessToken.getTokenSecret()); IDs friendsIDs = twitter.getFriendsIDs("gapinginfinity"); System.out.println(Arrays.toString(friendsIDs.getIDs())); ResponseList<Status> favorites = twitter.getFavorites("gapinginfinity"); System.out.println(favorites.size()); System.exit(0); }
From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java
License:Apache License
/** * Return instance of Twitter class which has AccessToken been set. * @param username//from ww w. j ava 2 s. c om * @return twitter instance of Twitter class */ public static Twitter getInstance(String username) { Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret")); twitter.setOAuthAccessToken(getAccessToken(username)); return twitter; }
From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java
License:Apache License
public static AccessToken getAccessToken(String username) { AccessToken accessToken = null;/*from w w w .j av a 2 s . com*/ if (Prefs.get(username + "/accessToken").isEmpty()) { Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret")); RequestToken requestToken; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { requestToken = twitter.getOAuthRequestToken(); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException ex) { if (401 == ex.getStatusCode()) { System.out.println("Unable to get the access token."); } else { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } } } } catch (IOException | TwitterException ex) { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } Prefs.put(username + "/accessToken", accessToken.getToken()); Prefs.put(username + "/accessTokenSecret", accessToken.getTokenSecret()); } logger.finest("Token&Secret: " + Prefs.get(username + "/accessToken") + " " + Prefs.get(username + "/accessTokenSecret")); logger.finest("OauthConsum&Secret: " + Prefs.get("OAuthConsumerKey") + " " + Prefs.get("consumerSecret")); accessToken = new AccessToken(Prefs.get(username + "/accessToken"), Prefs.get(username + "/accessTokenSecret")); return accessToken; }
From source file:com.company.TwitterPopularLinks.java
License:Apache License
public void sparkStreaming(SparkConf conf) { ///Creates Streaming Context JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(1)); //Create a Twitter Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(new AccessToken(accessTokenKey, accessTokenKey_secret)); JavaDStream<Status> stream = TwitterUtils.createStream(jsc, twitter.getAuthorization()); JavaDStream<String> words = stream.map(new Function<Status, String>() { public String call(Status status) { return status.getText(); }//ww w .ja va 2 s . c om }); JavaDStream<String> statuses = words.flatMap(new FlatMapFunction<String, String>() { public Iterable<String> call(String in) { return Arrays.asList(in.split(" ")); } }); //Get the stream of hashtags from the stream of tweets JavaDStream<String> hashTags = statuses.filter(new Function<String, Boolean>() { public Boolean call(String word) { return word.startsWith("#"); } }); //Count the hashtags over a 5 minute window JavaPairDStream<String, Integer> tuples = hashTags.mapToPair(new PairFunction<String, String, Integer>() { public Tuple2<String, Integer> call(String in) { return new Tuple2<String, Integer>(in, 1); } }); //count these hashtags over a 5 minute moving window JavaPairDStream<String, Integer> counts = tuples .reduceByKeyAndWindow(new Function2<Integer, Integer, Integer>() { public Integer call(Integer i1, Integer i2) { return i1 + i2; } }, new Function2<Integer, Integer, Integer>() { public Integer call(Integer i1, Integer i2) { return i1 - i2; } }, new Duration(60 * 5 * 1000), new Duration(1 * 1000)); counts.print(); //jsc.checkpoint(checkPoint); jsc.start(); jsc.awaitTermination(); }
From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java
License:Apache License
/** * Get the authorization URL and send it back in a sticky broadcast. */// ww w . j a v a 2 s .co m private void processGetAuthURL() { //create a RequestToken to use to create the request URL // token will be used later to decode result from twitter.com // and needs to be saved to static variable in MSTwitter RequestToken reqToken = null; Twitter twitter4j = null; String url = null; int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; // be optimistic try { twitter4j = new TwitterFactory().getInstance(); twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret); } catch (IllegalStateException e) { // No network access or token already available resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER; Log.e(MSTwitter.TAG, e.toString()); } // get the token if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) { try { reqToken = twitter4j.getOAuthRequestToken(MSTwitter.CALLBACK_URL); } catch (TwitterException e) { int tErrorNum = MSTwitter.getTwitterErrorNum(e, this); // No network access resultCode = tErrorNum; Log.e(MSTwitter.TAG, e.getExceptionCode() + ": " + e.getMessage()); } catch (IllegalStateException e) { // No network access or token already available resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_TOKEN_ALREADY_AVALIABLE; Log.e(MSTwitter.TAG, e.toString()); } } // if we got the request token then use it to get the url if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) { url = reqToken.getAuthenticationURL(); // save the request token MSTwitter.smReqToken = reqToken; } // broadcast the results Intent broadcastIntent = new Intent(); broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER); broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK, MSTwitterService.MST_SERVICE_TASK_GET_AUTH_URL); broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT, resultCode); if (url != null) { broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT_URL, url); } broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText); broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath); sendStickyBroadcast(broadcastIntent); }
From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java
License:Apache License
/** * Make the token and save using SharedPreferences. Then send back a sticky broadcast * @param extras Bundle containing the oauth verifier string *//*from w w w .j av a2 s. c o m*/ private void processMakeToken(Bundle extras) { AccessToken accessToken = null; int resultCode = MSTwitter.MST_RESULT_NO_PASSED_OAUTH; // get the oAuth verifier string from the bundle String oAuthVerifier = extras.getString(MST_KEY_AUTH_OAUTH_VERIFIER); if (oAuthVerifier != null) { // first setup the twitter4j object resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; Twitter twitter4j = null; try { twitter4j = new TwitterFactory().getInstance(); twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret); } catch (IllegalStateException e) { // No network access or token already available resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER; Log.e(MSTwitter.TAG, e.toString()); } // now get the access token if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) { try { accessToken = twitter4j.getOAuthAccessToken(MSTwitter.smReqToken, oAuthVerifier); } catch (NullPointerException e) { resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER; Log.e(MSTwitter.TAG, e.toString()); } catch (UnsupportedOperationException e) { resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER; Log.e(MSTwitter.TAG, e.toString()); } catch (TwitterException e) { resultCode = MSTwitter.getTwitterErrorNum(e, this); Log.e(MSTwitter.TAG, e.getLocalizedMessage()); } } } if (accessToken != null) { // save the access token parts String token = accessToken.getToken(); String secret = accessToken.getTokenSecret(); // Create shared preference object to remember if the user has already given us permission SharedPreferences refs = this.getSharedPreferences(MSTwitter.PERF_FILENAME, Context.MODE_PRIVATE); Editor editor = refs.edit(); editor.putString(MSTwitter.PREF_ACCESS_TOKEN, token); editor.putString(MSTwitter.PREF_ACCESS_TOKEN_SECRET, secret); editor.commit(); resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; } // broadcast the results Intent broadcastIntent = new Intent(); broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER); broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK, MSTwitterService.MST_SERVICE_TASK_MAKE_TOKEN); broadcastIntent.putExtra(MSTwitterService.MST_KEY_MAKE_TOKEN_RESULT, resultCode); broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText); broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath); sendStickyBroadcast(broadcastIntent); }
From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java
License:Apache License
/** * Sets access token, sends tweet.//from w w w.j a v a2s . co m * @category Helpers * @return result code */ private int sendTweet(String text, String imagePath, AccessToken accessToken) { int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; // check to make sure we have data and access before tweeting if (text == null && imagePath == null) { return MSTwitter.MST_RESULT_NO_DATA_TO_SEND; } if (accessToken == null) { return MSTwitter.MST_RESULT_NOT_AUTHORIZED; } // get twitter4j object Twitter twitter4j = null; try { twitter4j = new TwitterFactory().getInstance(); twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret); } catch (IllegalStateException e) { // No network access or token already available resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER; Log.e(MSTwitter.TAG, e.toString()); return resultCode; } // Create and set twitter access credentials from token and or secret twitter4j.setOAuthAccessToken(accessToken); try { // finally update the status (send the tweet) StatusUpdate status = new StatusUpdate(text); if (imagePath != null) { status.setMedia(new File(imagePath)); } twitter4j.updateStatus(status); } catch (TwitterException e) { return MSTwitter.getTwitterErrorNum(e, this); } return resultCode; }
From source file:com.eclipsesource.iot.photosensor.example.Main.java
License:Open Source License
private static void authenticateTwitter(AccessToken accessToken, Twitter twitter) { twitter.setOAuthConsumer(APP_KEY, APP_SECRET); twitter.setOAuthAccessToken(accessToken); }
From source file:com.esri.gpt.framework.security.identity.open.OpenidConsumerServlet.java
License:Apache License
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestContext context = null;//from w w w . j av a 2 s . c o m boolean useFacade = false; String err = ""; try { LOGGER.finer("Query string=" + request.getQueryString()); String op = request.getParameter("op"); context = RequestContext.extract(request); OpenProviders providers = context.getIdentityConfiguration().getOpenProviders(); if ((providers == null) || (providers.size() == 0)) { return; } String baseContextPath = RequestContext.resolveBaseContextPath(request); String callbackUrl = baseContextPath + "/openid"; String realm = baseContextPath; HttpSession session = request.getSession(); // process a response from an Openid provider if (op == null) { String identity = null; String username = null; String email = null; // determine the callback info String cbinfo = Val.chkStr((String) session.getAttribute(ATTR_CBINFO)); session.setAttribute(ATTR_CBINFO, null); if (cbinfo.length() == 0) { throw new ServletException("Invalid openid callback info."); } int idx = cbinfo.indexOf(","); long millis = Long.parseLong(cbinfo.substring(0, idx)); cbinfo = cbinfo.substring(idx + 1); idx = cbinfo.indexOf(","); String cbid = cbinfo.substring(0, idx); cbinfo = cbinfo.substring(idx + 1); idx = cbinfo.indexOf(","); op = cbinfo.substring(0, idx); String fwd = cbinfo.substring(idx + 1); LOGGER.finer("cbinfo retrieved: " + cbinfo); // determine the provider OpenProvider provider = providers.get(op); if (provider == null) { throw new ServletException("Invalid openid op parameter on callback: " + op); } boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter"); // determine the authenticated user attributes if (useFacade) { identity = "http://openidfacade/user123"; email = "user123@openidfacade.com"; username = email; // Twitter callback } else if (isTwitter) { try { LOGGER.finer("Determining user attributes for: " + op); String token = (String) session.getAttribute(ATTR_TOKEN); String tokenSecret = (String) session.getAttribute(ATTR_TOKEN_SECRET); Twitter twitter = new Twitter(); twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret()); AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret); twitter.setOAuthAccessToken(accessToken); twitter4j.User tUser = twitter.verifyCredentials(); String screenName = Val.chkStr(tUser.getScreenName()); if (screenName.length() > 0) { username = screenName + "@twitter"; identity = "twitter:" + screenName; } } catch (Exception e) { err = "oAuth authentication failed."; LOGGER.log(Level.WARNING, err, e); } // Openid callback } else { try { // determine the callback UUID String cbidParam = Val.chkStr(request.getParameter("cbid")); if (cbidParam.length() == 0) { throw new ServletException("Empty cbid parameter on callback."); } if (!cbid.equals(cbidParam)) { throw new ServletException("Invalid openid cbid parameter on callback."); } callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8"); LOGGER.finer("cbinfo based callback: " + cbinfo); LOGGER.finer("Determining user attributes for: " + op); OpenIdManager manager = new OpenIdManager(); manager.setRealm(realm); manager.setReturnTo(callbackUrl); checkNonce(request.getParameter("openid.response_nonce")); byte[] mac_key = (byte[]) session.getAttribute(ATTR_MAC); String alias = (String) session.getAttribute(ATTR_ALIAS); Authentication authentication = manager.getAuthentication(request, mac_key, alias); identity = authentication.getIdentity(); email = authentication.getEmail(); username = email; } catch (Exception e) { err = "Openid authentication suceeded, creating local user reference failed."; LOGGER.log(Level.WARNING, err, e); } } // check the parameters identity = Val.chkStr(identity); username = Val.chkStr(username); email = Val.chkStr(email); LOGGER.finer( "User attributes: identity=" + identity + ", username=" + username + ", email=" + email); if (identity.length() == 0) { err = "Your openid idenitfier was not determined."; } else if (username.length() == 0) { if (isTwitter) { err = "Your opennid screen name was not determined."; } else { err = "Your opennid email address was not determined."; } } else { // establish the user identity = "urn:openid:" + identity; User user = context.getUser(); user.reset(); user.setKey(identity); user.setDistinguishedName(identity); user.setName(username); user.getProfile().setUsername(username); if (email.length() > 0) { user.getProfile().setEmailAddress(email); } user.getAuthenticationStatus().setWasAuthenticated(true); // ensure a local reference for the user try { LocalDao localDao = new LocalDao(context); localDao.ensureReferenceToRemoteUser(user); } catch (Exception e) { user.reset(); err = "Openid authentication suceeded, creating local user reference failed."; LOGGER.log(Level.SEVERE, err, e); } } // redirect to the originating page String url = fwd; err = Val.chkStr(err); if (err.length() > 0) { if (url.indexOf("?") == -1) fwd += "?"; else url += "&"; url += "err=" + URLEncoder.encode(err, "UTF-8"); } response.sendRedirect(url); // process a request to enter Openid credentials } else if (op.length() > 0) { session.setAttribute(ATTR_CBINFO, null); // determine the provider OpenProvider provider = providers.get(op); if (provider == null) { throw new ServletException("Invalid openid op parameter: " + op); } boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter"); // determine the active Geoportal page (forward URL) String fwd = Val.chkStr(request.getParameter("fwd")); if (fwd.length() == 0) { throw new ServletException("Empty openid fwd parameter."); } // store the callback info String cbid = UUID.randomUUID().toString(); long millis = System.currentTimeMillis(); String cbinfo = millis + "," + cbid + "," + op + "," + fwd; session.setAttribute(ATTR_CBINFO, cbinfo); // determine the Openid Authentication URL String url = null; if (useFacade) { PrintWriter pw = response.getWriter(); pw.println("<html><head><title>Openid Facade</title></head><body><h1>Openid Facade</h1>"); pw.println("<a href=\"" + callbackUrl + "\">Supply credentials step</a>"); pw.println("</body></html>"); pw.flush(); return; // Twitter } else if (isTwitter) { try { LOGGER.fine("Initiating oAuth request for: " + op + ", callback=" + callbackUrl); Twitter twitter = new Twitter(); twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret()); RequestToken requestToken = twitter.getOAuthRequestToken(); String token = requestToken.getToken(); String tokenSecret = requestToken.getTokenSecret(); session.setAttribute(ATTR_TOKEN, token); session.setAttribute(ATTR_TOKEN_SECRET, tokenSecret); url = requestToken.getAuthorizationURL(); } catch (TwitterException e) { err = "Unable to determine endpoint for: " + op; LOGGER.log(Level.SEVERE, err, e); } // Openid } else { try { callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8"); LOGGER.finer("Initiating openid request for: " + op + ", callback=" + callbackUrl); OpenIdManager manager = new OpenIdManager(); manager.setRealm(realm); manager.setReturnTo(callbackUrl); // There is an issue here. It seems that the only way to set the endpoint // alias is through the jopenid-1.07.jar openid-providers.properties, // but we would to to configure the provider properties through gpt.xml //Endpoint endpoint = manager.lookupEndpoint(provider.getAuthenticationUrl()); Endpoint endpoint = manager.lookupEndpoint(op); Association association = manager.lookupAssociation(endpoint); request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey()); request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias()); url = manager.getAuthenticationUrl(endpoint, association); } catch (Exception e) { err = "Unable to determine Openid endpoint for: " + op; LOGGER.log(Level.SEVERE, err, e); } } // redirect to the authentication endpoint or to originating page err = Val.chkStr(err); if (err.length() > 0) { url = fwd; if (url.indexOf("?") == -1) fwd += "?"; else url += "&"; url += "err=" + URLEncoder.encode(err, "UTF-8"); } LOGGER.finer("Redirecting for authentication: " + url); response.sendRedirect(url); } else { throw new ServletException("Empty openid op parameter."); } } finally { if (context != null) context.onExecutionPhaseCompleted(); } }
From source file:com.firewallid.crawling.TwitterApp.java
private Twitter createTwitter() { String[] currentApp = conf.getStrings(String.format("%s.%s", APPS, apps[appIdx])); //0:CONSUMER_KEY 1:CONSUMER_KEY_SECRET 2:ACCESS_TOKEN 3:ACCESS_TOKEN_SECRET Twitter tw = new TwitterFactory().getInstance(); tw.setOAuthConsumer(currentApp[0], currentApp[1]); AccessToken accessToken = new AccessToken(currentApp[2], currentApp[3]); tw.setOAuthAccessToken(accessToken); return tw;/*ww w . jav a 2 s. c om*/ }