Example usage for twitter4j Twitter getRateLimitStatus

List of usage examples for twitter4j Twitter getRateLimitStatus

Introduction

In this page you can find the example usage for twitter4j Twitter getRateLimitStatus.

Prototype

Map<String, RateLimitStatus> getRateLimitStatus(String... resources) throws TwitterException;

Source Link

Document

Returns the current rate limits for methods belonging to the specified resource families.
Each 1.1 API resource belongs to a "resource family" which is indicated in its method documentation.

Usage

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();

    try {//from ww w  .  j  a v a  2s. c  om
        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:Beans.Crawler.java

public List search(Categoria categoria, Localizacao localizacao) throws Exception {
    long maxID = -1;

    List<Tweet> list = new ArrayList<Tweet>();
    Twitter twitter = getTwitter();
    try {// w  w  w.ja  v a  2s  . c  o m
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            if (searchTweetsRateLimit.getRemaining() == 0) {
            }

            String works = localizacao.getPalavrasChaves();
            String[] arrWorks = works.split(",");
            String keywork = "", or = "OR";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }
            System.out.println("exclude:retweets " + categoria.getDescricao() + keywork);
            Query q = new Query("exclude:retweets " + categoria.getDescricao() + keywork);
            q.setCount(TWEETS_PER_QUERY);
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }
            QueryResult r = twitter.search(q);
            if (r.getTweets().size() == 0) {
                break;
            }
            for (Status s : r.getTweets()) {
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }
                Tweet t = new Tweet();
                t.setUsuario(s.getUser().getId());
                String dataPostagem = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s.getCreatedAt());
                t.setDataPostagem(dataPostagem);
                t.setTweet(s.getText());
                t.setTweetId(s.getId());
                t.setCategoriaId(categoria.getId());
                t.setLocalizacaoId(localizacao.getId());
                list.add(t);
            }
            searchTweetsRateLimit = r.getRateLimitStatus();
        }
    } catch (Exception e) {
        throw e;
    }

    return list;
}

From source file:br.com.controller.TweetController.java

public String search() {
    Categoria c = new CategoriaDAO().find(Integer.parseInt(categoria));
    Localizacao l = new LocalizacaoDAO().find(Integer.parseInt(localizacao));
    long maxID = -1;

    Twitter twitter = getTwitter();
    try {/*from  www. j  a va 2s  .com*/
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            if (searchTweetsRateLimit.getRemaining() == 0) {
            }

            String works = c.getPalavrasChaves();
            String[] arrWorks = works.split(",");
            String keywork = "", or = "OR", query = "";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }

            query = "exclude:retweets " + keywork;

            works = l.getPalavrasChaves();
            arrWorks = works.split(",");
            keywork = "";
            or = "OR";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }

            query += keywork;

            Query q = new Query(query);
            q.setCount(TWEETS_PER_QUERY);
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }
            QueryResult r = twitter.search(q);
            if (r.getTweets().size() == 0) {
                break;
            }
            for (Status s : r.getTweets()) {
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }

                Tweet t = new Tweet();
                t.setUsuario(s.getUser().getId());
                t.setDataPostagem(s.getCreatedAt());
                t.setTweet(s.getText());
                if (!new DAO.TweetDAO().hastTweet(s.getId())) {
                    t.setTweetId(s.getId());
                    t.setCategoria(c);
                    t.setLocalizacao(l);
                    jpa.saveOrUpdate(t);
                }
            }
            searchTweetsRateLimit = r.getRateLimitStatus();
        }
    } catch (Exception e) {
    }

    return "index";
}

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 {//from w w  w .  j a v a 2 s  .  c  om
        //   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:ru.mail.sphere.java_hw5_vasilyev.twitteraccessor.Accessor.java

private static void meetRateLimits(Twitter twitter) throws TwitterException {
    RateLimitStatus rateLimitStatus = twitter.getRateLimitStatus("search").get("/search/tweets");
    if (rateLimitStatus.getRemaining() == 0) {
        int secondsToWait = rateLimitStatus.getSecondsUntilReset() + 1;
        System.out.println(String.format("Rate limit exceeded, waiting %d seconds...", secondsToWait));
        try {/*from  w w  w  . j a  v a2s .  c  o m*/
            Thread.sleep(secondsToWait * 1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Accessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*from   w w  w  . j a  v  a 2  s .  c  o m*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws TwitterException, IOException {

    /* ---------------------------Setting up twitter account authentication-------------------------------*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS")
            .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO")
            .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP")
            .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG");

    /* ---------------------------------File Writing Variables------------------------------------------------*/

    File outfile = new File("output.txt");
    FileWriter fwriter = new FileWriter(outfile);

    try (PrintWriter pWriter = new PrintWriter(fwriter)) {

        /*----------------------------------Search Parameters-------------------------------------*/

        String search = "chinese food";
        String lang = "en";
        /*------------------------End Search Parameters----------------------------------------*/

        int numTweets = 0;
        long maxID = -1;
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        try {

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

            /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(),
                searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());
            */

            for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) {

                System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n");

                if (searchTweetsRateLimit.getRemaining() == 0) {
                    System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                            searchTweetsRateLimit.getSecondsUntilReset());
                    Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                }
                //here is where we can send an object to the query
                Query query = new Query(search);
                query.setCount(tweetsPerQuery);
                query.resultType(Query.ResultType.recent);
                query.setLang(lang);

                if (maxID != -1) {
                    query.setMaxId(maxID - 1);
                }

                QueryResult result = twitter.search(query);

                if (result.getTweets().size() == 0) {
                    break;
                }

                for (Status s : result.getTweets()) {

                    numTweets++;

                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }

                    System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(),
                            s.getUser().getScreenName(), cleanText(s.getText()));

                    pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName()
                            + " " + cleanText(s.getText()));

                }

                searchTweetsRateLimit = result.getRateLimitStatus();

            }

        }

        catch (Exception e) {

            System.out.println("Broken");

            e.printStackTrace();
        }
        System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets);
        pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n");
        pWriter.close();

        /*while (result.hasNext()){
            numTweets += result.getCount();
        System.out.println(numTweets);
         for (Status status : result.getTweets()) {
             System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
         }  
         result.nextQuery();
        }
                   
                     
                 
                 
        /*
         QueryForm qf = new QueryForm();
           qf.show();
        */

    }

}