List of usage examples for twitter4j Twitter getOAuthAccessToken
AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;
From source file:org.picketlink.social.auth.TwitterAuthenticator.java
License:Apache License
@Override public void authenticate() { if (httpServletRequest == null) { throw new IllegalStateException("http request not available"); }/*from w ww. java2 s. c o m*/ if (httpServletResponse == null) { throw new IllegalStateException("http response not available"); } if (configuration == null) { throw new IllegalStateException("configuration not available"); } HttpSession session = httpServletRequest.getSession(); ServletContext servletContext = httpServletRequest.getServletContext(); String clientID = configuration.getClientID(); String clientSecret = configuration.getClientSecret(); String returnURL = configuration.getReturnURL(); Principal principal = null; Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(clientID, clientSecret); //See if we are a callback String verifier = httpServletRequest.getParameter("oauth_verifier"); RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); if (verifier != null && requestToken == null) { //Let us fall back String twitterSentRequestToken = httpServletRequest.getParameter("oauth_token"); if (twitterSentRequestToken != null) { requestToken = (RequestToken) servletContext.getAttribute(twitterSentRequestToken); } if (requestToken == null) { throw new IllegalStateException("Verifier present but request token null"); } //Discard the stored request tokens servletContext.removeAttribute(twitterSentRequestToken); session.removeAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); } if (requestToken != null && verifier != null) { try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); session.setAttribute("accessToken", accessToken); session.removeAttribute("requestToken"); } catch (TwitterException e) { throw new AuthenticationException("Twitter Login:", e); } try { principal = new TwitterPrincipal(twitter.verifyCredentials()); setStatus(AuthenticationStatus.SUCCESS); setAccount(new User(principal.getName())); return; } catch (TwitterException e) { throw new AuthenticationException("Twitter Login:", e); } } try { requestToken = twitter.getOAuthRequestToken(returnURL); session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken); //back up in the case the browser provides a new session to the user on twitter callback servletContext.setAttribute(requestToken.getToken(), requestToken); httpServletResponse.sendRedirect(requestToken.getAuthenticationURL()); } catch (Exception e) { throw new AuthenticationException("Twitter Login:", e); } if (principal != null) { setStatus(AuthenticationStatus.SUCCESS); setAccount(new User(principal.getName())); } }
From source file:org.sakaiproject.profile2.tool.pages.panels.TwitterPrefsPane.java
License:Educational Community License
/** * Helper to get the user access token from the request token and supplied access code * @param accessCode//from w w w .j a v a2 s . c o m * @return */ private AccessToken getOAuthAccessToken(String accessCode) { Map<String, String> config = externalIntegrationLogic.getTwitterOAuthConsumerDetails(); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); try { return twitter.getOAuthAccessToken(requestToken, accessCode); } catch (TwitterException e) { e.printStackTrace(); } return null; }
From source file:org.smarttechie.servlet.TwitterCallbackServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); System.out.println("TwitterCallbackServlet:requestToken:" + requestToken); String verifier = request.getParameter("oauth_verifier"); try {//from ww w . j a v a2 s. com twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java
License:Open Source License
/** * Starts a command line authentication with yammer to get the needed access * token.//from ww w . j av a 2 s . co m */ private void startCommandLineAuthentication() { if (!source.isPropertyTrue(TwitterProperties.ALLOW_COMMAND_LINE_AUTHENTICATION)) { return; } // get property values from configuration String consumerKey = source.getPropertyValue(TwitterProperties.CONSUMER_KEY_PROPERTY); String consumerSecret = source.getPropertyValue(TwitterProperties.CONSUMER_SECRET_PROPERTY); // check properties if (consumerKey == null || consumerKey.isEmpty()) { log("A valid consumer key is needed in the configuration specified by " + TwitterProperties.CONSUMER_KEY_PROPERTY, LogService.LOG_WARNING); return; } else if (consumerSecret == null || consumerSecret.isEmpty()) { log("A valid consumer secret is needed in the configuration specified by " + TwitterProperties.CONSUMER_SECRET_PROPERTY, LogService.LOG_WARNING); return; } log("Starting command line authentication.", LogService.LOG_INFO); // Access Token not contained in properties Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken; // create new request token try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { log("Unable to get request token from Twitter. Please check your Consumer Key and Secret.", LogService.LOG_ERROR); return; } System.out.println("Request token: " + requestToken.getToken()); System.out.println("Token secret: " + requestToken.getTokenSecret()); String authorizationURL = requestToken.getAuthorizationURL(); // wait for user confirming the request System.out.println("Now visit:\n" + authorizationURL + "\n... and grant this app authorization"); System.out.println("Enter the PIN code and hit ENTER when you're done:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String pin; try { pin = br.readLine(); } catch (IOException e) { e.printStackTrace(); return; } AccessToken accessToken = null; try { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } catch (Exception e) { accessToken = null; } if (accessToken == null) { log("Got no Twitter OAuth Access Token for given Request and Pin!", LogService.LOG_ERROR); return; } System.out.println("Access token: " + accessToken.getToken()); System.out.println("Token secret: " + accessToken.getTokenSecret()); }
From source file:org.springframework.integration.twitter.oauth.ConsoleBasedAccessTokenInitialRequestProcessListener.java
License:Apache License
public static void main(String[] args) throws Exception { File twitterProps = new File(SystemUtils.getUserHome(), "Desktop/twitter.properties"); PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new FileSystemResource(twitterProps)); propertiesFactoryBean.afterPropertiesSet(); Properties props = propertiesFactoryBean.getObject(); String key = StringUtils.trim(props.getProperty("twitter.oauth.consumerKey")); String secret = StringUtils.trim(props.getProperty("twitter.oauth.consumerSecret")); ConsoleBasedAccessTokenInitialRequestProcessListener consoleBasedAccessTokenInitialRequestProcessListener = new ConsoleBasedAccessTokenInitialRequestProcessListener(); Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(key, secret); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//w w w.j a v a 2 s .c o m BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { String pin = consoleBasedAccessTokenInitialRequestProcessListener .openUrlAndReturnPin(requestToken.getAuthorizationURL()); 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(); } } } consoleBasedAccessTokenInitialRequestProcessListener.persistReturnedAccessToken(accessToken); }
From source file:org.tomochika1985.twitter.AppSession.java
License:Apache License
public boolean login(String pin, Response response) { try {/*from w w w. jav a2 s. c o m*/ if (requestToken == null) { throw new IllegalStateException("requestToken is missing."); } Twitter client = new TwitterClient(); client.setOAuthConsumer(consumerKey, consumerSecret); AccessToken accessToken = client.getOAuthAccessToken(requestToken, pin); client.setOAuthAccessToken(accessToken); this.twitterSession = client; dirty(); return true; } catch (TwitterException ex) { LOGGER.error("Can not setup OAuth Access Token to Twitter object.", ex); return false; } }
From source file:org.twitter.oauth.java
public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer("SjLUa1Pwrs81nIAGiR4f1l4I7", "ISAXBmzqzYLKWQXAaOe09j34APvVOyxahHghLBSvvR0Psnhozl"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from w w w. j a v a 2 s.co m*/ 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 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 te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } //persist to the accessToken for future reference. storeAccessToken((int) twitter.verifyCredentials().getId(), accessToken); Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
From source file:org.wso2.carbon.identity.authenticator.twitter.TwitterAuthenticator.java
License:Open Source License
/** * Process the response of the Twitter// www. ja va 2 s . c om */ @Override protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { Twitter twitter = (Twitter) request.getSession() .getAttribute(TwitterAuthenticatorConstants.AUTHENTICATOR_NAME.toLowerCase()); RequestToken requestToken = (RequestToken) request.getSession() .getAttribute(TwitterAuthenticatorConstants.TWITTER_REQUEST_TOKEN); String verifier = request.getParameter(TwitterAuthenticatorConstants.TWITTER_OAUTH_VERIFIER); try { AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute(TwitterAuthenticatorConstants.TWITTER_REQUEST_TOKEN); User user = twitter.verifyCredentials(); if (token != null) { buildClaims(user, context); } } catch (TwitterException e) { log.error("Exception while obtaining OAuth token form Twitter", e); throw new AuthenticationFailedException("Exception while obtaining OAuth token form Twitter", e); } }
From source file:org.yamaLab.TwitterConnector.GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message */// w w w . j a v a2 s.c o m public static void main(String[] args) { File file = new File("TweetByWikiEx2.properties"); Properties prop = new Properties(); InputStream is = null; OutputStream os = null; try { /* try-0 */ if (file.exists()) { is = new FileInputStream(file); prop.load(is); } if (args.length < 2) { if (null == prop.getProperty("oauth.consumerKey") && null == prop.getProperty("oauth.consumerSecret")) { // consumer key/secret are not set in twitter4j.properties System.out.println( "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]"); System.exit(-1); } } else { prop.setProperty("oauth.consumerKey", args[0]); prop.setProperty("oauth.consumerSecret", args[1]); os = new FileOutputStream("twitter4j.properties"); prop.store(os, "twitter4j.properties"); } } catch (IOException ioe) { /* try-0 */ ioe.printStackTrace(); System.exit(-1); } finally { /* try-0 */ if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { try { os.close(); } catch (IOException ignore) { } } try { /* try-1 in try-0 */ Twitter twitter = new TwitterFactory().getInstance(); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { /* while */ System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); try { /* try-1 */ Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (UnsupportedOperationException ignore) { } catch (IOException ignore) { } catch (URISyntaxException e) { throw new AssertionError(e); } /* try-1 */ System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { /* try-3 in try-0 */ if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } /* try-3 in try-0 */ } /* while */ System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); try { /* try-2 in try 0 */ prop.setProperty("oauth.accessToken", accessToken.getToken()); prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret()); os = new FileOutputStream(file); prop.store(os, "twitter4j.properties"); os.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } finally { if (os != null) { try { os.close(); } catch (IOException ignore) { } } } System.out.println("Successfully stored access token to " + file.getAbsolutePath() + "."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get accessToken: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } /* try-1 in try-0 */ } /* try-0 */ }
From source file:org.yukung.following2ldr.command.impl.FindFeedUrlCommand.java
License:Apache License
@Override public void run() throws Throwable { // Twitter??//from ww w . ja v a 2 s . c o m long start = System.currentTimeMillis(); String consumerKey = config.getProperty(Constants.CONSUMER_KEY); String consumerSecret = config.getProperty(Constants.CONSUMER_SECRET); String userName = params.get(0); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); String authorizationURL = requestToken.getAuthorizationURL(); System.out.println(":" + authorizationURL); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the PIN:"); String pin = br.readLine(); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin); twitter.setOAuthAccessToken(accessToken); long cursor = -1L; IDs friendIDs; List<Long> iDsList = new ArrayList<Long>(5000); do { friendIDs = twitter.getFriendsIDs(userName, cursor); long[] iDs = friendIDs.getIDs(); for (long iD : iDs) { iDsList.add(iD); } cursor = friendIDs.getNextCursor(); } while (friendIDs.hasNext()); List<long[]> list = new ArrayList<long[]>(); int offset = 0; long[] tmp = new long[100]; for (Long id : iDsList) { if (offset < 100) { tmp[offset] = id; offset++; } else { list.add(tmp); offset = 0; tmp = new long[100]; } } list.add(tmp); List<URL> urlList = new ArrayList<URL>(); for (long[] array : list) { ResponseList<User> lookupUsers = twitter.lookupUsers(array); for (User user : lookupUsers) { log.info("URL:" + user.getURL()); urlList.add(user.getURL()); } } String path = "C:\\Users\\ikeda_yusuke\\Documents\\sandbox\\java\\data\\" + userName + ".txt"; FileWriter writer = new FileWriter(path); BufferedWriter out = new BufferedWriter(writer); // PrintWriter pw = new PrintWriter(writer); for (URL url : urlList) { if (url != null) { out.write(url.toString() + "\n"); } } out.flush(); out.close(); long end = System.currentTimeMillis(); log.info("?:" + (end - start) + " ms"); // ??IDor?? // Twitter API??????ID? // ?????ID?URL100??? // ??URL? }