Example usage for twitter4j RateLimitStatus getSecondsUntilReset

List of usage examples for twitter4j RateLimitStatus getSecondsUntilReset

Introduction

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

Prototype

int getSecondsUntilReset();

Source Link

Document

Returns the amount of seconds until the current rate limiting period ends.
This is a value provided/calculated only by Twitter4J for handiness and not a part of the twitter API spec.

Usage

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;//from  w ww  .  j a  v a2 s . c  om
    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:demo.UserFollowers.java

License:Apache License

static List<Long> followers(Twitter twitter, String screenName) {
    List<Long> m_FollowersList = new ArrayList<Long>();

    long cursor = -1;
    //int count = 0;
    while (true) {
        IDs ids = null;/*  w  ww .j  av  a  2  s .  c  o  m*/
        try {
            //IDs ids = twitter.getFollowersIDs(user.getId(), cursor);
            ids = twitter.getFollowersIDs(screenName, cursor);
        } catch (TwitterException twitterException) {
            // Rate Limit ?????????
            // (memo) status code ?????????

            RateLimitStatus rateLimit = twitterException.getRateLimitStatus();
            int secondsUntilReset = rateLimit.getSecondsUntilReset();
            System.err.println("please wait for " + secondsUntilReset + " seconds");
            System.err.println("Reset Time : " + rateLimit.getResetTimeInSeconds());

            //() 120?getSecondsUntilReset() ?????????????
            // long waitTime = (long)(secondsUntilReset + 120) * 1000;
            long waitTime = (long) (300 * 1000); // 300
            try {
                Thread.sleep(waitTime);
            } catch (Exception e) {
                e.printStackTrace();
            }

            continue;
        } catch (Exception e) {
            e.printStackTrace();
        }

        long[] idArray = ids.getIDs();
        for (int i = 0; i < idArray.length; i++) {
            //System.out.println("["+(++count)+"]" + idArray[i]);
            m_FollowersList.add(new Long(idArray[i]));
        }

        if (ids.hasNext()) {
            cursor = ids.getNextCursor();
        } else {
            break;
        }
    }
    return m_FollowersList;
}

From source file:examples.GetRateLimitStatus.java

License:Apache License

public static void main(String[] args) {
    try {//  www  .  java 2 s.  c o  m

        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 {//from  w  ww .j  a  va 2  s.com
            // 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();//w w w.j  a va 2 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   w  w  w.  jav a2  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);
    }/*from   w  ww . j  av  a 2  s.  c  o m*/

    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:org.springframework.integration.twitter.AbstractInboundTwitterEndpointSupport.java

License:Apache License

protected boolean handleReceivingRateLimitStatus(RateLimitStatus rateLimitStatus) {
    try {/* www .  j  ava2 s  . co m*/
        int secondsUntilReset = rateLimitStatus.getSecondsUntilReset();
        int remainingHits = rateLimitStatus.getRemainingHits();

        if (remainingHits == 0) {
            logger.debug("rate status limit service returned 0 for the remaining hits value");

            return false;
        }

        if (secondsUntilReset == 0) {
            logger.debug("rate status limit service returned 0 for the seconds until reset period value");

            return false;
        }

        int secondsUntilWeCanPullAgain = secondsUntilReset / remainingHits;
        long msUntilWeCanPullAgain = secondsUntilWeCanPullAgain * 1000;

        logger.debug("need to Thread.sleep() " + secondsUntilWeCanPullAgain
                + " seconds until the next timeline pull. Have " + remainingHits
                + " remaining pull this rate period. The period ends in " + secondsUntilReset);

        Thread.sleep(msUntilWeCanPullAgain);
    } catch (Throwable throwable) {
        logger.debug("encountered an error when" + " trying to refresh the timeline: "
                + ExceptionUtils.getFullStackTrace(throwable));
    }

    return true;
}

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