Example usage for twitter4j PagableResponseList hasNext

List of usage examples for twitter4j PagableResponseList hasNext

Introduction

In this page you can find the example usage for twitter4j PagableResponseList hasNext.

Prototype

@Override
    boolean hasNext();

Source Link

Usage

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void importFriends() {
    try {/*w w w.java2  s . co  m*/
        Twitter twitter = getTwitterClient();
        UserService userService = ServiceFactory.newInstance().createUserService();
        boolean exists = true;
        long cursor = -1;

        while (exists) {
            //return 100 follower with status per request
            PagableResponseList<User> twitterFollowers = twitter.getFollowersStatuses(cursor);

            for (User user : twitterFollowers) {
                com.appspot.bitlyminous.entity.User entity = userService
                        .getUserByScreenName(user.getScreenName());
                if (entity == null) {
                    entity = new com.appspot.bitlyminous.entity.User();
                    entity.setScreenName(user.getScreenName());
                    entity.setLevel(com.appspot.bitlyminous.entity.User.Level.DIRECT_USER);
                    userService.updateUser(entity);
                    twitter.createFriendship(user.getScreenName());
                    twitter.sendDirectMessage(user.getScreenName(),
                            ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.welcome"));
                    // following fofs will hit the limit soon.
                    //                   IDs friendsIDs = twitter.getFriendsIDs(user.getId());
                    //                   for (int id : friendsIDs.getIDs()) {
                    //                      twitter.createFriendship(id);
                    //                   }
                } else if (entity.getLevel() != com.appspot.bitlyminous.entity.User.Level.DIRECT_USER) {
                    entity.setLevel(com.appspot.bitlyminous.entity.User.Level.DIRECT_USER);
                    userService.updateUser(entity);
                    twitter.createFriendship(user.getScreenName());
                    twitter.sendDirectMessage(user.getScreenName(),
                            ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.welcome"));
                    // following fofs will hit the limit soon.
                    //                   IDs friendsIDs = twitter.getFriendsIDs(user.getId());
                    //                   for (int id : friendsIDs.getIDs()) {
                    //                      twitter.createFriendship(id);
                    //                   }
                }
            }

            exists = twitterFollowers.hasNext();
            cursor = twitterFollowers.getNextCursor();
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.marpies.ane.twitter.utils.UserUtils.java

License:Apache License

/**
 * Creates JSON from given response list and dispatches generic event.
 * Helper method for queries like getFollowers and getFriends.
 * @param users/*from   w  w  w. ja v a  2s. co  m*/
 * @param callbackID
 */
public static void dispatchUsers(PagableResponseList<User> users, final int callbackID) {
    try {
        AIR.log("Got response with " + users.size() + " users");
        /* Create array of JSON users */
        JSONArray usersJSON = new JSONArray();
        for (User user : users) {
            /* Create JSON for each user and put it to the array */
            JSONObject userJSON = getJSON(user);
            usersJSON.put(userJSON.toString());
        }
        JSONObject result = new JSONObject();
        result.put("users", usersJSON);
        if (users.hasNext()) {
            result.put("nextCursor", users.getNextCursor());
        }
        if (users.hasPrevious()) {
            result.put("previousCursor", users.getPreviousCursor());
        }
        result.put("listenerID", callbackID);
        AIR.dispatchEvent(AIRTwitterEvent.USERS_QUERY_SUCCESS, result.toString());
    } catch (JSONException e) {
        AIR.dispatchEvent(AIRTwitterEvent.USERS_QUERY_ERROR,
                StringUtils.getEventErrorJSON(callbackID, "Error creating result JSON: " + e.getMessage()));
    }
}

From source file:DataCollections.FriendsnFollowersCollection.java

public ArrayList<User_dbo> collectfriendsfollowersofuser(User_dbo cuserdbo) throws InterruptedException {
    long cursor = -1;
    PagableResponseList<User> list;
    User user;/*from ww w. j  a v  a 2  s  .  com*/
    User_dbo userdbo;
    ArrayList<User_dbo> userdbolist = new ArrayList<>();
    boolean available = true;
    Logger.LogPrinter.printLog(
            "Retrieving friends of the user  " + cuserdbo.values[User_dbo.map.get("screename")].string);
    while (available) {

        try {
            list = ffresources.getFriendsList(cuserdbo.values[User_dbo.map.get("user_id")].lnumber, cursor);
            ListIterator li = list.listIterator();
            while (li.hasNext()) {
                user = (User) li.next();
                LogPrinter.printLog("" + user.getName());
                userdbo = userhelper.convertUserToUser_dbo(user);
                userdbolist.add(userdbo);
                //LogPrinter.printLog(" Friend retrieved"+userdbo.values[User_dbo.map.get("screename")].string);
            }
            if (list.hasNext()) {
                cursor = list.getNextCursor();
            } else {
                available = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Logger.LogPrinter.printLog(" Sleeping... rate limit exceeded will try after " + 900 * 1000);
            Thread.sleep(900 * 1000 + 500);

            LogPrinter.printLog(" Message " + e.getMessage());
        }
    }
    LogPrinter.printLog("No of friends retrieved: " + userdbolist.size());
    available = true;
    cursor = 0;
    Logger.LogPrinter.printLog(
            "Retrieving followers of the user  " + cuserdbo.values[User_dbo.map.get("screename")].string);
    while (available) {

        try {
            list = ffresources.getFollowersList(cuserdbo.values[User_dbo.map.get("user_id")].lnumber, cursor);
            ListIterator li = list.listIterator();
            while (li.hasNext()) {
                user = (User) li.next();
                userdbo = userhelper.convertUserToUser_dbo(user);
                userdbolist.add(userdbo);
            }
            if (list.hasNext()) {
                cursor = list.getNextCursor();
            } else {
                available = false;
            }
        } catch (Exception e) {
            Logger.LogPrinter.printLog(" Sleeping... rate limit exceeded will try after " + 900 * 1000);
            Thread.sleep(900 * 1000 + 500);

            LogPrinter.printLog(" Message " + e.getMessage());
        }
    }
    LogPrinter.printLog("No of friends/follwers retrieved: " + userdbolist.size());
    return userdbolist;
}

From source file:org.apache.streams.twitter.provider.TwitterFollowingProviderTask.java

License:Apache License

private void collectUsers(Long id) {
    int keepTrying = 0;
    List<twitter4j.User> list = null;
    long curser = -1;

    twitter4j.User user;//from  w  w  w . java2 s .  c om
    String userJson;
    try {
        user = client.users().showUser(id);
        userJson = TwitterObjectFactory.getRawJSON(user);
    } catch (TwitterException ex) {
        LOGGER.error("Failure looking up " + id);
        return;
    }

    do {
        try {

            PagableResponseList<twitter4j.User> page = null;
            if (provider.getConfig().getEndpoint().equals("followers")) {
                page = client.friendsFollowers().getFollowersList(id, curser,
                        provider.getConfig().getPageSize().intValue());
            } else if (provider.getConfig().getEndpoint().equals("friends")) {
                page = client.friendsFollowers().getFriendsList(id, curser,
                        provider.getConfig().getPageSize().intValue());
            }

            Objects.requireNonNull(list);
            Preconditions.checkArgument(list.size() > 0);

            for (twitter4j.User other : list) {

                String otherJson = TwitterObjectFactory.getRawJSON(other);

                try {
                    Follow follow = null;
                    if (provider.getConfig().getEndpoint().equals("followers")) {
                        follow = new Follow().withFollowee(mapper.readValue(userJson, User.class))
                                .withFollower(mapper.readValue(otherJson, User.class));
                    } else if (provider.getConfig().getEndpoint().equals("friends")) {
                        follow = new Follow().withFollowee(mapper.readValue(otherJson, User.class))
                                .withFollower(mapper.readValue(userJson, User.class));
                    }

                    Objects.requireNonNull(follow);

                    if (item_count < provider.getConfig().getMaxItems()) {
                        ComponentUtils.offerUntilSuccess(new StreamsDatum(follow), provider.providerQueue);
                        item_count++;
                    }

                } catch (Exception ex) {
                    LOGGER.warn("Exception: {}", ex);
                }
            }
            if (!page.hasNext()) {
                break;
            }
            if (page.getNextCursor() == 0) {
                break;
            }
            curser = page.getNextCursor();
            page_count++;
        } catch (Exception ex) {
            keepTrying += TwitterErrorHandler.handleTwitterError(client, null, ex);
        }
    } while (provider.shouldContinuePulling(list) && curser != 0
            && keepTrying < provider.getConfig().getRetryMax() && count < provider.getConfig().getMaxItems());
}

From source file:uk.co.flax.ukmp.twitter.PartyListHandler.java

License:Apache License

private Set<Long> readPartyIds(Twitter twitter, String screenName, String slug, String party) {
    Set<Long> ids = new HashSet<>();

    try {//from w  ww .  jav  a2s.  co  m
        long cursor = -1;
        PagableResponseList<User> response = null;
        do {
            response = twitter.getUserListMembers(screenName, slug, cursor);
            for (User user : response) {
                LOGGER.debug("Read id for user @{}", user.getScreenName());
                ids.add(user.getId());
            }
            cursor = response.getNextCursor();
        } while (response != null && response.hasNext());
    } catch (TwitterException e) {
        LOGGER.error("Twitter exception updating {} party list : {}", party, e.getMessage());
    }

    return ids;
}