com.lbarriosh.sentimentanalyzer.downloads.TweetsDownloader.java Source code

Java tutorial

Introduction

Here is the source code for com.lbarriosh.sentimentanalyzer.downloads.TweetsDownloader.java

Source

/*******************************************************************************
 * Copyright (c) 2014 Luis Barrios Hernndez, Adrin Fernndez Hernndez
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Luis Barrios Hernndez, Adrin Fernndez Hernndez - initial API and implementation
 *******************************************************************************/
package com.lbarriosh.sentimentanalyzer.downloads;

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

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

import com.lbarriosh.sentimentanalyzer.utils.TwitterLocale;

public class TweetsDownloader {

    private TwitterFactory tf;

    public TweetsDownloader(String api_key, String api_secret, String access_token, String access_token_secret) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey(api_key);
        cb.setOAuthConsumerSecret(api_secret);
        cb.setOAuthAccessToken(access_token);
        cb.setOAuthAccessTokenSecret(access_token_secret);
        this.tf = new TwitterFactory(cb.build());
    }

    private static String buildQuery(String[] keywords) {
        StringBuilder strb = new StringBuilder();
        for (int i = 0; i < keywords.length; i++) {
            if (i == 0) {
                strb.append(keywords[i]);
            } else {
                strb.append("+").append(keywords[i]);
            }
        }
        return strb.toString();
    }

    public List<Status> downloadTweets(String[] keywords, TwitterLocale locale, int max_results)
            throws TwitterException {
        Twitter twitter = this.tf.getInstance();
        Query query = new Query(buildQuery(keywords));
        QueryResult result;
        ArrayList<Status> retrieved_tweets = new ArrayList<Status>();
        do {
            result = twitter.search(query);
            for (Status tweet : result.getTweets()) {
                if (tweet.getLang().equals(locale.toString())) {
                    retrieved_tweets.add(tweet); // Workaround. There's a bug in
                    // Twitter4j.
                }
                if (retrieved_tweets.size() == max_results)
                    break;
            }
        } while ((query = result.nextQuery()) != null && retrieved_tweets.size() < max_results);
        return retrieved_tweets;
    }
}