Example usage for twitter4j Twitter getFriendsList

List of usage examples for twitter4j Twitter getFriendsList

Introduction

In this page you can find the example usage for twitter4j Twitter getFriendsList.

Prototype

PagableResponseList<User> getFriendsList(long userId, long cursor) throws TwitterException;

Source Link

Document

Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues.

Usage

From source file:com.epsi.wks.api_wks_back.User.java

@GET
@Path("/following/tweet")
@Produces("application/json")
public List<JSONObject> getUserFollowingsTweets(@PathParam("id") long userID) {
    Twitter twitter = UtilConfig.getTwitterInstance();

    List<JSONObject> followingTweet = new ArrayList<>();
    try {/*from   w  ww. j  ava2  s.  c o  m*/
        PagableResponseList<twitter4j.User> userList = twitter.getFriendsList(userID, -1);

        for (twitter4j.User us : userList) {
            List<Status> statusFollower = twitter.getUserTimeline(us.getId());
            for (Status sts : statusFollower) {
                JSONObject tweet = new JSONObject();
                tweet.put("id", sts.getId());
                tweet.put("text", sts.getText());
                tweet.put("screen_name", sts.getUser().getScreenName());
                tweet.put("name", sts.getUser().getName());
                tweet.put("image_url", sts.getUser().getProfileImageURL());
                followingTweet.add(tweet);
            }
        }
    } catch (TwitterException e) {
    }
    System.out.println("array" + String.valueOf(followingTweet.size()));
    return followingTweet;
}

From source file:com.klinker.android.twitter.ui.profile_viewer.fragments.ProfileFragment.java

License:Apache License

public void getFollowing(final User user, final AsyncListView listView) {
    spinner.setVisibility(View.VISIBLE);
    canRefresh = false;/*from   w  w w .j  av  a2s.  c o m*/

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

                PagableResponseList<User> friendsPaging;
                try {
                    friendsPaging = twitter.getFriendsList(user.getId(), currentFollowing);
                } catch (OutOfMemoryError e) {
                    return;
                }

                for (int i = 0; i < friendsPaging.size(); i++) {
                    following.add(friendsPaging.get(i));
                    Log.v("friends_list", friendsPaging.get(i).getName());
                }

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

                currentFollowing = friendsPaging.getNextCursor();

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (followingAdapter == null) {
                            followingAdapter = new PeopleArrayAdapter(context, following);
                            listView.setAdapter(followingAdapter);
                        } else {
                            followingAdapter.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() {
                        try {
                            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);
                        } catch (Exception e) {
                            // fragment not attached
                        }
                        canRefresh = false;
                        hasMore = false;
                    }
                });
            }
        }
    }).start();
}

From source file:com.zisal.twit.crawl.core.Example.java

public static void main(String[] args) {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ApplicationConstant.TwitterKey.CUSTOMER_KEY,
            ApplicationConstant.TwitterKey.CUSTOMER_SECRET);
    twitter.setOAuthAccessToken(//from   w ww .j ava2  s  . co m
            new AccessToken(ApplicationConstant.TwitterKey.TOKEN, ApplicationConstant.TwitterKey.TOKEN_SECRET));
    /*try{
    ResponseList<Status> responseList = twitter.getUserTimeline(new Paging(1, 5));
    for(Status s: responseList){
        System.out.println("Response List ".concat(s.getText()));
    }
    }catch(Exception e){
    e.printStackTrace();
    }
            
    long cursor = -1;
    IDs ids = null;
    System.out.println("Listing followers's ids.");
    do {
    try {
        ids = twitter.getFollowersIDs(ApplicationConstant.Twitter.SCREEN_NAME, cursor);
        for (long id : ids.getIDs()) {
            System.out.println(id);
            User user = twitter.showUser(id);
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
    } while ((cursor = ids != null ? ids.getNextCursor() : 0) != 0);*/

    long cursor = -1;
    PagableResponseList<User> pagableFollowings = null;
    List<User> listFriends = new ArrayList<>();
    do {
        try {
            pagableFollowings = twitter.getFriendsList(18211861, cursor);
            for (User user : pagableFollowings) {
                listFriends.add(user);
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend #1st level " + user.getName());
                /*PagableResponseList<User> _2ndLevelPageableFollowings = twitter.getFriendsList(user.getId(), cursor);
                for(User _2ndLevelFriend : _2ndLevelPageableFollowings){
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "added friend #2nd level "+ _2ndLevelFriend.getName());
                listFriends.add(_2ndLevelFriend);
                }*/
            }
        } catch (TwitterException e) {
            e.printStackTrace();
        }

    } while ((cursor = pagableFollowings.getNextCursor()) != 0);

    logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend total : " + listFriends.size());
    for (User user : listFriends) {
        logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend : " + user.getName());
    }

    /*
            cursor = -1;
            PagableResponseList<User> pagableFollowers = null;
            List<User> listFollowers = new ArrayList<>();
            do {
    try {
        pagableFollowers = twitter.getFollowersList(twitter.getId(), cursor);
        for (User user : pagableFollowers) {
            listFollowers.add(user); // ArrayList<User>
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
            
            } while ((cursor = pagableFollowers.getNextCursor()) != 0);
    */

}

