Example usage for twitter4j ResponseList getRateLimitStatus

List of usage examples for twitter4j ResponseList getRateLimitStatus

Introduction

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

Prototype

@Override
    public RateLimitStatus getRateLimitStatus();

Source Link

Usage

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);
        }//w w w .j  a  v a2  s  .  c o 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:net.awairo.favdler.twitter.FavoriteListItems.java

License:MIT License

/**
 * Constructor./* w  ww .  ja v  a2  s  . c o  m*/
 *
 * @param responseList ?
 */
public FavoriteListItems(ResponseList<Status> responseList) {
    this(responseList, responseList.getRateLimitStatus());
}

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

License:MIT License

/**
 * @param result ??????????//  w w  w  .  ja va2  s.c  o  m
 */
public void update(ResponseList<Status> responseList) {

    list.setAll(Stream.concat(list.stream(), responseList.stream().map(Tweet::new))
            .sorted(Comparator.comparingLong(Tweet::getId).reversed()).collect(Collectors.toList()));

    updateRateLimitStatus(responseList.getRateLimitStatus());

    log.debug("??{} API{}/{} ??{}", responseList.size(), remaining, limit,
            secondsUntilReset);
}

From source file:org.opensocial.TwitterProxy.java

License:Apache License

/**
 * Called on HTTP GET//  w w  w . j  av  a 2s  .c  om
 * Returns last 20 tweets from the user using "screen_name".
 * If screenName is null or an empty string, we return the last 20 tweets from the public
 * timeline
 * @param screenName
 * @return JSON Response a ActivityStream Activity collection for the set tweets
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object getTweets(@QueryParam("screen_name") String screenName) {

    JSONArray resultArray = new JSONArray();
    ResponseList<Status> list = null;
    try {
        if (screenName == null || screenName.equals("")) {
            list = twitter.getHomeTimeline();
        } else {
            list = twitter.getUserTimeline(screenName);
        }

        System.out.println("Rate limit: " + list.getRateLimitStatus().getRemainingHits());
        Iterator<Status> iter = list.iterator();
        while (iter.hasNext()) {
            Status status = iter.next();

            ActivityBuilder activityBuilder = Activity.makeActivity().id(Long.toString(status.getId()))
                    .verb(Verb.POST).published(new DateTime(status.getCreatedAt().getTime()))
                    .source(ASObject.makeObject(ASObject.SOURCE).displayName(status.getSource()))
                    .author(PersonObject.makePerson(status.getUser().getScreenName())
                            .id(Long.toString(status.getUser().getId()))
                            .image(MediaLink
                                    .makeMediaLink(status.getUser().getProfileImageURL().toExternalForm()))
                            .get());

            boolean eeAdded = false;
            eeAdded = EmbeddedExperiences.addHashtagEE(uriInfo, status, activityBuilder);

            if (!eeAdded) {
                eeAdded = EmbeddedExperiences.addUrlMatchedEE(uriInfo, status, activityBuilder);
            }

            if (!eeAdded) {
                eeAdded = EmbeddedExperiences.addUrlStyleEE(status, activityBuilder);
            }

            activityBuilder.content(status.getText());
            Activity activity = activityBuilder.get();
            StringWriter swriter = new StringWriter();
            activity.writeTo(swriter);
            JSONObject jobj = new JSONObject(swriter.toString());

            resultArray.put(jobj);
        }
        return resultArray;
    } catch (Exception e) {
        e.printStackTrace();
        return Response.serverError().entity(e).build();
    }
}