List of usage examples for twitter4j Twitter setOAuthConsumer
void setOAuthConsumer(String consumerKey, String consumerSecret);
From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java
License:Open Source License
/** * Tweet a message to the specified profile * //from ww w . j a v a2 s .c o m * @param entity * An entity containing the user information and the twitter * credentials * @return true if it was able to tweet the updates * */ @SuppressWarnings("unchecked") private boolean tweet(OrcidSocialEntity entity) { String jsonCredentials = decrypt(entity.getEncryptedCredentials()); Map<String, String> credentials = (HashMap<String, String>) JSON.parse(jsonCredentials); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(twitterKey, twitterSecret); AccessToken accessToken = new AccessToken(credentials.get(TWITTER_USER_KEY), credentials.get(TWITTER_USER_SECRET)); twitter.setOAuthAccessToken(accessToken); try { twitter.updateStatus(buildUpdateMessage(entity.getId().getOrcid())); } catch (Exception e) { LOGGER.error("Unable to tweet on profile {}", entity.getId().getOrcid()); return false; } return true; }
From source file:org.osframework.maven.plugins.twitter.AbstractTwitterMojo.java
License:Apache License
private Twitter getAuthenticatedTwitter() throws TwitterException { if (StringUtils.isBlank(consumerKey) || StringUtils.isBlank(consumerSecret)) { throw new TwitterException("Missing required credentials"); }/* www. j a v a2 s . c o m*/ Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerSecret); loadAccessToken(twitter); twitter.setOAuthAccessToken(authToken); return twitter; }
From source file:org.picketlink.extensions.core.social.twitter.TwitterAuthenticationMechanism.java
License:Open Source License
@Override protected Principal doAuthenticate(UserCredential credential, AuthenticationResult result) throws AuthenticationException { TwitterCredential oAuthCredential = (TwitterCredential) credential; HttpServletRequest request = oAuthCredential.getRequest(); HttpServletResponse response = oAuthCredential.getResponse(); HttpSession session = request.getSession(); Principal principal = null;/* www. ja v a 2 s.co m*/ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(clientID, clientSecret); //See if we are a callback RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); if (requestToken != null) { String verifier = request.getParameter("oauth_verifier"); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); session.setAttribute("accessToken", accessToken); session.removeAttribute("requestToken"); } catch (TwitterException e) { throw new AuthenticationException(e); } try { principal = new TwitterPrincipal(twitter.verifyCredentials()); checkUserInStore((TwitterPrincipal) principal); } catch (TwitterException e) { throw new AuthenticationException(e); } return principal; } try { requestToken = twitter.getOAuthRequestToken(returnURL); session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (Exception e) { throw new AuthenticationException(e); } return principal; }
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 ww w. j av a 2 s. com*/ 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.primefaces.examples.service.TwitterAPIService.java
License:Apache License
public List<Status> getTweets(String username) { List<Status> tweets = null; try {//from w ww. j ava2 s. c o m if (username != null && !username.equals("")) { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret)); Paging p = new Paging(1, 200); tweets = twitter.getUserTimeline(username, p); } } catch (Exception e) { logger.severe(e.getMessage()); } return tweets; }
From source file:org.rhq.enterprise.server.plugins.alertMicroblog.MicroblogSender.java
License:Open Source License
@Override public SenderResult send(Alert alert) { SenderResult result;//from ww w. j av a 2 s . c o m String consumerKey = preferences.getSimpleValue("consumerKey", CONS_KEY); String consumerSecret = preferences.getSimpleValue("consumerSecret", CONS_SECRET); String accessTokenFilePath = preferences.getSimpleValue("accessTokenFilePath", "/path/to/token.ser"); try { TwitterFactory tFactory = new TwitterFactory(); AccessToken accessToken = restoreAccessToken(accessTokenFilePath); log.debug("loading accessToken from " + accessTokenFilePath); log.debug("token: [" + accessToken.getToken() + "]"); log.debug("tokenSecret: [" + accessToken.getTokenSecret() + "]"); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); AlertManagerLocal alertManager = LookupUtil.getAlertManager(); StringBuilder b = new StringBuilder("Alert "); b.append(alert.getId()).append(":'"); // Alert id b.append(alert.getAlertDefinition().getResource().getName()); b.append("' ("); b.append(alert.getAlertDefinition().getResource().getId()); b.append("): "); b.append(alertManager.prettyPrintAlertConditions(alert, true)); b.append("-by " + this.alertParameters.getSimpleValue("twittedBy", "@RHQ")); // TODO not for production :-) // TODO use some alert url shortening service String msg = b.toString(); if (msg.length() > 140) msg = msg.substring(0, 140); Status status = twitter.updateStatus(msg); result = SenderResult.getSimpleSuccess("Send notification - msg-id: " + status.getId()); } catch (TwitterException e) { log.warn("Notification via Microblog failed!", e); result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage()); } catch (IOException e) { log.error("Notification via Microblog failed!", e); result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage()); } return result; }
From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java
License:Educational Community License
/** * {@inheritDoc}/*from w ww.j a v a 2s .c o m*/ */ public String getTwitterName(ExternalIntegrationInfo info) { if (info == null) { return null; } //get values String token = info.getTwitterToken(); String secret = info.getTwitterSecret(); if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) { //global config Map<String, String> config = getTwitterOAuthConsumerDetails(); //token for user AccessToken accessToken = new AccessToken(token, secret); //setup TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); twitter.setOAuthAccessToken(accessToken); //check try { return twitter.verifyCredentials().getScreenName(); } catch (TwitterException e) { log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage()); } } return null; }
From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java
License:Educational Community License
/** * {@inheritDoc}//from www . j a va 2 s . co m */ public void sendMessageToTwitter(final String userUuid, String message) { //setup class thread to call later class TwitterUpdater implements Runnable { private Thread runner; private String userUuid; private String userToken; private String userSecret; private String message; public TwitterUpdater(String userUuid, String userToken, String userSecret, String message) { this.userUuid = userUuid; this.userToken = userToken; this.userSecret = userSecret; this.message = message; runner = new Thread(this, "Profile2 TwitterUpdater thread"); runner.start(); } //do it! public synchronized void run() { //global config Map<String, String> config = getTwitterOAuthConsumerDetails(); //token for user AccessToken accessToken = new AccessToken(userToken, userSecret); //setup TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); twitter.setOAuthAccessToken(accessToken); try { twitter.updateStatus(message); log.info("Twitter status updated for: " + userUuid); //post update event sakaiProxy.postEvent(ProfileConstants.EVENT_TWITTER_UPDATE, "/profile/" + userUuid, true); } catch (TwitterException e) { log.error( "ProfileLogic.sendMessageToTwitter() failed. " + e.getClass() + ": " + e.getMessage()); } } } //is twitter enabled if (!sakaiProxy.isTwitterIntegrationEnabledGlobally()) { return; } //get user info ExternalIntegrationInfo info = getExternalIntegrationInfo(userUuid); String token = info.getTwitterToken(); String secret = info.getTwitterSecret(); if (StringUtils.isBlank(token) || StringUtils.isBlank(secret)) { return; } //PRFL-423 limit to 140 chars //Hardcoded limit because 140 is the Twitter requirement so no need to make configurable message = ProfileUtils.truncate(message, 140, false); //instantiate class to send the data new TwitterUpdater(userUuid, token, secret, message); }
From source file:org.sakaiproject.profile2.tool.pages.panels.TwitterPrefsPane.java
License:Educational Community License
/** * Helper to get and set the Twitter request token we need for linking accounts *//*from w ww . ja v a2 s .com*/ private void setTwitterRequestToken() { Map<String, String> config = externalIntegrationLogic.getTwitterOAuthConsumerDetails(); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { e.printStackTrace(); } }
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// ww w . jav a2s .co 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; }