From source file:d3V.GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFollowersIDs [screen name]
 *
 * @param args message/*from ww  w.j  av  a 2  s .  c  o m*/
 */
public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Em3WTI7jc90HcvKzPkTLQ")
            .setOAuthConsumerSecret("vg4p6rOF32bmffqRR8m0jAUClrxvtGiMB5PrSr3Zsw")
            .setOAuthAccessToken("1681973072-1q0zI0VPjHD3ttNuaBOL94frzCI9sXInxAcDK0w")
            .setOAuthAccessTokenSecret("ZRLkOyjmhHBkU1iNyEVNyIgIBsKrl0DUDKOcOMneYFYEM");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    try {
        String core_user = "nytimes";
        FileWriter writer = new FileWriter(core_user + "_friends.txt", true);
        Twitter twitter = tf.getInstance();

        long cursor = -1;
        ArrayList<String> directFriends = new ArrayList<String>();
        PagableResponseList<User> tempFriends = null;

        System.out.println("Listing " + core_user + " friends's ScreenNames.");
        int count = 0;
        //boolean first = true;
        //getFriends(writer, twitter, cursor, count, core_user);
        do {
            tempFriends = twitter.getFriendsList(core_user, cursor);

            for (User user : tempFriends) {
                directFriends.add(user.getScreenName());
                writer.write(core_user + "\t" + user.getScreenName() + "\n");
            }

            count += tempFriends.size();
            System.out.println(core_user + ": " + count);
            if (count >= 100)
                break;

            Thread.sleep(300 * MILLISECOND);

        } while ((cursor = tempFriends.getNextCursor()) != 0);

        System.out.println("Size of DFs: " + directFriends.size());

        //            for (String user : directFriends){
        for (int i = 0; i < directFriends.size(); i++) {
            //                PagableResponseList<User> idrfriends = null;
            long _cursor = -1;
            int _count = 0;
            String _username = directFriends.get(i);
            System.out.println("\nFriends of Direct friend: " + _username + "(" + (i + 1) + ")");
            try {
                getFriends(writer, twitter, _cursor, _count, _username);
            } catch (TwitterException e) {
                e.printStackTrace();
                System.out.println("Failed to get friends' ids: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        writer.close();
        System.out.println(count);
        System.exit(0);
    } catch (TwitterException e) {
        e.printStackTrace();
        System.out.println("Failed to get friends' ids: " + e.getMessage());
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:d3V.GetFriendsIDs.java

License:Apache License

public static void getFriends(FileWriter writer, Twitter twitter, long _cursor, int _count, String _username)
        throws TwitterException, IOException, InterruptedException {
    PagableResponseList<User> idrfriends;
    do {//from  w  ww  . j  a  va 2  s .com
        idrfriends = twitter.getFriendsList(_username, _cursor);
        for (User _user : idrfriends) {
            writer.write(_username + "\t" + _user.getScreenName() + "\n");
        }
        _count += idrfriends.size();
        System.out.println(_username + ": " + _count);
        if (_count >= 40)
            break;

        Thread.sleep(300 * MILLISECOND);
    } while ((_cursor = idrfriends.getNextCursor()) != 0);
}

From source file:de.vanita5.twittnuker.loader.support.UserFriendsLoader.java

License:Open Source License

@Override
protected PagableResponseList<User> getCursoredUsers(final Twitter twitter, final CursorPaging paging)
        throws TwitterException {
    if (twitter == null)
        return null;
    if (mUserId > 0)
        return twitter.getFriendsList(mUserId, paging);
    else if (mScreenName != null)
        return twitter.getFriendsList(mScreenName, paging);
    return null;/*from  w w  w .j  av a  2  s . c o  m*/
}

From source file:examples.GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFriendsIDs [screen name]
 *
 * @param args message/*from   w ww . ja v a 2  s . c  o m*/
 */
public static void main(String[] args) {
    try {
        Twitter twitter = CommonUtils.getTwitterInstance();
        long cursor = -1;
        PagableResponseList<User> userList;
        System.out.println("Listing following ids.");
        do {
            userList = twitter.getFriendsList("tsantoo", cursor);
            for (User user : userList) {
                System.out.println(user.toString());
            }
        } while ((cursor = userList.getNextCursor()) != 0);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get friends' ids: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:org.getlantern.firetweet.loader.support.UserFriendsLoader.java

License:Open Source License

@Override
protected PageableResponseList<User> getCursoredUsers(final Twitter twitter, final CursorPaging paging)
        throws TwitterException {
    if (twitter == null)
        return null;
    if (mUserId > 0)
        return twitter.getFriendsList(mUserId, paging);
    else if (mScreenName != null)
        return twitter.getFriendsList(mScreenName, paging);
    return null;/*from w ww  .  jav  a2 s.co m*/
}

From source file:org.wso2.carbon.connector.twitter.TwitterGetFriends.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    if (log.isDebugEnabled()) {
        log.info("executing twitter get user time line");
    }//from w w  w . jav  a 2s .co  m

    try {

        String screenName = (TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME).isEmpty())

                        ? TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME)
                        : null;

        String userID = (TwitterUtils.lookupTemplateParamater(messageContext, USER_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, USER_ID).isEmpty())

                        ? TwitterUtils.lookupTemplateParamater(messageContext, USER_ID)
                        : null;

        String count = (TwitterUtils.lookupTemplateParamater(messageContext, COUNT) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, COUNT).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, COUNT)
                        : null;

        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();

        List<User> results = null;

        if (screenName != null && !screenName.isEmpty()) {
            if (count != null && !count.isEmpty()) {
                results = twitter.getFriendsList(screenName, Long.parseLong(count));
            } else {
                results = twitter.getFriendsList(screenName, -1);
            }
        } else if (userID != null && !userID.isEmpty()) {
            if (count != null && !count.isEmpty()) {
                results = twitter.getFriendsList(Long.parseLong(userID), Long.parseLong(count));
            } else {
                results = twitter.getFriendsList(Long.parseLong(userID), -1);
            }
        }

        if (log.isDebugEnabled()) {
            log.error("Retrived results : " + results.toString());
        }

        OMElement element = this.performSearchMessages(results);

        super.preparePayload(messageContext, element);

    } catch (TwitterException te) {
        log.error("Failed to search twitter : " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
        log.error("Failed to search generic: " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
}

From source file:peoplesearch.FindFriendsAndFollowers.java

public void GetFollowersIDs() {
    try {/*from  ww w  .j a  va 2 s .c o  m*/
        // I need to pass the Person name and the TwitterID.
        //String targetname="Philip Bergkvist";
        Twitter twitter = new TwitterFactory().getInstance();
        long cursor = -1;
        IDs ids;

        ResponseList<User> users1 = null;
        ResponseList<User> users2 = null;
        System.out.println("Listing followers's ids.");

        GraphManager mgr = EmbeddedGraphManager.getInstance();

        mgr.init(new File("/usr/local/Cellar/neo4j/2.1.7/libexec/data/forlang1.db"));
        //mgr.addTwitterAccount(new TwitterAccountImpl(new Date(), "I am Studying", 13, 82, true,"Aalborg", "Philiptwoshoes", 2730631792L));
        List<TwitterAccount> twitteraccountslist;
        twitteraccountslist = null;
        twitteraccountslist = mgr.listTwitterAccounts();
        System.out.println("the number of twitter account in the neo4J DB is" + twitteraccountslist.size());
        for (TwitterAccount Twit : twitteraccountslist) {

            do {
                TwitterLimitWait tlw = new TwitterLimitWait();
                tlw.CheckLimit();

                if (0 < twitteraccountslist.size()) {
                    ids = twitter.getFollowersIDs(Twit.getScreenName(), cursor); //.getFollowersIDs(pep[0], cursor);
                    //ids = twitter.getFollowersIDs("Philiptwoshoes", cursor); //.getFollowersIDs(pep[0], cursor);
                    tlw.CheckLimit();
                    users1 = twitter.getFollowersList(Twit.getScreenName(), cursor);
                    tlw.CheckLimit();
                    users2 = twitter.getFriendsList(Twit.getScreenName(), cursor);

                } else {
                    tlw.CheckLimit();
                    ids = twitter.getFollowersIDs(cursor);

                }

                for (User user : users1) {
                    tlw.CheckLimit();
                    System.out.println("the follower called " + user.getName() + " with twitter handler "
                            + user.getScreenName());
                    String username = user.getName();
                    //mgr.addPerson(new PersonImpl(username));
                    Date Creation = user.getCreatedAt();
                    tlw.CheckLimit();
                    String descript = user.getDescription();
                    boolean empty1 = user.getDescription().isEmpty();
                    if (empty1 == true) {
                        descript = " ";
                    }
                    tlw.CheckLimit();
                    int followers = user.getFollowersCount();
                    tlw.CheckLimit();
                    int following = user.getFriendsCount();
                    boolean geo = user.isGeoEnabled();
                    String loc = user.getLocation();
                    boolean empty2 = user.getLocation().isEmpty();
                    if (empty2 == true) {
                        loc = " ";
                    }
                    String screenname = user.getScreenName();
                    boolean empty3 = user.getScreenName().isEmpty();
                    if (empty3 == true) {
                        screenname = " ";
                    }
                    tlw.CheckLimit();
                    long twitID = user.getId();

                    mgr.linkPersonToTwitterAccount(new PersonImpl(username), new TwitterAccountImpl(Creation,
                            descript, followers, following, geo, loc, screenname, twitID));
                    mgr.linkTwitterAccounts(new TwitterAccountImpl(Creation, descript, followers, following,
                            geo, loc, screenname, twitID), Twit);
                }

                System.out.println("The total number of followers is: " + users1.size());
                // the same procedure for the Following
                for (User user : users2) {
                    tlw.CheckLimit();
                    System.out.println("the following called " + user.getName() + " with twitter handler "
                            + user.getScreenName());
                    String username1 = user.getName();
                    //mgr.addPerson(new PersonImpl(username1));
                    Date Creation = user.getCreatedAt();
                    String descript = user.getDescription();
                    boolean empty1 = user.getDescription().isEmpty();
                    if (empty1 == true) {
                        descript = " ";
                    }
                    int followers = user.getFollowersCount();
                    int following = user.getFriendsCount();
                    boolean geo = user.isGeoEnabled();
                    String loc = user.getLocation();
                    boolean empty2 = user.getLocation().isEmpty();
                    if (empty2 == true) {
                        loc = " ";
                    }
                    String screenname = user.getScreenName();
                    tlw.CheckLimit();
                    boolean empty3 = user.getScreenName().isEmpty();
                    if (empty3 == true) {
                        screenname = " ";
                    }
                    tlw.CheckLimit();
                    long twitID = user.getId();
                    //mgr.addTwitterAccount(new TwitterAccountImpl(Creation,descript,followers,following,geo,loc,screenname,twitID));
                    mgr.linkPersonToTwitterAccount(new PersonImpl(username1), new TwitterAccountImpl(Creation,
                            descript, followers, following, geo, loc, screenname, twitID));
                    mgr.linkTwitterAccounts(Twit, new TwitterAccountImpl(Creation, descript, followers,
                            following, geo, loc, screenname, twitID));
                }
                System.out.println("The total number of friend is: " + users2.size());

                //}
            } while ((cursor = ids.getNextCursor()) != 0);

        }
        mgr.destroy(); // I have to check that the second iteration works fine, because i could not test that.
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
}