List of usage examples for twitter4j TwitterException getMessage
@Override
public String getMessage()
From source file:org.kuali.mobility.conference.controllers.ConferenceController.java
License:Open Source License
@RequestMapping(value = "twitter-search", method = RequestMethod.GET) public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam, @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam); QueryResult result = null;/* w w w. j a v a 2 s .c om*/ query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01"); query.setCount(100); query.setResultType(Query.MIXED); String json = ""; List<String> tweetList = new ArrayList<String>(); try { result = twitter.search(query); } catch (TwitterException e) { System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage()); } String tweetInfo = ""; for (Status status : result.getTweets()) { tweetInfo = "{"; tweetInfo += "\"id\" : \"" + status.getId() + "\", "; tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", "; tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", "; tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", "; tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", "; tweetInfo += "\"status\" : \"" + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", "; tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\","; tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\""; tweetInfo += "}"; tweetList.add(tweetInfo); } json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]"; return new ResponseEntity<String>(json, HttpStatus.OK); }
From source file:org.loklak.api.cms.ProxyServlet.java
License:Open Source License
protected void process(HttpServletRequest request, HttpServletResponse response, Query post) throws ServletException, IOException { // parse arguments String url = post.get("url", ""); String screen_name = post.get("screen_name", ""); DAO.log("PROXY: called with screen_name=" + screen_name + ", url=" + url); if (screen_name.length() == 0 && (url.length() == 0 || screen_name.indexOf("twimg.com") < 0)) { response.sendError(503, "either attributes url or screen_name or both must be submitted"); return;/*from w w w. ja va 2 s .co m*/ } byte[] buffer = url.length() == 0 ? null : cache.get(url); if (buffer != null) DAO.log("PROXY: got url=" + url + " content from ram cache!"); UserEntry user = null; if (buffer == null && screen_name.length() > 0) { if (buffer == null && (url.length() == 0 || isProfileImage(url))) { // try to read it from the user profiles user = DAO.searchLocalUserByScreenName(screen_name); if (user != null) { buffer = user.getProfileImage(); if (buffer != null) DAO.log("PROXY: got url=" + url + " content from user profile bas64 cache!"); if (url.length() == 0) url = user.getProfileImageUrl(); cache.put(user.getProfileImageUrl(), buffer); } } } if (buffer == null && url.length() > 0) { // try to download the image buffer = ClientConnection.download(url); String newUrl = user == null ? null : user.getProfileImageUrl(); if (buffer != null) { DAO.log("PROXY: downloaded given url=" + url + " successfully!"); } else if (newUrl != null && !newUrl.equalsIgnoreCase(url)) { // if this fails, then check if the stored url is different. // That may happen because new user avatar images get new urls buffer = ClientConnection.download(newUrl); if (buffer != null) DAO.log("PROXY: downloaded url=" + url + " from old user setting successfully!"); } if (buffer == null) { // ask the Twitter API for new user data try { JSONObject usermap = TwitterAPI.getUser(screen_name, true); newUrl = usermap.has("profile_image_url") ? (String) usermap.get("profile_image_url") : null; if (newUrl != null && newUrl.length() > 0 && !newUrl.startsWith("http:") && usermap.has("profile_image_url_https")) newUrl = (String) usermap.get("profile_image_url_https"); if (newUrl != null && newUrl.length() > 0) buffer = ClientConnection.download(newUrl); if (buffer != null) DAO.log("PROXY: downloaded url=" + url + " from recently downloaded user setting successfully!"); } catch (TwitterException e) { DAO.log("ProxyServlet: call to twitter api failed: " + e.getMessage()); } } if (buffer != null) { // write the buffer if (user != null) { user.setProfileImageUrl(newUrl); user.setProfileImage(buffer); try { // record user into search index DAO.users.writeEntry(new IndexEntry<UserEntry>(user.getScreenName(), user.getType(), user)); } catch (IOException e) { Log.getLog().warn(e); } if (!cache.full()) cache.put(url, buffer); } else { cache.put(url, buffer); } } } if (buffer == null) { if (screen_name.length() == 0) { response.sendError(503, "url cannot be loaded"); return; } if (url.length() == 0) { response.sendError(503, "user cannot be found"); return; } response.sendError(503, "url cannot be loaded and user cannot be found"); return; } if (url.endsWith(".png") || (url.length() == 0 && request.getServletPath().endsWith(".png"))) post.setResponse(response, "image/png"); else if (url.endsWith(".gif") || (url.length() == 0 && request.getServletPath().endsWith(".gif"))) post.setResponse(response, "image/gif"); else if (url.endsWith(".jpg") || url.endsWith(".jpeg") || (url.length() == 0 && request.getServletPath().endsWith(".jpg"))) post.setResponse(response, "image/jpeg"); else post.setResponse(response, "application/octet-stream"); ServletOutputStream sos = response.getOutputStream(); sos.write(buffer); post.finalize(); }
From source file:org.loklak.api.server.ProxyServlet.java
License:Open Source License
protected void process(HttpServletRequest request, HttpServletResponse response, RemoteAccess.Post post) throws ServletException, IOException { // parse arguments String url = post.get("url", ""); String screen_name = post.get("screen_name", ""); DAO.log("PROXY: called with screen_name=" + screen_name + ", url=" + url); if (screen_name.length() == 0 && (url.length() == 0 || screen_name.indexOf("twimg.com") < 0)) { response.sendError(503, "either attributes url or screen_name or both must be submitted"); return;//from w w w . j ava 2s . c om } byte[] buffer = url.length() == 0 ? null : cache.get(url); if (buffer != null) DAO.log("PROXY: got url=" + url + " content from ram cache!"); UserEntry user = null; if (buffer == null && screen_name.length() > 0) { if (buffer == null && (url.length() == 0 || isProfileImage(url))) { // try to read it from the user profiles user = DAO.searchLocalUserByScreenName(screen_name); if (user != null) { buffer = user.getProfileImage(); if (buffer != null) DAO.log("PROXY: got url=" + url + " content from user profile bas64 cache!"); if (url.length() == 0) url = user.getProfileImageUrl(); cache.put(user.getProfileImageUrl(), buffer); } } } if (buffer == null && url.length() > 0) { // try to download the image buffer = ClientConnection.download(url); String newUrl = user == null ? null : user.getProfileImageUrl(); if (buffer != null) { DAO.log("PROXY: downloaded given url=" + url + " successfully!"); } else if (newUrl != null && !newUrl.equalsIgnoreCase(url)) { // if this fails, then check if the stored url is different. // That may happen because new user avatar images get new urls buffer = ClientConnection.download(newUrl); if (buffer != null) DAO.log("PROXY: downloaded url=" + url + " from old user setting successfully!"); } if (buffer == null) { // ask the Twitter API for new user data try { Map<String, Object> usermap = TwitterAPI.getUser(screen_name, true); newUrl = (String) usermap.get("profile_image_url"); if (newUrl != null && newUrl.length() > 0 && !newUrl.startsWith("http:")) newUrl = (String) usermap.get("profile_image_url_https"); if (newUrl != null && newUrl.length() > 0) buffer = ClientConnection.download(newUrl); if (buffer != null) DAO.log("PROXY: downloaded url=" + url + " from recently downloaded user setting successfully!"); } catch (TwitterException e) { DAO.log("ProxyServlet: call to twitter api failed: " + e.getMessage()); } } if (buffer != null) { // write the buffer if (user != null && user.getType().length() > 0) { user.setProfileImageUrl(newUrl); user.setProfileImage(buffer); DAO.writeUser(user, user.getType(), false); if (!cache.full()) cache.put(url, buffer); } else { cache.put(url, buffer); } } } if (buffer == null) { if (screen_name.length() == 0) { response.sendError(503, "url cannot be loaded"); return; } if (url.length() == 0) { response.sendError(503, "user cannot be found"); return; } response.sendError(503, "url cannot be loaded and user cannot be found"); return; } if (url.endsWith(".png") || (url.length() == 0 && request.getServletPath().endsWith(".png"))) post.setResponse(response, "image/png"); else if (url.endsWith(".gif") || (url.length() == 0 && request.getServletPath().endsWith(".gif"))) post.setResponse(response, "image/gif"); else if (url.endsWith(".jpg") || url.endsWith(".jpeg") || (url.length() == 0 && request.getServletPath().endsWith(".jpg"))) post.setResponse(response, "image/jpeg"); else post.setResponse(response, "application/octet-stream"); ServletOutputStream sos = response.getOutputStream(); sos.write(buffer); post.finalize(); }
From source file:org.luwrain.app.twitter.Base.java
License:Open Source License
static boolean updateStatusImpl(Twitter twitter, String tweet) { NullCheck.notNull(twitter, "twitter"); NullCheck.notEmpty(tweet, "tweet"); try {//from w ww . j ava 2s . c om twitter.updateStatus(tweet); return true; } catch (TwitterException e) { Log.error("twitter", "unable to update status:" + e.getClass().getName() + ":" + e.getMessage()); e.printStackTrace(); return false; } }
From source file:org.manalith.ircbot.plugin.tweetreader.TweetReader.java
License:Open Source License
private String getText(String twitterurl, UrlType type) { if (type == null) return null; // init twitter4j try {/* w ww .jav a 2 s .co m*/ initTwitter4j(); } catch (TwitterException e) { return e.getMessage(); } if (StringUtils.isEmpty(config.getString("com.twitter.accessKey")) || StringUtils.isEmpty(config.getString("com.twitter.accessSecret"))) { try { authorizeTwitter(); } catch (TwitterException e) { return "[twitter4j.TwitterException] " + e.getMessage(); } catch (ConfigurationException e) { return "[org.apache.common.configuration.ConfigutaionException] " + e.getMessage(); } } else { String accessToken = config.getString("com.twitter.accessKey"); String accessSecret = config.getString("com.twitter.accessSecret"); setAcecssToken(accessToken, accessSecret); } Status stat = null; try { stat = getStatus(twitterurl, type); } catch (TwitterException e) { return "[twitter4j.TwitterException] " + e.getMessage(); } if (stat == null) return null; String author = stat.getUser().getName(); String createdAt = DateFormatUtils.format(stat.getCreatedAt(), TARGET_DATE_PATTERN); String message = stat.getText(); return String.format("?: %s, ?: %s, : %s", author, createdAt, message); }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ProcessRedirectFromTwitter.java
License:Apache License
/** {@inheritDoc} */ @Override/*from w w w . j a v a 2s. c om*/ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { /* Ensure we were passed the incoming HTTP request */ final HttpServletRequest servletRequest = getHttpServletRequest(); if (servletRequest == null) { log.debug("{} Profile action does not contain an HttpServletRequest", getLogPrefix()); ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS); return; } /* Obtain the Twitter Oauth verifier from the query string */ final String verifier = servletRequest.getParameter("oauth_verifier"); if (verifier == null || verifier.isEmpty()) { log.debug("{} No Twitter Oauth verifier in request", getLogPrefix()); ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS); return; } log.debug("{} Twitter returned verifier {}", getLogPrefix(), verifier); /* Query Twitter for the access token */ AccessToken accessToken = null; try { accessToken = this.twitterContext.getTwitter().getOAuthAccessToken(twitterContext.getRequestToken(), verifier); } catch (TwitterException e) { log.warn("{} exception obtaining access token from Twitter: {}", getLogPrefix(), e.getMessage()); ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS); return; } log.info("{} Login by '{}' succeeded", getLogPrefix(), accessToken.getUserId()); /* Attach the access token to the Twitter context */ this.twitterContext.setAccessToken(accessToken); /* Complete the authentication flow by building the authentication result */ buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); }
From source file:org.primefaces.examples.service.TwitterAPIService.java
License:Apache License
public List<Status> asyncSearch(String query) { TwitterListener listener = new TwitterAdapter() { @Override/*from w ww . j av a 2 s. c om*/ public void searched(QueryResult queryResult) { asyncTweets = queryResult.getTweets(); } @Override public void onException(TwitterException e, TwitterMethod method) { logger.severe(e.getMessage()); } }; AsyncTwitter twitter = new AsyncTwitterFactory().getInstance(); twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret)); twitter.addListener(listener); Query q = new Query(query); twitter.search(q); return asyncTweets; }
From source file:org.rhq.enterprise.server.plugins.alertMicroblog.MicroblogSender.java
License:Open Source License
@Override public SenderResult send(Alert alert) { SenderResult result;/*from w ww . j a v a 2s . c om*/ 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.richfaces.examples.tweetstream.dataserver.source.TwitterSourceLocal.java
License:Open Source License
@Override public void fetchContent() { //Check if updating content is needed //If not skip because this can be called on every page load System.out.println("&&&&&&&&&&& fetchContent\n\n\n\n\n"); if (false) {/*from w ww .j av a 2 s . c o m*/ // if (performSearch()) { twitterAggregate = new TwitterAggregate(); Twitter twitter = new TwitterFactory().getInstance(); List<twitter4j.Tweet> t4jTweets = null; try { Query query = new Query(TRACK); QueryResult result = twitter.search(query); t4jTweets = result.getTweets(); for (twitter4j.Tweet t4jTweet : t4jTweets) { log.info("@" + t4jTweet.getFromUser() + " - " + t4jTweet.getText()); //Create a local tweet object from the t4j Tweet tweet = new Tweet(); tweet.setText(t4jTweet.getText()); tweet.setId(t4jTweet.getFromUserId()); tweet.setProfileImageUrl(t4jTweet.getProfileImageUrl()); tweet.setScreenName(t4jTweet.getFromUser()); tweet.setHashTags(TwitterAggregateUtil.pullHashtags(t4jTweet.getText())); twitterAggregate = TwitterAggregateUtil.updateTwitterAggregate(tweet, twitterAggregate); } } catch (TwitterException te) { te.printStackTrace(); log.info("Failed to search tweets: " + te.getMessage()); } } } }
From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java
License:Educational Community License
/** * {@inheritDoc}//from w ww . ja v a2 s. 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; }