Example usage for twitter4j IDs getIDs

List of usage examples for twitter4j IDs getIDs

Introduction

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

Prototype

long[] getIDs();

Source Link

Usage

From source file:GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFriendsIDs [screen name]
 *
 * @param args message//  w w  w  .  j a  v a 2s  .  c o  m
 */
public ArrayList<Long> getFriendsId() {
    ArrayList<Long> friendsid = new ArrayList<Long>();
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        long cursor = -1;
        IDs ids;
        System.out.println("Listing following ids.");

        do {

            ids = twitter.getFriendsIDs(cursor);

            for (long id : ids.getIDs()) {

                friendsid.add(id);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        System.out.println("done");
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get friends' ids: " + te.getMessage());

    }

    return friendsid;
}

From source file:aic2013.follower.TwitterDataAccess.java

public void forAllFriendIds(TwitterUser twitterUser, Processor<Long> processor) {
    long nextCursor = -1;
    IDs usersResponse = null;

    do {/* w w  w  .  j a va2 s  .  c  o  m*/
        assert usersResponse == null;

        while (usersResponse == null) {
            if (!open) {
                throw new ClosedException();
            }

            try {
                usersResponse = twitter.getFriendsIDs(twitterUser.getId(), nextCursor);
            } catch (TwitterException ex) {
                if (ex.exceededRateLimitation()) {
                    waitForReset(ex.getRateLimitStatus().getSecondsUntilReset() * 1000);
                } else if (ex.resourceNotFound()) {
                    //                        throw new RuntimeException("The user for which the friends were requested does not exist any more.", ex);
                    return;
                }

                // Retry when other errors like IO-related ones occur
            }
        }

        assert usersResponse != null;
        nextCursor = usersResponse.getNextCursor();

        for (long userId : usersResponse.getIDs()) {
            processor.process(userId);
        }
        usersResponse = null;
    } while (nextCursor > 0);
}

From source file:com.amandine.twitterpostforcoucou.Tweet.java

public void getFollowersInformation(String FollowersFor) {
    try {/*  w  ww .  j  a  v  a2 s.c  o  m*/
        Twitter twitter = new TwitterFactory().getInstance();
        long cursor = -1;
        IDs ids;
        System.out.println("Listing followers's ids.");
        do {
            //                 if (0 < args.length) { 
            ids = twitter.getFollowersIDs(URLEncoder.encode(FollowersFor), cursor);
            //                 } else { 
            //                     ids = twitter.getFollowersIDs(cursor); 
            //                 } 
            for (long id : ids.getIDs()) {
                //System.out.println(id + " " + twitter.showUser(id).getScreenName());
                //twitter.showUser(id).getDescription language location name
                //twitter.showUser(id).getScreenName() this is rate limited at 180 every 15 minutes
                writeUsersTwitterIdToUserTable(Long.toString(id), "", FollowersFor);
            }
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException ex) {
                logger.log(Level.INFO, "Woke up", ex);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.appspot.bitlyminous.standalone.TwitterExample.java

License:Apache License

/**
 * The main method./*  w  w  w .j a va2  s.c  om*/
 * 
 * @param args the arguments
 * 
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer("671O1zUicFBCYHHYVp0XA", "cP7WvfAtxXGSaf1Sz0ksZtWGcENosFcRr46WR7a9jU");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());
        System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    // persist to the accessToken for future reference.
    System.out.println("Screen name:" + accessToken.getScreenName());
    System.out.println("Token:" + accessToken.getToken());
    System.out.println("Secret:" + accessToken.getTokenSecret());

    IDs friendsIDs = twitter.getFriendsIDs("gapinginfinity");
    System.out.println(Arrays.toString(friendsIDs.getIDs()));

    ResponseList<Status> favorites = twitter.getFavorites("gapinginfinity");
    System.out.println(favorites.size());
    System.exit(0);
}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/getFriends.arihant15")
public void doFriends(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {//from www. j  a va  2s.  c  o m
        Twitter twitter = (Twitter) req.getSession().getAttribute("t");
        IDs ids = twitter.getFollowersIDs(-1);
        PagableResponseList<User> users;
        for (long id : ids.getIDs()) {
            (res.getWriter()).println("@" + twitter.showUser(id).getName() + "\n");
        }
    } catch (Exception e) {
        (res.getWriter()).println(e);
    }
}

From source file:com.avishkar.NewGetFollowersIDs.java

License:Apache License

private static List<Long> getUserFollwers(long twitterUserId)
        throws UnknownHostException, TwitterException, InterruptedException {
    Twitter twitter = new TwitterFactory(AccessTokenUtil.getConfig()).getInstance();
    List<Long> filteredUserListOnFollowerCount = new ArrayList<Long>();
    final Gson gson = new Gson();
    try {/*  w  w w.  jav  a  2  s . com*/

        checkRateLimit("/followers/ids", twitter);
        System.out.println("Listing followers's Follower for ID:" + twitterUserId + System.lineSeparator());
        IDs followerIDs = twitter.getFollowersIDs(twitterUserId, -1);
        JsonObject followerJSON = new JsonObject();

        followerJSON.addProperty("id", twitterUserId);
        followerJSON.addProperty("followers", gson.toJson(followerIDs.getIDs()));
        DBAccess.insert(gson.toJson(followerJSON));

        System.out.println("Current Followers Fetched Size:" + followerIDs.getIDs().length);
        // Filtering for influential user
        if (followerIDs.getIDs().length > 1000) {
            System.out.println("User assumed as Influential");
            return null;
        }
        int from = 0;
        int to = 99;
        int limit = checkRateLimit("/users/lookup", twitter);
        while (from < followerIDs.getIDs().length) {
            if (to > followerIDs.getIDs().length)
                to = followerIDs.getIDs().length - 1;
            if (limit == 0)
                checkRateLimit("/users/lookup", twitter);
            ResponseList<User> followers = twitter
                    .lookupUsers(Arrays.copyOfRange(followerIDs.getIDs(), from, to));
            System.out.println("Recieved User count:" + followers.size());
            for (User user : followers) {
                DBAccess.insertUser(gson.toJson(user));
                if (user.getFollowersCount() < 1000) {
                    // if(user.getStatusesCount()>0 &&
                    // user.getStatus()!=null &&
                    // sevenDaysAgo.after(user.getStatus().getCreatedAt()))
                    filteredUserListOnFollowerCount.add(user.getId());
                    getStatuses(user.getScreenName(), twitter);
                } else
                    System.out.println("User " + user.getScreenName()
                            + " is pruned for Influential or over subscription." + " Follower count:"
                            + user.getFollowersCount() + " Friends Count:" + user.getFriendsCount());
            }

            from += 100;
            to += 100;
            limit--;
        }
    } catch (TwitterException te) {
        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {
            System.out.println("Encountered locked profile. Skipping " + twitterUserId);
            return null;

            // log something here
        }
        te.printStackTrace();
        System.out.println("Failed to get followers' Follower: " + te.getMessage());
        // System.exit(-1);
    }

    return filteredUserListOnFollowerCount;
}

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();// w ww  .  ja  v  a  2s.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.daiv.android.twitter.ui.profile_viewer.fragments.ProfileFragment.java

License:Apache License

public void getFollowers(final User user, final AsyncListView listView) {
    spinner.setVisibility(View.VISIBLE);
    canRefresh = false;//from w w  w .j a v a  2s  .co m

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                try {
                    if (followingIds == null && user.getId() == settings.myId) {
                        long currCursor = -1;
                        IDs idObject;
                        int rep = 0;

                        do {
                            // gets 5000 ids at a time
                            idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                            long[] lIds = idObject.getIDs();
                            followingIds = new ArrayList<Long>();
                            for (int i = 0; i < lIds.length; i++) {
                                followingIds.add(lIds[i]);
                            }

                            rep++;
                        } while ((currCursor = idObject.getNextCursor()) != 0 && rep < 3);
                    }
                } catch (Throwable t) {
                    followingIds = null;
                }

                PagableResponseList<User> friendsPaging = twitter.getFollowersList(user.getId(),
                        currentFollowers, 100);

                for (int i = 0; i < friendsPaging.size(); i++) {
                    followers.add(friendsPaging.get(i));
                }

                if (friendsPaging.size() > 17) {
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                currentFollowers = friendsPaging.getNextCursor();

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (followersAdapter == null) {
                            if (followingIds == null) {
                                // we will do a normal array adapter
                                followersAdapter = new PeopleArrayAdapter(context, followers);
                            } else {
                                followersAdapter = new FollowersArrayAdapter(context, followers, followingIds);
                            }
                            listView.setAdapter(followersAdapter);
                        } else {
                            followersAdapter.notifyDataSetChanged();
                        }

                        if (settings.roundContactImages) {
                            ImageUtils.loadSizedCircleImage(context, profilePicture,
                                    thisUser.getOriginalProfileImageURL(), mCache, 96);
                        } else {
                            ImageUtils.loadImage(context, profilePicture, thisUser.getOriginalProfileImageURL(),
                                    mCache);
                        }

                        String url = user.getProfileBannerURL();
                        ImageUtils.loadImage(context, background, url, mCache);

                        canRefresh = true;
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (user != null && user.isProtected()) {
                            Toast.makeText(context, getResources().getString(R.string.protected_account),
                                    Toast.LENGTH_SHORT).show();
                            if (settings.roundContactImages) {
                                ImageUtils.loadSizedCircleImage(context, profilePicture,
                                        thisUser.getOriginalProfileImageURL(), mCache, 96);
                            } else {
                                ImageUtils.loadImage(context, profilePicture, user.getOriginalProfileImageURL(),
                                        mCache);
                            }

                            String url = user.getProfileBannerURL();
                            ImageUtils.loadImage(context, background, url, mCache);
                        } else {
                            Toast.makeText(context, getResources().getString(R.string.error_loading_timeline),
                                    Toast.LENGTH_SHORT).show();
                        }
                        spinner.setVisibility(View.GONE);
                        canRefresh = false;
                        hasMore = false;
                    }
                });
            }
        }
    }).start();
}

