Example usage for twitter4j RateLimitStatus getLimit

List of usage examples for twitter4j RateLimitStatus getLimit

Introduction

In this page you can find the example usage for twitter4j RateLimitStatus getLimit.

Prototype

int getLimit();

Source Link

Document

Returns the current limit in effect
This value is identical to the "X-Rate-Limit-Limit" response header.

Usage

From source file:account.GetRateLimitStatus.java

License:Apache License

public static ConstVars getRateLimit(String[] args) {

    ConstVars StaticVars = new ConstVars();

    try {//from  w w  w.  j  a v a  2s.  c o m

        // init Twitter OAuth
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(args[1]).setOAuthConsumerSecret(args[2])
                .setOAuthAccessToken(args[3]).setOAuthAccessTokenSecret(args[4]);

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        // it returns RateLimits of all end-points
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();

        // get RateLimit of required end-point
        RateLimitStatus status = rateLimitStatus.get(args[0]);
        String Endpoint = args[0];
        int Limit = status.getLimit();

        int Remaining = status.getRemaining();
        int ResetTimeInSeconds = status.getResetTimeInSeconds();
        int SecondsUntilReset = status.getSecondsUntilReset();

        // set and return rate limit info to ConstVars's variables
        StaticVars.Endpoint = Endpoint;
        StaticVars.Limit = Limit;
        StaticVars.Remaining = Remaining;
        StaticVars.ResetTimeInSeconds = ResetTimeInSeconds;
        StaticVars.SecondsUntilReset = SecondsUntilReset;

    } catch (TwitterException te) {
        if (args.length == 6) {
            System.err
                    .println("Failed to get rate limit status of " + args[5] + " because: " + te.getMessage());
        } else {
            System.err.println("Failed to get rate limit status because: " + te.getMessage());
        }
    }
    return StaticVars;
}

From source file:Beans.Crawler.java

public String teste() {
    String result = "";
    int totalTweets = 0;
    long maxID = -1;

    GeoLocation geo = new GeoLocation(Double.parseDouble("-19.9225"), Double.parseDouble("-43.9450"));
    result += geo.getLatitude() + " " + geo.getLongitude() + "<br><br>";

    Twitter twitter = getTwitter();//from  w w  w .  j  a  v  a  2 s.c om

    try {
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

        result += "You have " + searchTweetsRateLimit.getRemaining() + " calls remaining out of "
                + searchTweetsRateLimit.getLimit() + ", Limit resets in "
                + searchTweetsRateLimit.getSecondsUntilReset() + " seconds<br/><br/>";

        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            //   Do we need to delay because we've already hit our rate limits?
            if (searchTweetsRateLimit.getRemaining() == 0) {
                //   Yes we do, unfortunately ...
                //                        System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());

                //   If you sleep exactly the number of seconds, you can make your query a bit too early
                //   and still get an error for exceeding rate limitations
                //
                //    Adding two seconds seems to do the trick. Sadly, even just adding one second still triggers a
                //   rate limit exception more often than not.  I have no idea why, and I know from a Comp Sci
                //   standpoint this is really bad, but just add in 2 seconds and go about your business.  Or else.
                //               Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset()+2) * 1000l);
            }

            Query q = new Query(SEARCH_TERM); //.geoCode((geo), 100, "mi");         // Search for tweets that contains this term
            q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve
            //                    q.setGeoCode(geo, 100, Query.Unit.mi);
            //                    q.setSince("2012-02-20");
            //                                
            //            q.resultType("recent");                  // Get all tweets
            //            q.setLang("en");                     // English language tweets, please

            //   If maxID is -1, then this is our first call and we do not want to tell Twitter what the maximum
            //   tweet id is we want to retrieve.  But if it is not -1, then it represents the lowest tweet ID
            //   we've seen, so we want to start at it-1 (if we start at maxID, we would see the lowest tweet
            //   a second time...
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }

            //   This actually does the search on Twitter and makes the call across the network
            QueryResult r = twitter.search(q);

            //   If there are NO tweets in the result set, it is Twitter's way of telling us that there are no
            //   more tweets to be retrieved.  Remember that Twitter's search index only contains about a week's
            //   worth of tweets, and uncommon search terms can run out of week before they run out of tweets
            if (r.getTweets().size() == 0) {
                break; // Nothing? We must be done
            }

            //   loop through all the tweets and process them.  In this sample program, we just print them
            //   out, but in a real application you might save them to a database, a CSV file, do some
            //   analysis on them, whatever...
            for (Status s : r.getTweets()) // Loop through all the tweets...
            {
                //   Increment our count of tweets retrieved
                totalTweets++;

                //   Keep track of the lowest tweet ID.  If you do not do this, you cannot retrieve multiple
                //   blocks of tweets...
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }
                //   Do something with the tweet....
                result += "ID: " + s.getId() + " Data " + s.getCreatedAt().toString() + " user "
                        + s.getUser().getScreenName() + " texto: " + cleanText(s.getText()) + "  <br/>";

            }

            //   As part of what gets returned from Twitter when we make the search API call, we get an updated
            //   status on rate limits.  We save this now so at the top of the loop we can decide whether we need
            //   to sleep or not before making the next call.
            searchTweetsRateLimit = r.getRateLimitStatus();
        }

    } catch (Exception e) {
        //   Catch all -- you're going to read the stack trace and figure out what needs to be done to fix it
    }
    result += "<br><br>" + totalTweets + "<br>";
    return result;
}

