Example usage for twitter4j TwitterException exceededRateLimitation

List of usage examples for twitter4j TwitterException exceededRateLimitation

Introduction

In this page you can find the example usage for twitter4j TwitterException exceededRateLimitation.

Prototype

public boolean exceededRateLimitation() 

Source Link

Document

Tests if the exception is caused by rate limitation exceed

Usage

From source file:aic2013.follower.TwitterDataAccess.java

public void forAllFriendIds(TwitterUser twitterUser, Processor<Long> processor) {
    long nextCursor = -1;
    IDs usersResponse = null;/*from  w ww.j  a  v a2  s.com*/

    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.revolucion.secretwit.twitter.TwitterClient.java

License:Open Source License

private String findExceptionCause(TwitterException exception) {
    if (exception.exceededRateLimitation())
        return "Rate limitation exceeded.";

    if (exception.isCausedByNetworkIssue())
        return "Network issue.";

    if (exception.resourceNotFound())
        return "Resource not found.";

    return exception.getMessage() + " " + exception.getExceptionCode();
}

From source file:DataCollections.UserTimeLineCollection.java

public void collect_InsertTimeLineOfUser(User_dbo user) throws InterruptedException {

    Paging p = new Paging();
    int count = 20;
    p.setCount(count);/*  w  ww.j  av  a  2  s  .  c o m*/
    long max_id, since_id;
    int totaltweets = 0;
    long timestamp = -1;
    int nooftweets = 0;
    if (user.values[User_dbo.map.get("max_id")].used) {
        max_id = user.values[User_dbo.map.get("max_id")].lnumber;
        p.setMaxId(max_id);
    } else {
        max_id = -1;
    }
    if (user.values[User_dbo.map.get("since_id")].used) {
        since_id = user.values[User_dbo.map.get("since_id")].lnumber;
    } else {
        since_id = -1;
    }

    ResponseList<Status> statuses = null;
    boolean available = true;
    while (available) {

        try {
            LogPrinter.printLog("Retrieving some more tweets....");
            statuses = timelinesres.getUserTimeline(user.values[User_dbo.map.get("user_id")].lnumber, p);
        } catch (Exception e) {
            e.printStackTrace();
            TwitterException te = (TwitterException) e;
            if (te.exceededRateLimitation()) {
                LogPrinter.printLog("Rate Limited Reached.. Sleeping.. for ms " + 900 * 1000);
                Thread.sleep(900 * 1000 + 500);
            } else {

                return;
            }

        }
        totaltweets += statuses.size();
        if (statuses.isEmpty()) {
            LogPrinter.printLog("All tweets are retrieved....");
            available = false;
            continue;

        }
        ListIterator li = statuses.listIterator();
        while (li.hasNext()) {
            Status s = (Status) li.next();
            if (since_id < 0 && nooftweets == 0) {
                since_id = s.getId();
            }
            Tweet_dbo tweet = tweethelper.convertStatusToTweet_dbo(s);
            Tweet_dbo[] currentweets = TweetsTable
                    .select(" tweet_id = " + tweet.values[Tweet_dbo.map.get("tweet_id")].lnumber, 0, 2);
            if (currentweets.length == 0) {
                tweet.values[Tweet_dbo.map.get("processed")].setValue("true");
                tweet.values[Tweet_dbo.map.get("f_usertimeline")].setValue("true");
                TweetsTable.insert(tweet);
                useredgecollections.extract_InsertUsers_EdgesFromTweet(s);
                nooftweets++;
                LogPrinter.printLog("Inserting a new tweet.." + nooftweets);
            } else {
                LogPrinter.printLog("This tweet already exists in the database...");
            }
        }
        if (!statuses.isEmpty()) {
            max_id = ((Status) statuses.get(statuses.size() - 1)).getId();
            p.setMaxId(max_id);
        }
        if (totaltweets > 250) {
            LogPrinter.printLog("No of tweets collected reached goal....");
            available = false;
            continue;

        }

    }
    LogPrinter.printLog(String.valueOf(max_id));
    LogPrinter.printLog(String.valueOf(since_id));
    if (since_id > 0 && max_id > 0) {
        boolean selected[] = new boolean[User_dbo.nooffields];
        selected[User_dbo.map.get("max_id")] = true;
        selected[User_dbo.map.get("since_id")] = true;
        selected[User_dbo.map.get("utimeline_processed")] = true;
        user.values[User_dbo.map.get("max_id")].setValue(String.valueOf(max_id));
        user.values[User_dbo.map.get("since_id")].setValue(String.valueOf(since_id));
        user.values[User_dbo.map.get("utimeline_processed")].setValue("true");
        UsersTable.update(user, selected, " user_id =  " + user.values[User_dbo.map.get("user_id")].lnumber);
    }

}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * @return a message describing the problem with twitter or an empty string
 * if nothing related to twitter!/*  w  w w  .  ja v  a2 s.c  om*/
 */
public static String getMessage(Exception ex) {
    String msg = ex.getMessage() == null ? "" : ex.getMessage();
    if (msg.length() > 100)
        msg = msg.substring(0, 100);
    if (ex instanceof TwitterException) {
        TwitterException twExc = (TwitterException) ex;
        if (twExc.exceededRateLimitation())
            return "Couldn't process your request. You don't have enough twitter API points!" + " Please wait: "
                    + twExc.getRetryAfter() + " seconds and try again! " + msg;
        else if (twExc.isCausedByNetworkIssue())
            return "Couldn't process your request. Network issue." + msg;

        return "Couldn't process your request. Something went wrong while communicating with Twitter :-/ "
                + msg;
    } else if (ex != null)
        return msg;

    return "";
}

From source file:de.jetwick.bot.Jetwot.java

License:Apache License

public void start(int cycles, long interval) {
    init();/*from   w  w w .  j a  va2  s.c  om*/

    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.jetwick.tw.TwitterSearch.java

License:Apache License

public List<JTweet> getTweets(JUser user, int start, int tweets) throws TwitterException {
    List<JTweet> res = new ArrayList<JTweet>();
    int currentPage = start / tweets;

    if (tweets > 100)
        throw new IllegalStateException("Twitter does not allow more than 100 tweets per page!");

    if (tweets == 0)
        throw new IllegalStateException("tweets should be positive!");

    for (int trial = 0; trial < 2; trial++) {
        try {/* w  ww.  j  a  va 2  s. c o m*/
            ResponseList rList = twitter.getUserTimeline(user.getScreenName(),
                    new Paging(currentPage + 1, tweets, 1));
            rateLimit--;
            for (Object st : rList) {
                Tweet tw = toTweet((Status) st);
                res.add(new JTweet(tw, user.init(tw)));
            }
            break;
        } catch (TwitterException ex) {
            logger.warn("Exception while getTweets. trial:" + trial + " page:" + currentPage + " - "
                    + Helper.getMsg(ex));
            if (ex.exceededRateLimitation())
                return res;

            continue;
        }
    }

    return res;
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

/**
 * @return a message describing the problem with twitter or an empty string
 * if nothing related to twitter!//from   www .j  av  a2s  .c  o  m
 */
public static String getMessage(Exception ex) {
    if (ex instanceof TwitterException) {
        TwitterException twExc = (TwitterException) ex;
        if (twExc.exceededRateLimitation())
            return ("Couldn't process your request. You don't have enough twitter API points!"
                    + " Please wait: " + twExc.getRetryAfter() + " seconds and try again!");
        else if (twExc.isCausedByNetworkIssue())
            return ("Couldn't process your request. Network issue.");
        else
            return ("Couldn't process your request. Something went wrong while communicating with Twitter :-/");
    }

    return "";
}

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 www  .j a  v a 2s. co m*/
            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;/*  w ww  .  j a v  a2  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:jp.gr.java_conf.ya.shiobeforandroid3.UpdateTweetMultiple.java

License:Open Source License

private final void tweet(final String index, final String screenName, final String str1, final String str2,
        final String str3) throws TwitterException {

    last_edited_editText.setEnabled(false);

    pref_app = PreferenceManager.getDefaultSharedPreferences(this);

    final String tweetstr = StringUtil.getTweetString(adapter.getTweetHeader(pref_app, str1), str2,
            adapter.getTweetfooter(pref_app, str3));
    if (tweetstr.equals("")) {
        adapter.toast(getString(R.string.empty_tweettext));
        return;/*from  w w w. j  a  v a2 s. com*/
    }

    try {
        adapter.getTwitter(adapter.checkIndexFromPrefTwtr(), false).updateStatus(new StatusUpdate(tweetstr));
        adapter.toast(getString(R.string.done_tweet) + ": " + tweetstr + System.getProperty("line.separator")
                + System.getProperty("line.separator") + "[@" + screenName + "]");
        last_edited_editText.setEnabled(true);

        final boolean pref_enable_ringtone_ontweet = pref_app.getBoolean("pref_enable_ringtone_ontweet", true);
        final String pref_ringtone_ontweet_updatetweetmultiple = pref_app
                .getString("pref_ringtone_ontweet_updatetweetmultiple", "");
        if (pref_enable_ringtone_ontweet && (pref_ringtone_ontweet_updatetweetmultiple != null)
                && (pref_ringtone_ontweet_updatetweetmultiple.equals("") == false)) {
            final MediaPlayer mediaPlayer = MediaPlayer.create(UpdateTweetMultiple.this,
                    Uri.parse(pref_ringtone_ontweet_updatetweetmultiple));
            mediaPlayer.setLooping(false);
            mediaPlayer.seekTo(0);
            mediaPlayer.start();
        }
    } catch (final TwitterException e) {
        if (e.exceededRateLimitation()) {
            try {
                adapter.getTwitter(adapter.checkIndexFromPrefTwtr(1), false)
                        .updateStatus(new StatusUpdate(tweetstr));
                adapter.toast(
                        getString(R.string.done_tweet) + ": " + tweetstr + System.getProperty("line.separator")
                                + System.getProperty("line.separator") + "[@" + screenName + "]");
                last_edited_editText.setEnabled(true);
            } catch (final TwitterException e1) {
            }
        }
        adapter.toast(getString(R.string.cannot_access_twitter));
    } catch (final Exception e) {
        adapter.toast(getString(R.string.exception));
    }
    return;
}