Example usage for twitter4j IDs hasNext

List of usage examples for twitter4j IDs hasNext

Introduction

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

Prototype

@Override
    boolean hasNext();

Source Link

Usage

From source file:com.buddycloud.friendfinder.provider.Twitter.java

License:Apache License

@Override
public ContactProfile getProfile(String accessToken, String accessTokenSecret) throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(getProperties().getProperty("twitter.consumerKey"))
            .setOAuthConsumerSecret(getProperties().getProperty("twitter.consumerSecret"))
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter twitter = tf.getInstance();

    Long myId = twitter.getId();//from   w ww. j  av a 2  s .  co m
    ContactProfile contactProfile = new ContactProfile(HashUtils.encodeSHA256(PROVIDER_NAME, myId.toString()));
    long nextCursor = -1;
    while (true) {
        IDs friendsIDs = twitter.getFollowersIDs(nextCursor);
        for (Long friendId : friendsIDs.getIDs()) {
            contactProfile.addFriendHash(HashUtils.encodeSHA256(PROVIDER_NAME, friendId.toString()));
        }
        if (!friendsIDs.hasNext()) {
            break;
        }
        nextCursor = friendsIDs.getNextCursor();
    }
    return contactProfile;
}

From source file:com.freshdigitable.udonroad.module.twitter.TwitterApi.java

License:Apache License