From source file:com.data.dataanalytics.twitter.TwitterFeed.java

public List<Tweet> getTweets(String search) {
    //   We're curious how many tweets, in total, we've retrieved.  Note that TWEETS_PER_QUERY is an upper limit,
    //   but Twitter can and often will retrieve far fewer tweets

    twitter4j.Twitter twitter = getTwitter();

    /*   This variable is the key to our retrieving multiple blocks of tweets.  In each batch of tweets we retrieve,
       we use this variable to remember the LOWEST tweet ID.  Tweet IDs are (java) longs, and they are roughly
       sequential over time.  Without setting the MaxId in the query, Twitter will always retrieve the most
       recent tweets.  Thus, to retrieve a second (or third or ...) batch of Tweets, we need to set the Max Id
       in the query to be one less than the lowest Tweet ID we've seen already.  This allows us to page backwards
       through time to retrieve additional blocks of tweets*/
    long maxID = -1;

    try {//www.  jav a 2  s. co m
        //   There are limits on how fast you can make API calls to Twitter, and if you have hit your limit
        //   and continue to make calls Twitter will get annoyed with you.  I've found that going past your
        //   limits now and then doesn't seem to be problematic, but if you have a program that keeps banging
        //   the API when you're not allowed you will eventually get shut down.
        //
        //   Thus, the proper thing to do is always check your limits BEFORE making a call, and if you have
        //   hit your limits sleeping until you are allowed to make calls again.
        //
        //   Every time you call the Twitter API, it tells you how many calls you have left, so you don't have
        //   to ask about the next call.  But before the first call, we need to find out whether we're already
        //   at our limit.

        //   This returns all the various rate limits in effect for us with the Twitter API
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");

        //   This finds the rate limit specifically for doing the search API call we use in this program
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

        //   Always nice to see these things when debugging code...
        System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(), searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());

        //   This is the loop that retrieve multiple blocks of tweets from Twitter
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
            //   Delay
            if (searchTweetsRateLimit.getRemaining() == 0) {
                System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                        searchTweetsRateLimit.getSecondsUntilReset());

                //   If you sleep exactly the number of seconds, you can make your query a bit too early
                //   and still get an error for exceeding rate limitations
                //
                //    Adding two seconds seems to do the trick. Sadly, even just adding one second still triggers a
                //   rate limit exception more often than not.  I have no idea why, and I know from a Comp Sci
                //   standpoint this is really bad, but just add in 2 seconds and go about your business.  Or else.
                Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
            }

            Query q = new Query(search); // Search for tweets that contains this term
            q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve
            //q.resultType("recent");                  // Get all tweets
            q.setLang("en"); // English language tweets, please

            //   If maxID is -1, then this is our first call and we do not want to tell Twitter what the maximum
            //   tweet id is we want to retrieve.  But if it is not -1, then it represents the lowest tweet ID
            //   we've seen, so we want to start at it-1 (if we start at maxID, we would see the lowest tweet
            //   a second time...
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }

            //   This actually does the search on Twitter and makes the call across the network
            QueryResult r = twitter.search(q);

            //   If there are NO tweets in the result set, it is Twitter's way of telling us that there are no
            //   more tweets to be retrieved.  Remember that Twitter's search index only contains about a week's
            //   worth of tweets, and uncommon search terms can run out of week before they run out of tweets
            if (r.getTweets().size() == 0) {
                break; // Nothing? We must be done
            }

            //   loop through all the tweets and process them. Need to save as CSV file for database
            for (Status s : r.getTweets()) { // Loop through all the tweets...
                //   Increment our count of tweets retrieved

                //   Keep track of the lowest tweet ID.  If you do not do this, you cannot retrieve multiple
                //   blocks of tweets...
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }

                //   Do something with the tweet....
                ta.processTweets(s, new Date());

            }

            //   As part of what gets returned from Twitter when we make the search API call, we get an updated
            //   status on rate limits.  We save this now so at the top of the loop we can decide whether we need
            //   to sleep or not before making the next call.
            searchTweetsRateLimit = r.getRateLimitStatus();
        }

    } catch (Exception e) {
        //   Catch all -- you're going to read the stack trace and figure out what needs to be done to fix it
        System.out.println("That didn't work well...wonder why?");

        e.printStackTrace();

    }

    System.out.printf("\n\nA total of %d tweets retrieved\n", ta.getTotalTweets());
    System.out.println("The total amount of tweets in an hour " + ta.getTweetsInAnHour());
    ta.checkIfTrending(ta.getTweetsInAnHour(), ta.getTotalTweets());

    return ta.getTweetList();
}

