com.happy_coding.viralo.twitter.FriendDiscoverer.java Source code

Java tutorial

Introduction

Here is the source code for com.happy_coding.viralo.twitter.FriendDiscoverer.java

Source

/**
 * Copyright (C) 2012 Happy Coding <contact@happy-coding.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.happy_coding.viralo.twitter;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.IDs;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * My class for discovering friends.
 */
public class FriendDiscoverer {

    public static final int MAX_FRIENDS_ITERATIONS = 2;
    public static final int FRIENDS_PER_PAGE = 100;
    public static final int WAIT_BETWEEN_KEYWORD_SEARCH_IN_MS = 2000;
    private Logger logger;

    public FriendDiscoverer() {
        logger = LoggerFactory.getLogger(getClass());
    }

    /**
     * retrieve friends by keywords.
     *
     * @param keywords
     * @param delimiter
     * @return
     */
    public List<Contact> findFriends(String keywords, String delimiter) {

        Iterable<String> it = Splitter.on(delimiter).trimResults().omitEmptyStrings().split(keywords);

        return findFriends(Lists.newArrayList(it));
    }

    /**
     * Returns list of Twitter Friends by the given keywords.
     *
     * @param keywords
     * @return
     */
    public List<Contact> findFriends(List<String> keywords) {

        Joiner joiner = Joiner.on(" ").skipNulls();

        String twitterKeywords = joiner.join(keywords);

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

        for (int i = 1; i <= MAX_FRIENDS_ITERATIONS; i++) {

            Query query = new Query(twitterKeywords);
            query.setPage(i);
            query.setRpp(FRIENDS_PER_PAGE);

            QueryResult result = null;
            try {
                result = twitter.search(query);
            } catch (TwitterException e) {
                logger.error("can't find friends", e);
                return null;
            }

            List<String> tmpFriendList = new ArrayList<String>();

            for (Tweet tweet : result.getTweets()) {
                String user = tweet.getFromUser();

                if (!tmpFriendList.contains(user)) {
                    Contact newContact = new Contact(user);
                    newContact.setUid(tweet.getFromUserId());
                    contacts.add(newContact);
                    tmpFriendList.add(user);
                }
            }
            try {
                Thread.sleep(WAIT_BETWEEN_KEYWORD_SEARCH_IN_MS);
            } catch (InterruptedException e) {
                logger.error("can't find friends", e);
                return null;
            }
        }

        return contacts;
    }

    /**
     * Returns the friends for the provided friend.
     *
     * @param forContact
     * @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;
    }

    /**
     * Returns a list of contacts which follow the provided contact.
     *
     * @param forContact
     * @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;
    }

    /**
     * Returns the current authorized user as Contact.
     *
     * @return
     */
    public Contact returnMyself() {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            Contact me = new Contact(twitter.getId());
            me.setName(twitter.getScreenName());
            return me;
        } catch (TwitterException e) {
            logger.error("can't get myself", e);
            return null;
        }
    }
}