Example usage for twitter4j RateLimitStatus getRemaining

List of usage examples for twitter4j RateLimitStatus getRemaining

Introduction

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

Prototype

int getRemaining();

Source Link

Document

Returns the remaining number of API requests available.
This value is identical to the "X-Rate-Limit-Remaining" response header.

Usage

From source file:tientx.supercode.myproejectdemov3.service.TwitterServiceImpl.java

private void overError88(String command) throws TwitterException, InterruptedException {
    Map<String, RateLimitStatus> temp = twitter.getRateLimitStatus();
    RateLimitStatus temp2 = temp.get(command);
    System.out.println("------------------------------------------------Remaining:" + temp2.getRemaining());
    if (temp2.getRemaining() == 0) {
        Thread.sleep((temp2.getSecondsUntilReset() + 5) * 1000);
        return;//  w w  w  . j a  v a  2  s  .co  m
    }
    System.out.println("------------------------------------------------SecondsUntilReset:"
            + temp2.getSecondsUntilReset());
    int secondstosleep = 1 + temp2.getSecondsUntilReset() / temp2.getRemaining();
    System.out.println("------------------------------------------------secondstosleep:" + secondstosleep);
    Thread.sleep(secondstosleep * 1000);
}

From source file:tweetcrawling.Main.java

public static void getRateLimitStatuses(TwitterConfiguration tc_) {
    try {/*from w w w .  ja  v a  2 s .c o 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);
    }
}

From source file:tweetcrawling.TweetCrawler.java

public void rateLimitHandler(TwitterConfiguration tc_, String endpoint)
        throws TwitterException, InterruptedException {
    Map<String, RateLimitStatus> rateLimitStatus = tc_.getTwitter().getRateLimitStatus();
    RateLimitStatus appRateLimit = rateLimitStatus.get(endpoint);

    System.out.printf(endpoint + ": You have %d calls remaining out of %d, Limit resets in %d seconds\n",
            appRateLimit.getRemaining(), appRateLimit.getLimit(), appRateLimit.getSecondsUntilReset()); // For debug purposes

    if (appRateLimit.getRemaining() < 10) {
        System.out.println("Sleeping for " + appRateLimit.getSecondsUntilReset() + " seconds due to " + endpoint
                + " rate limit."); // For debug purposes
        Thread.sleep((appRateLimit.getSecondsUntilReset() + 2) * 1001);
    }//from   w w w  . j a  v  a2 s  .  co  m
}

From source file:tweetdownloader.cnr_stable.version.TweetDownload.java

/**
 * this method return an ArrayList of dataOfTweets
 * @param allMyTweets//from   w ww.j av  a2 s.  c o  m
 * @return allMyTweet
 */
public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) {
    {
        try {
            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
            for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
                dataOfTweet tweet = new dataOfTweet();

                //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                if (searchTweetsRateLimit.getRemaining() == 0) {
                    try {
                        //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());
                        Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                    } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                }
                Query q = new Query(SEARCH_TERM);
                q.setCount(TWEETS_PER_QUERY);
                q.setLang("it");

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

                QueryResult r = twitter.search(q);

                if (r.getTweets().isEmpty()) {
                    break;
                }
                for (Status s : r.getTweets()) {

                    totalTweets++;
                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }
                    if (s.isRetweeted() == false) {

                        tweet.setUsername(s.getUser().getScreenName());
                        tweet.setCreatedAt(s.getCreatedAt().toString());
                        tweet.setTweetText(s.getText());

                        if (s.getGeoLocation() != null) {
                            tweet.setLat(s.getGeoLocation().getLatitude());
                            tweet.setLongi(s.getGeoLocation().getLongitude());
                        }
                    }
                }
                allMyTweets.add(tweet);
            }
        } catch (TwitterException ex) {
            java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return allMyTweets;
}

From source file:twitter4j.examples.account.GetRateLimitStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.account.GetRateLimitStatus
 *
 * @param args message// w  w w  . ja va2s.co  m
 */
public static void main(String[] args) {
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        Map<String, RateLimitStatus> rateLimitStatus = twitter.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);
    }
}

From source file:TwitterDownload.TwitterHandler.java

public int getRemainingRateLimit() {
    try {//from  ww  w.j  ava 2 s  .  co  m
        RateLimitStatus rateLimit = twitter.getRateLimitStatus("statuses").get("/statuses/user_timeline");
        int restTime = rateLimit.getSecondsUntilReset();
        return rateLimit.getRemaining();
    } catch (TwitterException ex) {
        String s = ex.toString();
    } catch (IllegalStateException ex) {
        String s = ex.toString();
    }
    return -1;
}

From source file:TwitterDownload.TwitterHandler.java

public int getRemainingSearchRateLimit() {
    try {/*from   w  ww  . jav a 2s .co  m*/
        RateLimitStatus rateLimit = twitter.getRateLimitStatus("search").get("/search/tweets");
        int restTime = rateLimit.getSecondsUntilReset();
        return rateLimit.getRemaining();
    } catch (TwitterException ex) {
        String s = ex.toString();
    } catch (IllegalStateException ex) {
        String s = ex.toString();
    }
    return -1;
}

From source file:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*from w  w  w.ja  va  2s  . 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();
        */

    }

}