From source file:com.mobilesolutionworks.android.twitter.TwitterLimitDatabase.java

License:Apache License

public void updateAll(Map<String, RateLimitStatus> limits) {
    List<ContentValues> bulk = new ArrayList<ContentValues>(limits.size());
    for (String key : limits.keySet()) {
        RateLimitStatus status = limits.get(key);

        ContentValues object = new ContentValues();
        object.put("uri", key);
        object.put("limit", status.getLimit());
        object.put("remaining", status.getRemaining());
        object.put("reset", System.currentTimeMillis() + status.getSecondsUntilReset() * 1000);

        mDb.insert(TWITTER_LIMITS, null, object);
    }/*from  w w  w.  ja  v  a 2 s  .c  o m*/
}

From source file:com.mothsoft.integration.twitter.TwitterServiceImpl.java

License:Apache License

@SuppressWarnings("deprecation")
public List<Status> getHomeTimeline(AccessToken accessToken, Long sinceId, Short maximumNumber) {
    final Twitter twitter = this.factory.getInstance(accessToken);
    final List<Status> statuses = new ArrayList<Status>(maximumNumber);

    // default maximum number to 200 if null
    maximumNumber = maximumNumber == null ? 200 : maximumNumber;

    // default page size to lesser of maximumNumber, 200
    final int pageSize = maximumNumber > 200 ? 200 : maximumNumber;
    int page = 0;

    while (statuses.size() < maximumNumber) {
        Paging paging = new Paging(++page, pageSize);
        final ResponseList temp;

        if (sinceId != null) {
            paging = paging.sinceId(sinceId);
        }//from w w  w  . ja v  a2s.  co m

        try {
            temp = twitter.getHomeTimeline(paging);
        } catch (TwitterException e) {
            throw this.wrapException(e);
        }

        // break out as soon as we get a page smaller than the designated
        // page size
        if (temp.size() == 0) {
            break;
        } else {
            statuses.addAll(temp);
        }

        // check rate limit status and warn or skip remaining fetches as
        // appropriate
        final RateLimitStatus rateLimitStatus = temp.getRateLimitStatus();
        if (rateLimitStatus.getRemaining() < (.1 * rateLimitStatus.getLimit())) {
            logger.warn("Twitter rate limit approaching. Calls remaining: " + rateLimitStatus.getRemaining());
        }

        if (rateLimitStatus.getRemainingHits() == 0) {
            final Date resetTime = new Date(
                    System.currentTimeMillis() + (rateLimitStatus.getSecondsUntilReset() * 1000));

            logger.error("Twitter rate limit hit.  Will reset at: " + resetTime.toLocaleString());
            break;
        }
    }

    return statuses;
}

From source file:examples.GetRateLimitStatus.java

License:Apache License

