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: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);
    }//www .  j a  v  a  2s. 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 . j a  v  a  2 s. c  om*/

        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:de.jetsli.twitter.TwitterSearch.java

License:Apache License

public int getSecondsUntilReset() {
    try {/* w w w. jav a 2 s. c  o  m*/
        RateLimitStatus rls = getRLS();
        rateLimit = rls.getRemaining();
        return rls.getSecondsUntilReset();
    } catch (TwitterException ex) {
        logger.error("Cannot determine rate limit:" + ex.getMessage());
        return -1;
    }
}

From source file:examples.GetRateLimitStatus.java

License:Apache License

public static void main(String[] args) {
    try {//from  w  ww .ja v 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 {/* w  ww.  jav a 2 s.  c  o 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();//from   w w w  .jav  a2  s  . c o m
    remaining = status.getRemaining();
    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:org.loklak.harvester.TwitterAPI.java

License:Open Source License

public static JSONObject getUser(String screen_name, boolean forceReload) throws TwitterException, IOException {
    if (!forceReload) {
        JsonFactory mapcapsule = DAO.user_dump.get("screen_name", screen_name);
        if (mapcapsule == null)
            mapcapsule = DAO.user_dump.get("id_str", screen_name);
        if (mapcapsule != null) {
            JSONObject json = mapcapsule.getJSON();
            if (json.length() > 0) {
                // check if the entry is maybe outdated, i.e. if it is empty or too old
                try {
                    Date d = DAO.user_dump.parseDate(json);
                    if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis())
                        return json;
                } catch (ParseException e) {
                    return json;
                }//from   ww w  .  j av  a 2  s.  c o m
            }
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    User user = twitter.showUser(screen_name);
    RateLimitStatus rateLimitStatus = user.getRateLimitStatus();
    getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000;
    getUserRemaining = rateLimitStatus.getRemaining();
    JSONObject json = user2json(user);
    enrichLocation(json);
    DAO.user_dump.putUnique(json);
    return json;
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

public static JSONObject getNetworkerNames(final String screen_name, final int max_count,
        final Networker networkRelation) throws IOException, TwitterException {
    if (max_count == 0)
        return new JSONObject();
    boolean complete = true;
    Set<Number> networkingIDs = new LinkedHashSet<>();
    Set<Number> unnetworkingIDs = new LinkedHashSet<>();
    JsonFactory mapcapsule = (networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump)
            .get("screen_name", screen_name);
    if (mapcapsule == null) {
        JsonDataset ds = networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump;
        mapcapsule = ds.get("screen_name", screen_name);
    }//  www .  j a  v  a  2 s  .  c  om

    if (mapcapsule != null) {
        JSONObject json = mapcapsule.getJSON();

        // check date and completeness
        complete = json.has("complete") ? (Boolean) json.get("complete") : Boolean.FALSE;
        String retrieval_date_string = json.has("retrieval_date") ? (String) json.get("retrieval_date") : null;
        DateTime retrieval_date = retrieval_date_string == null ? null
                : AbstractObjectEntry.utcFormatter.parseDateTime(retrieval_date_string);
        if (complete && System.currentTimeMillis() - retrieval_date.getMillis() < DateParser.DAY_MILLIS)
            return json;

        // load networking ids for incomplete retrievals (untested)
        String nr = networkRelation == Networker.FOLLOWERS ? "follower" : "following";
        if (json.has(nr)) {
            JSONArray fro = json.getJSONArray(nr);
            for (Object f : fro)
                networkingIDs.add((Number) f);
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    long cursor = -1;
    collect: while (cursor != 0) {
        try {
            IDs ids = networkRelation == Networker.FOLLOWERS ? twitter.getFollowersIDs(screen_name, cursor)
                    : twitter.getFriendsIDs(screen_name, cursor);
            RateLimitStatus rateStatus = ids.getRateLimitStatus();
            if (networkRelation == Networker.FOLLOWERS) {
                getFollowerIdRemaining = rateStatus.getRemaining();
                getFollowerIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000;
            } else {
                getFollowingIdRemaining = rateStatus.getRemaining();
                getFollowingIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000;
            }
            //System.out.println("got: " + ids.getIDs().length + " ids");
            //System.out.println("Rate Status: " + rateStatus.toString() + "; time=" + System.currentTimeMillis());
            boolean dd = false;
            for (long id : ids.getIDs()) {
                if (networkingIDs.contains(id))
                    dd = true; // don't break loop here
                networkingIDs.add(id);
            }
            if (dd)
                break collect; // this is complete!
            if (rateStatus.getRemaining() == 0) {
                complete = false;
                break collect;
            }
            if (networkingIDs.size() >= Math.min(10000, max_count >= 0 ? max_count : 10000)) {
                complete = false;
                break collect;
            }
            cursor = ids.getNextCursor();
        } catch (TwitterException e) {
            complete = false;
            break collect;
        }
    }
    // create result
    JSONObject json = new JSONObject(true);
    json.put("screen_name", screen_name);
    json.put("retrieval_date", AbstractObjectEntry.utcFormatter.print(System.currentTimeMillis()));
    json.put("complete", complete);
    Map<String, Number> networking = getScreenName(networkingIDs, max_count, true);
    Map<String, Number> unnetworking = getScreenName(unnetworkingIDs, max_count, true);
    if (networkRelation == Networker.FOLLOWERS) {
        json.put("followers_count", networking.size());
        json.put("unfollowers_count", unnetworking.size());
        json.put("followers_names", networking);
        json.put("unfollowers_names", unnetworking);
        if (complete)
            DAO.followers_dump.putUnique(json); // currently we write only complete data sets. In the future the update of datasets shall be supported
    } else {
        json.put("following_count", networking.size());
        json.put("unfollowing_count", unnetworking.size());
        json.put("following_names", networking);
        json.put("unfollowing_names", unnetworking);
        if (complete)
            DAO.following_dump.putUnique(json);
    }
    return json;
}

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 www  .j a  v a 2s .c o  m*/
            Thread.sleep(secondsToWait * 1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Accessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}