de.dev.eth0.retweeter.Retweeter.java Source code

Java tutorial

Introduction

Here is the source code for de.dev.eth0.retweeter.Retweeter.java

Source

package de.dev.eth0.retweeter;

import de.dev.eth0.retweeter.Config.RetweeterConfig;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.*;

/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE":
* <amuthmann@dev-eth0.de> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return
* ----------------------------------------------------------------------------
*/
/**
 * Class used for retweets defined in config
 *
 * @author deveth0
 */
public class Retweeter extends AbstractTwitterClient {

    private final static Logger logger = LoggerFactory.getLogger(Retweeter.class);
    private final Set<Long> ALREADY_RETWEETED = new HashSet<Long>();

    /**
     * Constructor
     *
     * @param _config
     */
    public Retweeter(Config _config) {
        super(_config);
    }

    /**
     * Performs the retweet-action and returns the number of tweets found with the configured hashtag
     *
     * @return number of retweeted tweets
     * @throws TwitterException
     */
    public int retweet() throws TwitterException {
        if (!getConfig().isRetweeterConfigValid()) {
            return Integer.MIN_VALUE;
        }
        Twitter twitter = getTwitter();
        String search = buildSearchString();
        Query query = new Query(search);
        QueryResult result = twitter.search(query);

        List<Status> lastretweets = twitter.getRetweetedByMe();
        int count = 0;
        for (Tweet tweet : result.getTweets()) {
            // ignore retweets and check if the hashtag is really in the tweet's text
            if (!StringUtils.startsWith(tweet.getText(), "RT @")
                    && StringUtils.contains(tweet.getText(), getConfig().getRetweeterConfig().getHashtag())
                    && !ALREADY_RETWEETED.contains(tweet.getId())) {
                boolean retweeted = false;
                for (Status retweet : lastretweets) {
                    if (tweet.getId() == retweet.getRetweetedStatus().getId()) {
                        retweeted = true;
                        break;
                    }
                }
                if (!retweeted) {
                    // try to retweet, might fail
                    logger.debug("found new tweet to retweet: {}", tweet.toString());
                    try {
                        twitter.retweetStatus(tweet.getId());
                        count++;
                    } catch (TwitterException te) {
                        logger.debug("retweet failed", te);
                    } finally {
                        ALREADY_RETWEETED.add(tweet.getId());
                    }
                }
            }
        }
        return count;
    }

    /**
     * Builds the searchstring, format #HASHTAG from user1 OR user2 ...
     *
     * @return searchstring
     */
    private String buildSearchString() {
        StringBuilder sb = new StringBuilder();
        RetweeterConfig rc = getConfig().getRetweeterConfig();
        sb.append(rc.getHashtag());
        sb.append(" ");
        for (int i = 0; i < rc.getAccounts().size(); i++) {
            if (i > 0) {
                sb.append(" OR ");
            }
            sb.append("from:");
            sb.append(rc.getAccounts().get(i));
        }
        String ret = sb.toString();
        logger.debug("SearchString: " + ret);
        return ret;
    }
}