List of usage examples for twitter4j TwitterException getMessage
@Override
public String getMessage()
From source file:net.firejack.platform.web.security.twitter.BaseTwitterAuthenticationProcessor.java
License:Apache License
protected AuthenticationToken getOpenFlameToken(Twitter twitterService, String browserIpAddress) throws TwitterException { try {/*from w w w . j a v a2 s . c o m*/ Map<String, String> mappedAttributes = getTwitterUserInformation(twitterService); ServiceResponse<AuthenticationToken> response = OPFEngine.AuthorityService .processTwitterIdSignIn(twitterService.getId(), mappedAttributes, browserIpAddress); AuthenticationToken token; if (response == null) { throw new IllegalStateException("API Service response should not be null."); } else if (response.isSuccess()) { token = response.getItem(); } else { logger.error("API Service response has failure status. Reason: " + response.getMessage()); token = null; } return token; } catch (TwitterException e) { logger.error( "Failed to obtain opf authentication token. Precondition failed, reason: " + e.getMessage()); throw 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 w w . ja v 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()); } } } }
From source file:nz.co.lolnet.james137137.lolnettwitchaddonbc.TwitterAPI.java
public List<Status> getLatestStatus() { List<Status> twitchTweets = new ArrayList<>(); try {// ww w . j a v a2s . c o m Query query = new Query("lolnetNZ twitch.tv"); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { if (tweet.getUser().getId() == 495479479 && tweet.getSource().contains("http://www.twitch.tv")) { twitchTweets.add(tweet); } } } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); } return twitchTweets; }
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** * Entry point for a Lappsgrid service.// ww w . j a v a2 s . c o m * <p> * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container} * payload. * <p> * Errors and exceptions that occur during processing should be wrapped in a {@code Data} * object with the discriminator set to http://vocab.lappsgrid.org/ns/error * <p> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br /> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br /> * * @param input A JSON string representing a Data object * @return A JSON string containing a Data object with a Container payload. */ @Override public String execute(String input) { Data<String> data = Serializer.parse(input, Data.class); String discriminator = data.getDiscriminator(); // Return ERRORS back if (Discriminators.Uri.ERROR.equals(discriminator)) { return input; } // Generate an error if the used discriminator is wrong if (!Discriminators.Uri.GET.equals(discriminator)) { return generateError( "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator); } Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false) .build(); // Authentication using saved keys Twitter twitter = new TwitterFactory(config).getInstance(); String key = readProperty(KEY_PROPERTY); if (key == null) { return generateError("The Twitter Consumer Key property has not been set."); } String secret = readProperty(SECRET_PROPERTY); if (secret == null) { return generateError("The Twitter Consumer Secret property has not been set."); } twitter.setOAuthConsumer(key, secret); try { twitter.getOAuth2Token(); } catch (TwitterException te) { String errorData = generateError(te.getMessage()); logger.error(errorData); return errorData; } // Get query String from data payload Query query = new Query(data.getPayload()); // Set the type to Popular or Recent if specified // Results will be Mixed by default. if (data.getParameter("type") == "Popular") query.setResultType(Query.POPULAR); if (data.getParameter("type") == "Recent") query.setResultType(Query.RECENT); // Get lang string String langCode = (String) data.getParameter("lang"); // Verify the validity of the language code and add it to the query if it's valid if (validateLangCode(langCode)) query.setLang(langCode); // Get date strings String sinceString = (String) data.getParameter("since"); String untilString = (String) data.getParameter("until"); // Verify the format of the date strings and set the parameters to query if correctly given if (validateDateFormat(untilString)) query.setUntil(untilString); if (validateDateFormat(sinceString)) query.setSince(sinceString); // Get GeoLocation if (data.getParameter("address") != null) { String address = (String) data.getParameter("address"); double radius = (double) data.getParameter("radius"); if (radius <= 0) radius = 10; Query.Unit unit = Query.MILES; if (data.getParameter("unit") == "km") unit = Query.KILOMETERS; GeoLocation geoLocation; try { double[] coordinates = getGeocode(address); geoLocation = new GeoLocation(coordinates[0], coordinates[1]); } catch (Exception e) { String errorData = generateError(e.getMessage()); logger.error(errorData); return errorData; } query.geoCode(geoLocation, radius, String.valueOf(unit)); } // Get the number of tweets from count parameter, and set it to default = 15 if not specified int numberOfTweets; try { numberOfTweets = (int) data.getParameter("count"); } catch (NullPointerException e) { numberOfTweets = 15; } // Generate an ArrayList of the wanted number of tweets, and handle possible errors. // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed ArrayList<Status> allTweets; Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter); String tweetsDataDisc = tweetsData.getDiscriminator(); if (Discriminators.Uri.ERROR.equals(tweetsDataDisc)) return tweetsData.asPrettyJson(); else { allTweets = (ArrayList<Status>) tweetsData.getPayload(); } // Initialize StringBuilder to hold the final string StringBuilder builder = new StringBuilder(); // Append each Status (each tweet) to the initialized builder for (Status status : allTweets) { String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : " + status.getText() + "\n"; builder.append(single); } // Output results Container container = new Container(); container.setText(builder.toString()); Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container); return output.asPrettyJson(); }
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** Contacts the Twitter API and gets any number of tweets corresponding to a certain query. The main * purpose of this function is to avoid the limit of 100 tweets that can be extracted at once. * * @param numberOfTweets the number of tweets to be printed * @param query the query to be searched by the twitter client * @param twitter the twitter client//from www . j ava 2 s. co m * * @return A JSON string containing a Data object with either a list containing the tweets as a payload * (when successful) or a String payload (for errors). */ private Data getTweetsByCount(int numberOfTweets, Query query, Twitter twitter) { ArrayList<Status> tweets = new ArrayList<>(); if (!(numberOfTweets > 0)) { // Default of 15 tweets numberOfTweets = 15; } // Set the last ID to the maximum possible value as a default long lastID = Long.MAX_VALUE; int original; try { while (tweets.size() < numberOfTweets) { // Keep number of original to avoid infinite looping when not getting enough tweets original = tweets.size(); // If there are more than 100 tweets left to be extracted, extract // 100 during the next query, since 100 is the limit to retrieve at once if (numberOfTweets - tweets.size() > 100) query.setCount(100); else query.setCount(numberOfTweets - tweets.size()); // Extract tweets corresponding to the query then add them to the list QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); // Iterate through the list and get the lastID to know where to start from // if there are more tweets to be extracted for (Status status : tweets) if (status.getId() < lastID) lastID = status.getId(); query.setMaxId(lastID - 1); // Break the loop if the tweet count didn't change. This would prevent an infinite loop when // tweets for the specified query are not available if (tweets.size() == original) break; } } catch (TwitterException te) { // Put the list of tweets in Data format then output as JSon String. // Since we checked earlier for errors, we assume that an error occuring at this point due // to Rate Limits is caused by a too high request. Thus, we output the retrieved tweets and log // the error String errorDataJson = generateError(te.getMessage()); logger.error(errorDataJson); if (te.exceededRateLimitation() && tweets.size() > 0) { Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } else { return Serializer.parse(errorDataJson, Data.class); } } // Return a special error message if no tweets are found if (tweets.size() == 0) { String noTweetsMessage = "No tweets found for the following query. " + "Note: Twitter's REST API only retrieves tweets from the past week."; String errorDataJson = generateError(noTweetsMessage); return Serializer.parse(errorDataJson, Data.class); } else { // Put the list of tweets in Data format then output as JSon String. Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } }
From source file:org.apache.blur.demo.twitter.Whiteboard.java
License:Apache License
/** * @param args/*from w ww .ja v a2 s. c o m*/ * @throws TwitterException */ public static void main(String[] args) throws TwitterException { Twitter twitter = new TwitterFactory(new ConfigurationBuilder().build()).getInstance(); OAuth2Token token = twitter.getOAuth2Token(); System.out.println(token.getTokenType()); try { Query query = new Query("Apache"); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }
From source file:org.apache.streams.twitter.provider.TwitterErrorHandler.java
License:Apache License
public static int handleTwitterError(Twitter twitter, Exception exception) { if (exception instanceof TwitterException) { TwitterException e = (TwitterException) exception; if (e.exceededRateLimitation()) { LOGGER.warn("Rate Limit Exceeded"); try { Thread.sleep(retry); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); }//from ww w .j a va2 s .c om return 1; } else if (e.isCausedByNetworkIssue()) { LOGGER.info("Twitter Network Issues Detected. Backing off..."); LOGGER.info("{} - {}", e.getExceptionCode(), e.getLocalizedMessage()); try { Thread.sleep(retry); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return 1; } else if (e.isErrorMessageAvailable()) { if (e.getMessage().toLowerCase().contains("does not exist")) { LOGGER.warn("User does not exist..."); return 100; } else { return 1; } } else { if (e.getExceptionCode().equals("ced778ef-0c669ac0")) { // This is a known weird issue, not exactly sure the cause, but you'll never be able to get the data. return 5; } else { LOGGER.warn("Unknown Twitter Exception..."); LOGGER.warn(" Account: {}", twitter); LOGGER.warn(" Access: {}", e.getAccessLevel()); LOGGER.warn(" Code: {}", e.getExceptionCode()); LOGGER.warn(" Message: {}", e.getLocalizedMessage()); return 1; } } } else if (exception instanceof RuntimeException) { LOGGER.warn("TwitterGrabber: Unknown Runtime Error", exception.getMessage()); return 1; } else { LOGGER.info("Completely Unknown Exception: {}", exception); return 1; } }
From source file:org.apache.streams.twitter.provider.TwitterFriendsProviderTask.java
License:Apache License
protected void getFriends(Long id) { int keepTrying = 0; long curser = -1; do {//from w w w . j a v a 2 s . co m try { twitter4j.User follower4j; String followerJson; try { follower4j = client.users().showUser(id); followerJson = TwitterObjectFactory.getRawJSON(follower4j); } catch (TwitterException e) { LOGGER.error("Failure looking up " + id); break; } PagableResponseList<User> followeeList = client.friendsFollowers().getFriendsList(id.longValue(), curser); for (twitter4j.User followee4j : followeeList) { String followeeJson = TwitterObjectFactory.getRawJSON(followee4j); try { Follow follow = new Follow() .withFollowee( mapper.readValue(followeeJson, org.apache.streams.twitter.pojo.User.class)) .withFollower( mapper.readValue(followerJson, org.apache.streams.twitter.pojo.User.class)); ComponentUtils.offerUntilSuccess(new StreamsDatum(follow), provider.providerQueue); } catch (JsonParseException e) { LOGGER.warn(e.getMessage()); } catch (JsonMappingException e) { LOGGER.warn(e.getMessage()); } catch (IOException e) { LOGGER.warn(e.getMessage()); } } curser = followeeList.getNextCursor(); } catch (TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch (Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } while (curser != 0 && keepTrying < 10); }
From source file:org.apache.streams.twitter.provider.TwitterFriendsProviderTask.java
License:Apache License
protected void getFriends(String screenName) { int keepTrying = 0; long curser = -1; do {//from ww w . j a v a2 s . com try { twitter4j.User follower4j; String followerJson; try { follower4j = client.users().showUser(screenName); followerJson = TwitterObjectFactory.getRawJSON(follower4j); } catch (TwitterException e) { LOGGER.error("Failure looking up " + screenName); break; } PagableResponseList<User> followeeList = client.friendsFollowers().getFriendsList(screenName, curser); for (twitter4j.User followee4j : followeeList) { String followeeJson = TwitterObjectFactory.getRawJSON(followee4j); try { Follow follow = new Follow() .withFollowee( mapper.readValue(followeeJson, org.apache.streams.twitter.pojo.User.class)) .withFollower( mapper.readValue(followerJson, org.apache.streams.twitter.pojo.User.class)); ComponentUtils.offerUntilSuccess(new StreamsDatum(follow), provider.providerQueue); } catch (JsonParseException e) { LOGGER.warn(e.getMessage()); } catch (JsonMappingException e) { LOGGER.warn(e.getMessage()); } catch (IOException e) { LOGGER.warn(e.getMessage()); } } curser = followeeList.getNextCursor(); } catch (TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch (Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } while (curser != 0 && keepTrying < 10); }
From source file:org.apache.streams.twitter.provider.TwitterTimelineProvider.java
License:Apache License
private Collection<Long> retrieveIds(String[] screenNames) { Twitter client = getTwitterClient(); List<Long> ids = Lists.newArrayList(); try {/*from w w w .j ava2 s . c om*/ for (User tStat : client.lookupUsers(screenNames)) { ids.add(tStat.getId()); } } catch (TwitterException e) { LOGGER.error("Failure retrieving user details.", e.getMessage()); } return ids; }