List of usage examples for twitter4j TwitterException getRateLimitStatus
@Override
public RateLimitStatus getRateLimitStatus()
From source file:aic2013.follower.TwitterDataAccess.java
public void forAllFriendIds(TwitterUser twitterUser, Processor<Long> processor) { long nextCursor = -1; IDs usersResponse = null;//from w w w.j a v a 2 s . c o m do { assert usersResponse == null; while (usersResponse == null) { if (!open) { throw new ClosedException(); } try { usersResponse = twitter.getFriendsIDs(twitterUser.getId(), nextCursor); } catch (TwitterException ex) { if (ex.exceededRateLimitation()) { waitForReset(ex.getRateLimitStatus().getSecondsUntilReset() * 1000); } else if (ex.resourceNotFound()) { // throw new RuntimeException("The user for which the friends were requested does not exist any more.", ex); return; } // Retry when other errors like IO-related ones occur } } assert usersResponse != null; nextCursor = usersResponse.getNextCursor(); for (long userId : usersResponse.getIDs()) { processor.process(userId); } usersResponse = null; } while (nextCursor > 0); }
From source file:com.javielinux.api.loaders.ListUserTwitterLoader.java
License:Apache License
@Override public BaseResponse loadInBackground() { try {/*from w w w . j a v a2s . co m*/ ListUserTwitterResponse response = new ListUserTwitterResponse(); ArrayList<InfoUsers> ar = new ArrayList<InfoUsers>(); ResponseList<User> users = ConnectionManager.getInstance().getTwitter(request.getUserId()) .searchUsers(request.getUser(), 0); for (int i = 0; i < users.size(); i++) { ar.add(new InfoUsers(users.get(i))); } response.setUsers(ar); return response; } catch (TwitterException e) { e.printStackTrace(); ErrorResponse errorResponse = new ErrorResponse(); RateLimitStatus rate = e.getRateLimitStatus(); if (rate != null) { errorResponse.setTypeError(Utils.LIMIT_ERROR); errorResponse.setRateError(rate); } else { errorResponse.setTypeError(Utils.UNKNOWN_ERROR); } errorResponse.setError(e, e.getMessage()); return errorResponse; } }
From source file:com.javielinux.database.EntitySearch.java
License:Apache License
public InfoSaveTweets saveTweets(Context cnt, boolean saveNotifications, long since_id) { ConnectionManager.getInstance().open(cnt); Twitter twitter = ConnectionManager.getInstance().getUserForSearchesTwitter(); InfoSaveTweets out = new InfoSaveTweets(); try {//from w w w . j a v a 2 s . co m int nResult = DataFramework.getInstance().getEntityListCount("tweets", "favorite=0 and search_id=" + getId()); Query query = getQuery(cnt); if (since_id != -1) query.setSinceId(since_id); QueryResult result = twitter.search(query); ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets(); if (tweets.size() > 0) { out.setNewMessages(tweets.size()); out.setNewerId(tweets.get(0).getId()); out.setOlderId(tweets.get(tweets.size() - 1).getId()); if (saveNotifications) { setValue("new_tweets_count", getInt("new_tweets_count") + tweets.size()); save(); } Log.d(Utils.TAG, tweets.size() + " mensajes nuevos en " + getString("name")); long fisrtId = 1; Cursor c = DataFramework.getInstance().getCursor("tweets", new String[] { DataFramework.KEY_ID }, null, null, null, null, DataFramework.KEY_ID + " desc", "1"); if (!c.moveToFirst()) { c.close(); fisrtId = 1; } else { long Id = c.getInt(0) + 1; c.close(); fisrtId = Id; } for (int i = tweets.size() - 1; i >= 0; i--) { /*String sql = "INSERT INTO 'tweets' (" + DataFramework.KEY_ID + ", search_id, url_avatar, username, user_id, tweet_id," + "text, source, to_username, to_user_id, date, favorite) VALUES (" + fisrtId + "," + getId() + ",'" +tweets.get(i).getProfileImageUrl() + "','"+tweets.get(i).getFromUser()+"','" + tweets.get(i).getFromUserId() + "','" + tweets.get(i).getId() + "','" + tweets.get(i).getText() + "','" + tweets.get(i).getSource() + "','"+tweets.get(i).getToUser() +"','"+tweets.get(i).getToUserId()+"','"+String.valueOf(tweets.get(i).getCreatedAt().getTime()) + "',0);\n";*/ User u = tweets.get(i).getUser(); ContentValues args = new ContentValues(); args.put(DataFramework.KEY_ID, "" + fisrtId); args.put("search_id", "" + getId()); if (u.getProfileImageURL() != null) { args.put("url_avatar", u.getProfileImageURL().toString()); } else { args.put("url_avatar", ""); } args.put("username", u.getScreenName()); args.put("fullname", u.getName()); args.put("user_id", "" + u.getId()); args.put("tweet_id", Utils.fillZeros("" + tweets.get(i).getId())); args.put("text", tweets.get(i).getText()); args.put("source", tweets.get(i).getSource()); args.put("to_username", tweets.get(i).getInReplyToScreenName()); args.put("to_user_id", "" + tweets.get(i).getInReplyToUserId()); args.put("date", String.valueOf(tweets.get(i).getCreatedAt().getTime())); if (tweets.get(i).getGeoLocation() != null) { args.put("latitude", tweets.get(i).getGeoLocation().getLatitude()); args.put("longitude", tweets.get(i).getGeoLocation().getLongitude()); } args.put("favorite", "0"); DataFramework.getInstance().getDB().insert("tweets", null, args); fisrtId++; } if (saveNotifications) { setValue("last_tweet_id_notifications", tweets.get(0).getId() + ""); save(); } int total = nResult + tweets.size(); if (total > Utils.MAX_ROW_BYSEARCH) { Log.d(Utils.TAG, "Limpiando base de datos"); String date = DataFramework.getInstance() .getEntityList("tweets", "favorite=0 and search_id=" + getId(), "date desc") .get(Utils.MAX_ROW_BYSEARCH).getString("date"); String sqldelete = "DELETE FROM tweets WHERE favorite=0 AND search_id=" + getId() + " AND date < '" + date + "'"; DataFramework.getInstance().getDB().execSQL(sqldelete); } } } catch (TwitterException e) { e.printStackTrace(); RateLimitStatus rate = e.getRateLimitStatus(); if (rate != null) { out.setError(Utils.LIMIT_ERROR); out.setRate(rate); } else { out.setError(Utils.UNKNOWN_ERROR); } } catch (Exception e) { e.printStackTrace(); out.setError(Utils.UNKNOWN_ERROR); } return out; }
From source file:de.fhb.twitalyse.spout.TwitterStreamSpout.java
License:Open Source License
@Override public void onException(Exception ex) { LOGGER.log(Level.SEVERE, null, ex); TwitterException tex = (TwitterException) ex; if (400 == tex.getStatusCode()) { close();// w w w. j a v a2s . c om LOGGER.log(Level.SEVERE, "Rate limit texceeded. Clients may not make more than {0} requests per hour. \nThe ntext reset is {1}", new Object[] { tex.getRateLimitStatus().getHourlyLimit(), tex.getRateLimitStatus().getResetTime() }); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (401 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Authentication credentials were missing or incorrect."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (403 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Duplicated status."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (404 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "The URI requested is invalid or the resource requested, such as a user, does not exists."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (406 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Request returned - invalid format is specified in the request."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (420 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Too many logins with your account in a short time."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (500 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Something is broken. Please post to the group so the Twitter team can investigate."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (502 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Twitter is down or being upgraded."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (503 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "The Twitter servers are up, but overloaded with requests. Try again later."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else if (-1 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Can not connect to the internet or the host is down."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } else { close(); LOGGER.log(Level.SEVERE, "Unknown twitter-error occured."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[] { tex, tex.getMessage(), tex.getCause() }); } }
From source file:de.jetwick.bot.Jetwot.java
License:Apache License
public void start(int cycles, long interval) { init();// ww w .j ava2s . c o m for (int i = 0; cycles < 0 || i < cycles; i++) { logger.info("tweet cache:" + tweetCache.size()); Collection<JTweet> newSearchedTweets = search(); JTweet selectedTweet = null; for (JTweet newSearchTw : newSearchedTweets) { command.calcTermsWithoutNoise(newSearchTw); if (newSearchTw.getTextTerms().size() >= 4) { float maxJc = -1; for (JTweet twInCache : tweetCache.values()) { float jcIndex = (float) TermCreateCommand.calcJaccardIndex(twInCache.getTextTerms(), newSearchTw.getTextTerms()); if (maxJc < jcIndex) maxJc = jcIndex; } if (maxJc < 0.2 || maxJc == -1) { selectedTweet = newSearchTw; logger.info("new tweet with max jacc index= " + maxJc + ":" + newSearchTw.getText()); break; } logger.info("skip tweet because max jacc index= " + maxJc + ":" + newSearchTw.getText()); } else { logger.info("skip tweet because too less terms= " + newSearchTw.getTextTerms().size() + " :" + newSearchTw.getText()); } } if (selectedTweet != null) { try { tw4j.doRetweet(selectedTweet.getTwitterId()); addToCaches(selectedTweet); logger.info("=> retweeted:" + selectedTweet.getText() + " " + selectedTweet.getTwitterId()); } catch (Exception ex) { logger.error("Couldn't retweet tweet:" + selectedTweet + " " + ex.getMessage()); if (ex instanceof TwitterException) { TwitterException ex2 = ((TwitterException) ex); if (ex2.exceededRateLimitation()) { logger.error("Remaining hits:" + ex2.getRateLimitStatus().getRemainingHits() + " wait some seconds:" + ex2.getRateLimitStatus().getResetTimeInSeconds()); } } } } // Create tweet for Trending URLS? // every 15 minutes check for new trending url. put title + url into cache // or even better facet over dt (every 20 minutes) and pick up the docs! // f.dest_title_1_s.facet.limit=20 // from this, calculate trend -> up coming urls (new tweets per hour that link to this url) // every 2 hours post a new trending url from cache with the highest up rate + over a certain number of tweets // do no overuse ratelimit ! // twitter.postTweet("'Title ABOUT XY' short.url/test"); try { // add some noise when waiting to avoid being identified or filtered out as bot ;-) long tmp = (long) (interval + interval * rand.nextDouble() * 0.3); logger.info("wait " + (tmp / 60f / 1000f) + " minutes => next tweet on: " + new MyDate().plusMillis(tmp)); Thread.sleep(tmp); } catch (InterruptedException ex) { logger.warn("Interrupted " + ex.getMessage()); break; } } }
From source file:de.vanita5.twittnuker.util.Utils.java
License:Open Source License
public static String getTwitterErrorMessage(final Context context, final CharSequence action, final TwitterException te) { if (context == null) return null; if (te == null) return context.getString(R.string.error_unknown_error); if (te.exceededRateLimitation()) { final RateLimitStatus status = te.getRateLimitStatus(); final long secUntilReset = status.getSecondsUntilReset() * 1000; final String nextResetTime = ParseUtils .parseString(getRelativeTimeSpanString(System.currentTimeMillis() + secUntilReset)); if (isEmpty(action)) return context.getString(R.string.error_message_rate_limit, nextResetTime.trim()); return context.getString(R.string.error_message_rate_limit_with_action, action, nextResetTime.trim()); } else if (te.getErrorCode() > 0) { final String msg = StatusCodeMessageUtils.getTwitterErrorMessage(context, te.getErrorCode()); return getErrorMessage(context, action, msg != null ? msg : trimLineBreak(te.getMessage())); } else if (te.getCause() instanceof SSLException) { final String msg = te.getCause().getMessage(); if (msg != null && msg.contains("!=")) return getErrorMessage(context, action, context.getString(R.string.ssl_error)); else//from w w w. ja v a 2 s . c om return getErrorMessage(context, action, context.getString(R.string.network_error)); } else if (te.getCause() instanceof IOException) return getErrorMessage(context, action, context.getString(R.string.network_error)); else if (te.getCause() instanceof JSONException) return getErrorMessage(context, action, context.getString(R.string.api_data_corrupted)); else return getErrorMessage(context, action, trimLineBreak(te.getMessage())); }
From source file:de.vanita5.twittnuker.util.Utils.java
License:Open Source License
public static void showTwitterErrorMessage(final Context context, final CharSequence action, final TwitterException te, final boolean long_message) { if (context == null) return;//from ww w. j a va 2 s. c o m final String message; if (te != null) { if (action != null) { if (te.exceededRateLimitation()) { final RateLimitStatus status = te.getRateLimitStatus(); final long sec_until_reset = status.getSecondsUntilReset() * 1000; final String next_reset_time = ParseUtils .parseString(getRelativeTimeSpanString(System.currentTimeMillis() + sec_until_reset)); message = context.getString(R.string.error_message_rate_limit_with_action, action, next_reset_time.trim()); } else if (isErrorCodeMessageSupported(te)) { final String msg = StatusCodeMessageUtils.getMessage(context, te.getStatusCode(), te.getErrorCode()); message = context.getString(R.string.error_message_with_action, action, msg != null ? msg : trimLineBreak(te.getMessage())); } else if (te.getCause() instanceof SSLException) { final String msg = te.getCause().getMessage(); if (msg != null && msg.contains("!=")) { message = context.getString(R.string.error_message_with_action, action, context.getString(R.string.ssl_error)); } else { message = context.getString(R.string.error_message_with_action, action, context.getString(R.string.network_error)); } } else if (te.getCause() instanceof IOException) { message = context.getString(R.string.error_message_with_action, action, context.getString(R.string.network_error)); } else { message = context.getString(R.string.error_message_with_action, action, trimLineBreak(te.getMessage())); } } else { message = context.getString(R.string.error_message, trimLineBreak(te.getMessage())); } } else { message = context.getString(R.string.error_unknown_error); } showErrorMessage(context, message, long_message); }
From source file:demo.UserFollowers.java
License:Apache License
static List<Long> followers(Twitter twitter, String screenName) { List<Long> m_FollowersList = new ArrayList<Long>(); long cursor = -1; //int count = 0; while (true) { IDs ids = null;//from w ww .j a v a2 s. co m try { //IDs ids = twitter.getFollowersIDs(user.getId(), cursor); ids = twitter.getFollowersIDs(screenName, cursor); } catch (TwitterException twitterException) { // Rate Limit ????????? // (memo) status code ????????? RateLimitStatus rateLimit = twitterException.getRateLimitStatus(); int secondsUntilReset = rateLimit.getSecondsUntilReset(); System.err.println("please wait for " + secondsUntilReset + " seconds"); System.err.println("Reset Time : " + rateLimit.getResetTimeInSeconds()); //() 120?getSecondsUntilReset() ????????????? // long waitTime = (long)(secondsUntilReset + 120) * 1000; long waitTime = (long) (300 * 1000); // 300 try { Thread.sleep(waitTime); } catch (Exception e) { e.printStackTrace(); } continue; } catch (Exception e) { e.printStackTrace(); } long[] idArray = ids.getIDs(); for (int i = 0; i < idArray.length; i++) { //System.out.println("["+(++count)+"]" + idArray[i]); m_FollowersList.add(new Long(idArray[i])); } if (ids.hasNext()) { cursor = ids.getNextCursor(); } else { break; } } return m_FollowersList; }
From source file:edu.uml.TwitterDataMining.TwitterConsumer.java
/** * Search twitter with the given search term Results will be saved in a file * with the same name as the query/*from w w w . j a va2 s . com*/ * * @param searchTerm The search term to be queried * @return a list of tweets */ public static List<Status> queryTwitter(String searchTerm) { Query query = new Query(searchTerm); query.setLang("en"); // we only want english tweets // get and format date to get tweets no more than a year old SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String date = sdf.format(new Date(System.currentTimeMillis() - (long) (365 * 24 * 60 * 60 * 1000))); query.setSince(date); QueryResult result; List<Status> tweets = null; try { //ONLY GETTING FIRST SET OF RESULTS result = twitter.search(query); tweets = result.getTweets(); // for (Status tweet : tweets) { // System.out.println("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText()); // } // Wait loop for reset } catch (TwitterException te) { try { // try block for sleep thread if (!te.isCausedByNetworkIssue()) { // Not really checking for anything else but it is likely that we are out of requests int resetTime = te.getRateLimitStatus().getSecondsUntilReset(); while (resetTime > 0) { Thread.sleep(1000); // 1 second stop System.out.println("seconds till reset: " + resetTime); --resetTime; } } else { te.printStackTrace(); } } catch (InterruptedException ie) { ie.printStackTrace(); System.exit(-1); } } return tweets; }
From source file:edu.uml.TwitterDataMining.TwitterConsumer.java
/** * Search a specific user name and get their most recent tweets. DO NOT * INCLUDE THE @ SYMBOL BEFORE USERNAME/*from w w w .ja v a 2 s . c om*/ * * @param Username * @return a list of tweets */ public static List<Status> queryTwitterUser(String Username) { List<Status> tweets = null; try { tweets = twitter.getUserTimeline(Username); // for (Status tweet : tweets) { // System.out.println("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText()); // } // Wait loop for reset } catch (TwitterException te) { try { // try block for sleep thread if (!te.isCausedByNetworkIssue()) { // Not really checking for anything else but it is likely that we are out of requests int resetTime = te.getRateLimitStatus().getSecondsUntilReset(); while (resetTime > 0) { Thread.sleep(1000); // 1 second stop System.out.println("seconds till reset: " + resetTime); --resetTime; } } else { te.printStackTrace(); } } catch (InterruptedException ie) { ie.printStackTrace(); System.exit(-1); } } return tweets; }