public Observable<IDs> getAllBlocksIDs() {
    return Observable.create(new Observable.OnSubscribe<IDs>() {
        @Override/*from  ww  w .j  a v  a2  s  .c  om*/
        public void call(Subscriber<? super IDs> subscriber) {
            try {
                IDs blocksIDs = null;
                while (blocksIDs == null || blocksIDs.hasNext()) {
                    final long cursor = blocksIDs == null ? -1 : blocksIDs.getNextCursor();
                    blocksIDs = twitter.getBlocksIDs(cursor);
                    subscriber.onNext(blocksIDs);
                }
                subscriber.onCompleted();
            } catch (TwitterException e) {
                subscriber.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}

From source file:com.freshdigitable.udonroad.module.twitter.TwitterApi.java

License:Apache License

public Observable<IDs> getAllMutesIDs() {
    return Observable.create(new Observable.OnSubscribe<IDs>() {
        @Override//from w w  w  .ja va2 s. co m
        public void call(Subscriber<? super IDs> subscriber) {
            try {
                IDs mutesIDs = null;
                while (mutesIDs == null || mutesIDs.hasNext()) {
                    final long cursor = mutesIDs == null ? -1 : mutesIDs.getNextCursor();
                    mutesIDs = twitter.getMutesIDs(cursor);
                    subscriber.onNext(mutesIDs);
                }
                subscriber.onCompleted();
            } catch (TwitterException e) {
                subscriber.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}

From source file:com.happy_coding.viralo.twitter.FriendDiscoverer.java

License:Apache License

/**
 * Returns the friends for the provided friend.
 *
 * @param forContact//from w w w.j  ava2  s .  c o  m
 * @return
 */
public List<Contact> findFriends(Contact forContact) {

    List<Contact> contacts = new ArrayList<Contact>();
    Twitter twitter = new TwitterFactory().getInstance();

    try {
        IDs list = twitter.getFriendsIDs(forContact.getUid(), -1);
        do {

            for (long id : list.getIDs()) {
                Contact contact = new Contact(id);
                contact.setActiveUid(twitter.getId());
                contacts.add(contact);
            }
        } while (list.hasNext());

    } catch (TwitterException e) {
        logger.error("can't find friends for contact", e);
        return null;
    }
    return contacts;
}

From source file:com.happy_coding.viralo.twitter.FriendDiscoverer.java

License:Apache License

/**
 * Returns a list of contacts which follow the provided contact.
 *
 * @param forContact//from   w w  w  .  j  a v a 2s  .c  om
 * @return
 */
public List<Contact> findFollowers(Contact forContact) {
    List<Contact> contacts = new ArrayList<Contact>();
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        IDs list = twitter.getFollowersIDs(forContact.getUid(), -1);
        do {

            for (long id : list.getIDs()) {
                logger.debug("follower id: " + id);
                Contact contact = new Contact(id);
                contact.setActiveUid(twitter.getId());
                contacts.add(contact);
            }
        } while (list.hasNext());
    } catch (TwitterException e) {
        logger.error("can't find followers", e);
        return null;
    }
    return contacts;
}

From source file:com.jeanchampemont.wtfdyum.service.impl.TwitterServiceImpl.java

License:Apache License

@Override
public Set<Long> getFollowers(final Long userId, final Optional<Principal> principal) throws WTFDYUMException {
    Preconditions.checkNotNull(userId);//from   w w  w.  j  ava 2 s  . co  m

    final Twitter twitter = principal.isPresent() ? twitter(principal.get()) : twitter();

    final Set<Long> result = new HashSet<>();
    try {
        IDs followersIDs = null;
        long cursor = -1;
        do {
            followersIDs = twitter.getFollowersIDs(userId, cursor);
            if (followersIDs.hasNext()) {
                cursor = followersIDs.getNextCursor();
                checkRateLimitStatus(followersIDs.getRateLimitStatus(),
                        WTFDYUMExceptionType.GET_FOLLOWERS_RATE_LIMIT_EXCEEDED);
            }

            final Set<Long> currentFollowers = Arrays.stream(followersIDs.getIDs()).boxed()
                    .collect(Collectors.toCollection(() -> new HashSet<>()));

            result.addAll(currentFollowers);
        } while (followersIDs.hasNext());

    } catch (final TwitterException e) {
        log.debug("Error while getFollowers", e);
        throw new WTFDYUMException(e, WTFDYUMExceptionType.TWITTER_ERROR);
    }
    return result;
}

From source file:com.mycompany.omnomtweets.RetweetersOfCandidate.java

/**
 * Method user IDs of retweeters.  Paginates on cursor.
 * @param tweetId id of the tweet we are getting retweeters of
 * @param calls number of API calls left
 * @return List of users that retweeted the given tweet.
 *///from   w w w.j  av  a2 s. c om
public List<String> getRetweeters(String tweetId) {
    //System.out.println("Getting retweeters of " + tweetId);
    List<String> retweeters = new ArrayList<>();
    IDs currentIDs;
    try {
        if (calls > 0) {
            calls -= 1;
            currentIDs = twitter.getRetweeterIds(Long.parseLong(tweetId), -1);
            long[] longIDs = currentIDs.getIDs();
            //System.out.println("Got " + longIDs.length + " retweeters");
            for (int i = 0; i < longIDs.length; i++) {
                retweeters.add("" + longIDs[i]);
            }
            while (calls > 0 && currentIDs.hasNext()) {
                calls -= 1;
                currentIDs = twitter.getRetweeterIds(Long.parseLong(tweetId), currentIDs.getNextCursor());
                longIDs = currentIDs.getIDs();
                //System.out.println("Adding " + longIDs.length + " retweeters");
                for (int i = 0; i < longIDs.length; i++) {
                    retweeters.add("" + longIDs[i]);
                }
            }
        } else {
            System.out.println("Cut off early");
            return retweeters;
        }
    } catch (TwitterException ex) {
        System.out.println("Failed to get rate limit status: " + ex.getMessage());
        return retweeters;
    }
    return retweeters;
}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

public void getFriendsOrFollowers(String userName, AnyExecutor<User> executor, boolean friends,
        boolean waitIfNoApiPoints) {
    long cursor = -1;
    resetRateLimitCache();/* w  w  w  .  ja v  a2 s .c  om*/
    MAIN: while (true) {
        if (waitIfNoApiPoints) {
            checkAndWaitIfRateLimited("getFriendsOrFollowers 1");
        }

        ResponseList<User> res = null;
        IDs ids = null;
        try {
            if (friends)
                ids = twitter.getFriendsIDs(userName, cursor);
            else
                ids = twitter.getFollowersIDs(userName, cursor);

            rateLimit--;
        } catch (TwitterException ex) {
            if (waitIfNoApiPoints && checkAndWaitIfRateLimited("getFriendsOrFollowers 2", ex)) {
                // nothing to do
            } else
                logger.warn(ex.getMessage());
            break;
        }
        if (ids.getIDs().length == 0)
            break;

        long[] intids = ids.getIDs();

        // split into max 100 batch            
        for (int offset = 0; offset < intids.length; offset += 100) {
            long[] limitedIds = new long[100];
            for (int ii = 0; ii + offset < intids.length && ii < limitedIds.length; ii++) {
                limitedIds[ii] = intids[ii + offset];
            }

            // retry at max N times for every id bunch
            for (int trial = 0; trial < 5; trial++) {
                try {
                    res = twitter.lookupUsers(limitedIds);
                } catch (TwitterException ex) {
                    if (waitIfNoApiPoints
                            && checkAndWaitIfRateLimited("getFriendsOrFollowers 3 (trial " + trial + ")", ex)) {
                        // nothing to do
                    } else {
                        // now hoping that twitter recovers some seconds later
                        logger.error("(trial " + trial + ") error while lookupUsers: " + getMessage(ex));
                        myWait(10);
                    }
                    continue;
                } catch (Exception ex) {
                    logger.error("(trial " + trial + ") error while lookupUsers: " + getMessage(ex));
                    myWait(5);
                    continue;
                }

                rateLimit--;
                for (User user : res) {
                    // strange that this was necessary for ibood
                    if (user.getScreenName().trim().isEmpty())
                        continue;

                    if (executor.execute(user) == null)
                        break MAIN;
                }
                break;
            }

            if (res == null) {
                logger.error("giving up");
                break;
            }
        }

        if (!ids.hasNext())
            break;

        cursor = ids.getNextCursor();
    }
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public void getFriendsOrFollowers(String userName, AnyExecutor<JUser> executor, boolean friends) {
    long cursor = -1;
    resetRateLimitCache();/*from w  w  w. j  ava  2s.  c om*/
    MAIN: while (true) {
        while (getRateLimitFromCache() < LIMIT) {
            int reset = getSecondsUntilReset();
            if (reset != 0) {
                logger.info("no api points left while getFriendsOrFollowers! Skipping ...");
                return;
            }
            resetRateLimitCache();
            myWait(0.5f);
        }

        ResponseList res = null;
        IDs ids = null;
        try {
            if (friends)
                ids = twitter.getFriendsIDs(userName, cursor);
            else
                ids = twitter.getFollowersIDs(userName, cursor);

            rateLimit--;
        } catch (TwitterException ex) {
            logger.warn(ex.getMessage());
            break;
        }
        if (ids.getIDs().length == 0)
            break;

        long[] intids = ids.getIDs();

        // split into max 100 batch            
        for (int offset = 0; offset < intids.length; offset += 100) {
            long[] limitedIds = new long[100];
            for (int ii = 0; ii + offset < intids.length && ii < limitedIds.length; ii++) {
                limitedIds[ii] = intids[ii + offset];
            }

            // retry at max N times for every id bunch
            for (int i = 0; i < 5; i++) {
                try {
                    res = twitter.lookupUsers(limitedIds);
                    rateLimit--;
                    for (Object o : res) {
                        User user = (User) o;
                        // strange that this was necessary for ibood
                        if (user.getScreenName().trim().isEmpty())
                            continue;

                        JUser jUser = new JUser(user);
                        if (executor.execute(jUser) == null)
                            break MAIN;
                    }
                    break;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    myWait(5);
                    continue;
                }
            }

            if (res == null) {
                logger.error("giving up");
                break;
            }
        }

        if (!ids.hasNext())
            break;

        cursor = ids.getNextCursor();
    }
}

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;
        try {//w  w w  .j a v a2s .c o  m
            //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;
}