List of usage examples for twitter4j Twitter getOAuthAccessToken
AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;
From source file:h2weibo.controllers.CallbackServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletRouter r = new HttpServletRouter(request); r.setPattern("/:type"); if (request.getParameter("denied") != null) { response.sendRedirect("/"); return;// w ww . j av a 2s. c om } HttpSession session = request.getSession(false); String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER); String token = (String) session.getAttribute(Keys.SESSION_TOKEN); String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET); String oauthVerifier = request.getParameter("oauth_verifier"); DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER); if (r.is(":type", "weibo")) { try { Weibo weibo = new Weibo(); AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier); if (accessToken != null) { T2WUser tid = helper.findOneByUser(loginUser); if (tid.getToken() == null) { // send for the first time session.setAttribute(Keys.SESSION_PROMPT_TWEET, "You are ready to go! Do you want to tweet about this service and share it with your friends?"); } tid.setToken(accessToken.getToken()); tid.setTokenSecret(accessToken.getTokenSecret()); helper.saveUser(tid); } else { log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString()); } } catch (WeiboException e) { log.error("Weibo Exception", e); throw new RuntimeException(e); } } else if (r.is(":type", "twitter")) { try { TwitterFactory factory = new TwitterFactory(); Twitter t = factory.getInstance(); twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN); twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier); session.removeAttribute(Keys.SESSION_REQUEST_TOKEN); if (accessToken != null) { t.setOAuthAccessToken(accessToken); User user = t.verifyCredentials(); loginUser = user.getScreenName(); T2WUser tid = helper.findOneByUser(loginUser); if (tid.getTwitterToken() == null) { // save latest id for the first time. sync from that tweet ResponseList<Status> tl = t.getUserTimeline(); if (tl.size() > 0) { Status s = tl.get(0); tid.setLatestId(s.getId()); } } tid.setTwitterToken(accessToken.getToken()); tid.setTwitterTokenSecret(accessToken.getTokenSecret()); helper.saveUser(tid); session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser); } } catch (TwitterException e) { log.error("Twitter Exception", e); throw new RuntimeException(e); } } String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL); if (requestUrl != null) { session.removeAttribute(Keys.SESSION_REQUEST_URL); response.sendRedirect(requestUrl); } else { response.sendRedirect("/u/" + loginUser); } }
From source file:hashimotonet.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * //from w ww . j a v a 2 s . c o m * @param args * message */ public static void main(String[] args) { /* try { new UpdateStatus().connectTwitter(); } catch(Exception e) { e.printStackTrace(); } */ if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } String message = ""; for (int i = 0; i < args.length; i++) { message += args[i] + " "; } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is // already available RequestToken requestToken = twitter.getOAuthRequestToken(); // RequestToken requestToken = new RequestToken(Globals.KEY,Globals.SECRET); String url = requestToken.getAuthenticationURL(); System.out.println("url = " + url); 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) { 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) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { 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(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is // not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(message); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:info.maslowis.twitterripper.twitter.OAuthTwitter.java
License:Open Source License
/** * Displays authorization URL and gets PIN for connection to twitter under authorized user *///from ww w. j a v a 2 s . c om public void authorization() throws IOException { try { Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerKeySecret); RequestToken requestToken = twitter.getOAuthRequestToken(); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Authorization URL:").reset()); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.CYAN).a(requestToken.getAuthorizationURL())); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED).a("Enter PIN please:").reset()); String pin = reader.readLine(); twitter.getOAuthAccessToken(requestToken, pin); } catch (TwitterException e) { logger.error("Authorization fail! Please try to run application again and enter PIN."); exit(1); } }
From source file:jp.ky.twittersample.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message//from w w w . j a v a 2s . com */ public static void main(String[] args) { // if (args.length < 1) { // System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); // System.exit(-1); // } String message = "Test5"; try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available 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) { 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) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { 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(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } //Status status = twitter.updateStatus(message); //System.out.println("Successfully updated the status to [" + status.getText() + "]."); AccountSettings as = twitter.getAccountSettings(); System.out.println("accountsettings:" + as.getScreenName()); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:jp.wda.azeda.core.logics.impl.TwitterServiceImpl.java
License:Apache License
/** {@inheritDoc} */ @Override/*from w ww .ja va 2s .c o m*/ public void registerAccessToken(String requestID, String oauthVerifier) throws TwitterException { Twitter twitter = new TwitterFactory().getInstance(); RequestToken requestToken = requestTokens.get(requestID); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier); StoredAccessToken dbToken = new StoredAccessToken(); dbToken.setUserID(accessToken.getUserId()); dbToken.setAccount(accessToken.getScreenName()); dbToken.setAccessToken(accessToken.getToken()); dbToken.setAccessTokenSecret(accessToken.getTokenSecret()); dbToken.setUpdatedAt(new java.sql.Timestamp(System.currentTimeMillis())); try { accessTokensDao.update(dbToken); } catch (NotSingleRowUpdatedRuntimeException ex) { accessTokensDao.insert(dbToken); } crawlerFactory.startCrawl(dbToken.getUserID()); }
From source file:jp.xxxxxxxx.l3fish.twnyaan.service.AuthenticationService.java
License:Open Source License
/** * RequestToken?PIN??AccessToken??/* w w w . ja v a 2 s .co m*/ * RequestToken??????????{@code null}? * * @param requestToken RequestToken * @param pinCode ???PIN * @return AccessToken??????????{@code null} */ public AccessToken requestAccessToken(RequestToken requestToken, String pinCode) { Twitter twitter = TwitterFactory.getSingleton(); AccessToken accessToken = null; try { accessToken = twitter.getOAuthAccessToken(requestToken, pinCode); twitter.setOAuthAccessToken(accessToken); } catch (IllegalStateException e) { System.err.println(ErrorCode.NO_TOKEN_AVAILABLE); } catch (TwitterException e) { System.err.println(ErrorCode.TWITTER_AUTHORIZATION_FAILED); } return accessToken; }
From source file:net.awairo.favdler.oauth.TwitterOAuth.java
License:MIT License
private MyTask.Function<TwitterAccessor> getTwitterAccessor(Twitter t, RequestToken token, String oauthVerifier) {/*from w w w . ja v a2 s. c o m*/ return () -> { t.getOAuthAccessToken(token, oauthVerifier); return new TwitterAccessor(t); }; }
From source file:net.chrissearle.flickrvote.service.cli.TwitterOAuthCLI.java
License:Apache License
public void authorize(String key, String secret) throws TwitterException, IOException { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(key, secret); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from w ww . j a v a 2 s.c o 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 available) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } System.out.println("Token: " + accessToken.getToken()); System.out.println("TokenSecret: " + accessToken.getTokenSecret()); } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } }
From source file:net.codestory.http.filters.twitter.TwitterAuthenticator.java
License:Apache License
@Override public User authenticate(String oauthToken, String oauthVerifier) { Twitter twitter = twitterFactory.getInstance(); try {//w w w .j a va 2 s.c o m AccessToken accessToken = twitter.getOAuthAccessToken(oauthRequestByToken.remove(oauthToken), oauthVerifier); twitter4j.User user = twitter.users().showUser(accessToken.getUserId()); return new User(accessToken.getUserId(), accessToken.getScreenName(), accessToken.getToken(), accessToken.getTokenSecret(), user.getBiggerProfileImageURL()); } catch (TwitterException e) { throw new AuthenticationException(e); } }
From source file:net.firejack.platform.web.security.twitter.TwitterAuthenticationProcessor.java
License:Apache License
@Override public void processAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (StringUtils.isBlank(getTwitterConsumerKey()) || StringUtils.isBlank(getTwitterConsumerSecret())) { logger.error("Twitter consumer key or consumer secret configs were not set."); response.sendRedirect(getDefaultPageUrl()); } else {/* w ww .j av a 2s .c o m*/ HttpSession httpSession = request.getSession(true); Twitter twitter = (Twitter) httpSession.getAttribute(ATTR_TWITTER_API); if (twitter == null) { twitter = populateTwitterService(); httpSession.setAttribute(ATTR_TWITTER_API, twitter); } if (isRequestTokenCase(request)) { RequestToken requestToken; try { requestToken = twitter.getOAuthRequestToken(getCallbackUrl()); httpSession.setAttribute(ATTR_TWITTER_REQUEST_TOKEN, requestToken); response.sendRedirect(requestToken.getAuthenticationURL());//show twitter authentication form } catch (TwitterException e) {//service is unavailable logger.error("Twitter service is unavailable."); logger.error(e.getMessage(), e); cleanSessionInformation(httpSession); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Twitter service is unavailable."); } catch (IllegalStateException e) {//access token is already available logger.error("access token is already available"); cleanSessionInformation(httpSession); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Twitter processor already having information about access token."); } } else if (isAuthenticationCallback(request)) { RequestToken requestToken = (RequestToken) httpSession.getAttribute(ATTR_TWITTER_REQUEST_TOKEN); String verifier = request.getParameter("oauth_verifier"); try { twitter.getOAuthAccessToken(requestToken, verifier); httpSession.removeAttribute(ATTR_TWITTER_REQUEST_TOKEN); String browserIpAddress = request.getRemoteAddr(); AuthenticationToken authenticationToken = this.getOpenFlameToken(twitter, browserIpAddress); if (authenticationToken == null) { logger.error("Authentication token is null."); } getSignInProcessor().processSignInInternal(request, response, authenticationToken); } catch (TwitterException e) { logger.error(e.getMessage(), e); cleanSessionInformation(httpSession); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } } }