List of usage examples for twitter4j Twitter Twitter
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 ww w .j a v a2s .com 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.eventattend.portal.bl.TwitterBL.java
License:Open Source License
public TwitterBL() { twitter = new Twitter(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); }
From source file:com.eventattend.portal.bl.TwitterBL.java
License:Open Source License
public TwitterDTO initTwitter(TwitterDTO twitterDTO) throws EventPortalException { //TwitterDTO twitterDTO = new TwitterDTO(); boolean isTwitterConnected = false; RequestToken requestToken;//w w w . j av a 2s .c om String tokenSecret = null; String token = null; String authUrl = null; AccessToken adminAccessToken = null; AccessToken userAccessToken = null; try { System.out.println("Initialising Social Media ==>Twitter"); adminAccessToken = getAccessToken(twitterDTO.getAdminProfileId()); userAccessToken = getAccessToken(twitterDTO.getProfileId()); twitterDTO = new TwitterDTO(); if (adminAccessToken != null) { //isTwitterConnected = testTwitter(adminAccessToken); isTwitterConnected = true; if (isTwitterConnected) { twitterDTO.setAdminAccessToken(adminAccessToken); } else { adminAccessToken = null; } } if (userAccessToken != null) { //isTwitterConnected = testTwitter(userAccessToken); isTwitterConnected = true; if (isTwitterConnected) { twitterDTO.setAccessToken(userAccessToken); } else { userAccessToken = null; } } if (adminAccessToken == null || userAccessToken == null) { twitter = new Twitter(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); requestToken = twitter.getOAuthRequestToken(); token = requestToken.getToken(); tokenSecret = requestToken.getTokenSecret(); authUrl = requestToken.getAuthorizationURL(); System.out.println("Request token: " + token); System.out.println("Token secret: " + tokenSecret); System.out.println("authUrl: " + authUrl); twitterDTO.setToken(token); twitterDTO.setTokenSecret(tokenSecret); twitterDTO.setAuthUrl(authUrl); } } catch (TwitterException e) { processTwitterException(e); } return twitterDTO; }
From source file:com.joshlong.esb.springintegration.modules.social.twitter.TwitterMessageSource.java
License:Apache License
public void afterPropertiesSet() throws Exception { logger.debug("after properties set for TwitterMessageSource!!"); if (twitter == null) { Assert.state(!StringUtils.isEmpty(userId)); Assert.state(!StringUtils.isEmpty(password)); twitter = new Twitter(); twitter.setUserId(userId);//from w ww .j av a 2 s .c o m twitter.setPassword(password); } else { // it isnt null, in which case it becomes canonical memory setPassword(twitter.getPassword()); setUserId(twitter.getUserId()); } cachedStatuses = new ConcurrentLinkedQueue<Tweet>(); lastStatusIdRetreived = -1; }
From source file:com.joshlong.esb.springintegration.modules.social.twitter.TwitterTweetSendingMessageHandler.java
License:Apache License
public void afterPropertiesSet() throws Exception { Assert.state(null != type);//from w w w . j a va2 s. c o m if (twitter == null) { Assert.state(!StringUtils.isEmpty(username)); Assert.state(!StringUtils.isEmpty(password)); twitter = new Twitter(); twitter.setUserId(username); twitter.setPassword(password); } else { // it isnt null, in which case it becomes canonical memory setPassword(twitter.getPassword()); setUsername(twitter.getUserId()); } }
From source file:main.TokenManager.java
License:Open Source License
public void initialize() { // Log the user in twitter = new Twitter(); twitter.setOAuthConsumer(Global.MY_TOKEN, Global.MY_SECRET); String YN = "#"; String PIN = null;//from www. ja v a 2s .co m if (readMyToken() == false) { RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { // TODO Auto-generated catch block System.out.println("Error in twitter.getOAuthRequestToken()"); } 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("Once you are done, type in the PIN code:"); try { PIN = br.readLine(); } catch (IOException e) { } try { accessToken = twitter.getOAuthAccessToken(requestToken, PIN); } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } username = accessToken.getScreenName(); System.out.print("Access granted. Do you want to save the token for future use? (Y/N) "); while (YN.charAt(0) != 'Y' && YN.charAt(0) != 'y' && YN.charAt(0) != 'N' && YN.charAt(0) != 'n') { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { YN = in.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } switch (YN.charAt(0)) { case 'Y': case 'y': try { storeAccessToken(twitter.verifyCredentials().getId(), accessToken); } catch (TwitterException e) { System.out.println("twitter.verifyCredentials().getId()"); } break; } } else { accessToken = new AccessToken(myToken, myTokenSecret); twitter.setOAuthAccessToken(accessToken); } }
From source file:org.apache.aries.sample.twitter.TwitterQuery.java
License:Apache License
public void start(BundleContext context) throws Exception { Twitter twitter = new Twitter(); Query query = new Query("from:theasf"); try {/*from ww w . j a va2 s .com*/ QueryResult result = twitter.search(query); List<Tweet> tweets = result.getTweets(); System.out.println("hits:" + tweets.size()); for (Tweet tweet : tweets) { System.out.println(tweet.getFromUser() + ":" + StringEscapeUtils.unescapeXml(tweet.getText())); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.sevenleaves.droidsensor.TwitterUtils.java
License:Apache License
public static String getProfileUri(String user) { Twitter twitter = new Twitter(); StringBuilder b = new StringBuilder(); b.append(twitter.getBaseURL());/* ww w .java 2 s . c o m*/ b.append('/'); b.append(user); return b.toString(); }