From source file:com.dhamacher.sentimentanalysis4tweets.twitterapi.TweetOperator.java

License:Apache License

public LinkedList<Long> getFollowerIds(String user) {
    try {/*from w w  w. j  a  v  a 2s .c o  m*/
        long cursor = -1;
        LinkedList<Long> res = new LinkedList<Long>();
        IDs ids;
        do {
            ids = twitter.getFollowersIDs(user, cursor);
            for (long id : ids.getIDs()) {
                res.add(id);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        return res;

    } catch (TwitterException ex) {
        Logger.getLogger(TweetOperator.class.getName()).log(Level.SEVERE, null, ex);
        return new LinkedList<Long>();
    }
}

From source file:com.dhamacher.sentimentanalysis4tweets.twitterapi.TweetOperator.java

License:Apache License

public LinkedList<Long> getFollowerIds(long userId) {
    try {//from w w w .  j  a v  a 2s  . co m
        long cursor = -1;
        LinkedList<Long> res = new LinkedList<Long>();
        IDs ids;
        do {
            ids = twitter.getFollowersIDs(userId, cursor);
            for (long id : ids.getIDs()) {
                res.add(id);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        return res;

    } catch (TwitterException ex) {
        Logger.getLogger(TweetOperator.class.getName()).log(Level.SEVERE, null, ex);
        return new LinkedList<Long>();
    }
}