public static void main(String[] args) {
    try {//from ww w  .jav  a2 s  . c  om

        Twitter twitter = CommonUtils.getTwitterInstance();

        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();
        for (String endpoint : rateLimitStatus.keySet()) {
            RateLimitStatus status = rateLimitStatus.get(endpoint);
            if (endpoint.equals("/users/lookup")) {
                System.out.println("Endpoint: " + endpoint);
                System.out.println(" Limit: " + status.getLimit());
                System.out.println(" Remaining: " + status.getRemaining());
                System.out.println(" ResetTimeInSeconds: " + status.getResetTimeInSeconds());
                System.out.println(" SecondsUntilReset: " + status.getSecondsUntilReset());
            }
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get rate limit status: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:mineTwit.Main.java

License:Open Source License

private void updateStatus(Twitter twitter, String newMessage) {
    if (twitter != null) {
        // Check newMessage
        try {/*ww  w.  j a  v  a  2s.  co  m*/
            // Debug code to check twitter rate limits
            Map<String, RateLimitStatus> rateLimit = twitter.getRateLimitStatus();
            for (String endpoint : rateLimit.keySet()) {
                RateLimitStatus status = rateLimit.get(endpoint);
                //Test line to remove later
                //getLogger().info("Got rateLimits.endpoints");
                //Omit any endpoints that haven't moved from default limit
                if (status.getRemaining() != status.getLimit()) {
                    getLogger().info("Endpoint: " + endpoint);
                    getLogger().info(" Limit: " + status.getLimit());
                    getLogger().info(" Remaining: " + status.getRemaining());
                    getLogger().info(" ResetTimeInSeconds: " + status.getResetTimeInSeconds());
                    getLogger().info(" SecondsUntilReset: " + status.getSecondsUntilReset());
                }
            }
            boolean rateLimited = false;
            //Test line for debugging
            getLogger().info(" Duplicate Array value is : " + myNotifications[8].status);
            // Check if rateLimited by any particular endpoint.
            if (!rateLimited) {
                //Tweet if duplicates are off AND not duplicate AND not rate limited
                if (myNotifications[8].status) {
                    getLogger().info("Duplicates are true.\n Who cares what the new message is.");
                    twitter.updateStatus(newMessage + "\n" + new Date());
                    // Tweet anyway if duplicates are on AND not ratelimited
                } else if (!myNotifications[8].status && !newMessage.equals(getCurrentStatus(twitter))) {
                    getLogger().info("Duplicates are false.");
                    getLogger().info("Latest is ''" + newMessage + "''");
                    getLogger().info("Last was ''" + getCurrentStatus(twitter) + "''");
                    twitter.updateStatus(newMessage + "\n" + new Date());
                } else {
                    getLogger().info("Duplicates are false and message is duplicate");
                }
            } else {
                getLogger().info("Twitter is rate limited, not tweeting");
            }
        } catch (TwitterException e) {
            getLogger().info("Twitter is broken because of " + e);
            throw new RuntimeException(e);
        }
    }
}

From source file:net.awairo.favdler.twitter.FavoriteListItems.java

License:MIT License

private void updateRateLimitStatus(RateLimitStatus status) {
    limit = status.getLimit();
    remaining = status.getRemaining();/*from  w w  w .j  a  v  a2 s.  co m*/
    resetTimeInSeconds = status.getResetTimeInSeconds();
    secondsUntilReset = status.getSecondsUntilReset();
}

From source file:ontoSentiment.Util.java

public static void imprimirRateLimit(String tipo) throws TwitterException {
    Map<String, RateLimitStatus> rateLimitStatusSearch = getTwitter().getRateLimitStatus(tipo.split("/")[1]);
    RateLimitStatus searchTweetsRateLimit = rateLimitStatusSearch.get(tipo);
    System.out.printf("Ainda restam %d requisies de %d, O limite reseta em %d minutos\n",
            searchTweetsRateLimit.getRemaining(), searchTweetsRateLimit.getLimit(),
            (searchTweetsRateLimit.getSecondsUntilReset() / 60));
}

From source file:tweetcrawling.Main.java

public static void getRateLimitStatuses(TwitterConfiguration tc_) {
    try {/* w ww. j  a  v a 2  s .  co  m*/
        //          Twitter twitter = new TwitterFactory().getInstance();
        Map<String, RateLimitStatus> rateLimitStatus = tc_.getTwitter().getRateLimitStatus();
        for (String endpoint : rateLimitStatus.keySet()) {
            RateLimitStatus status = rateLimitStatus.get(endpoint);
            System.out.println("Endpoint: " + endpoint);
            System.out.println(" Limit: " + status.getLimit());
            System.out.println(" Remaining: " + status.getRemaining());
            System.out.println(" ResetTimeInSeconds: " + status.getResetTimeInSeconds());
            System.out.println(" SecondsUntilReset: " + status.getSecondsUntilReset());
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get rate limit status: " + te.getMessage());
        System.exit(-1);
    }
}