Example usage for twitter4j QueryResult getTweets

List of usage examples for twitter4j QueryResult getTweets

Introduction

In this page you can find the example usage for twitter4j QueryResult getTweets.

Prototype

List<Status> getTweets();

Source Link

Usage

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from youw twitter account based on the query string that you pass by
 * parameters./*from   w w w .  j a  v a  2s.com*/
 * @param query Query you want to place.
 * @throws FileNotFoundException
 * @throws TwitterException 
 */
public void MineFromQuery(String query) throws FileNotFoundException, TwitterException {
    Query q = new Query(query);
    QueryResult r;
    q.count(100);

    do {
        r = twitter.search(q);
        List<Status> statuses = r.getTweets();
        for (Status st : statuses) {
            GeoLocation loc = st.getGeoLocation();
            if (loc != null) {
                System.out.println("Loc not null");
                Double lat = loc.getLatitude();
                Double lon = loc.getLongitude();
                pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
            }
        }
        q = r.nextQuery();
    } while (r.hasNext());
}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *///from   ww w.  j av a  2  s .  c  o  m
public static void main(String[] args) throws Exception {

    ConfigurationBuilder configurtacion = new ConfigurationBuilder();
    configurtacion.setDebugEnabled(true).setOAuthConsumerKey("KdVOb7h8mqcjWIfkXXED2G6sJ")
            .setOAuthConsumerSecret("EXImfgfGCYIbWZIOSEeYVvaDE5oxwJZY7UIuwUusbyRWf2ds7l")
            .setOAuthAccessToken("785481406654722049-aRARaHgZujPZIdpYla4mVZIMMlvzJRb")
            .setOAuthAccessTokenSecret("YWWQwbFw8K7rxsnivwpBRZVoQlUhMYy7gOs7KUWOb8Rvy");
    Twitter twitter = new TwitterFactory(configurtacion.build()).getInstance();
    twitter.getUserTimeline();

    String hashtag = "#ElectionNight";
    Query busqueda = new Query(hashtag);
    int numeroTweets = 1500;
    long ultimo = Long.MAX_VALUE;
    ArrayList<Status> tweets = new ArrayList<Status>();

    while (tweets.size() < numeroTweets) {
        if (numeroTweets - tweets.size() > 255) {
            busqueda.setCount(255);
        } else {
            busqueda.setCount(numeroTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(busqueda);
            tweets.addAll(result.getTweets());
            System.out.println("Generados " + tweets.size() + " tweets" + "\n");
            for (Status t : tweets) {
                if (t.getId() < ultimo) {
                    ultimo = t.getId();
                }
                System.out.println("Generados " + tweets.size() + " tweets" + "\n");

            }

        } catch (TwitterException excepcion) {
            System.out.println("Sin conexin " + excepcion);
        }
        ;
        busqueda.setMaxId(ultimo - 1);
    }

    // guardamos los datos
    java.util.Date fecha = new Date();
    int hora = fecha.getHours();
    int minuto = fecha.getMinutes();
    System.out.println();
    String nombre = "Datos_" + hashtag + " " + hora + " " + minuto + ".txt";
    File f = new File(nombre);
    FileWriter fw = new FileWriter(f);
    BufferedWriter bw = new BufferedWriter(fw);

    System.out.println("identificador\tUsuario\ttweet\n");
    for (int i = 0; i < tweets.size(); i++) {
        Status estadoTweet = (Status) tweets.get(i);

        GeoLocation loc = estadoTweet.getGeoLocation();
        String user = estadoTweet.getUser().getScreenName();
        String msg = estadoTweet.getText();
        Boolean sensitive = estadoTweet.isPossiblySensitive();
        int fav = estadoTweet.getFavoriteCount();

        System.out.println("Id: " + i + "| User: " + user + "| Texto: " + msg + "| SentimientoPositivo: "
                + sensitive + "$\n");
        int id = i + 1;
        bw.append(msg + " | " + sensitive + ";");
        bw.newLine();

    }
    bw.close();
}

From source file:tweets_stock_price_prediction.TweetsManager.java

public ArrayList<String> getTweets(String topic, String fromDate, String toDate) {

    //Twitter twitter = new TwitterFactory().getInstance();
    System.out.println("*** TWITTER QUERY: " + topic);
    ArrayList<String> tweetList = new ArrayList<String>();
    try {/*w w  w . j a  v  a2  s . c o  m*/
        Query query = new Query(topic);
        query.setLang("en");
        //query.setCount(count);
        query.setSince(fromDate);
        query.setUntil(toDate);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                //System.out.print("LANGUAGE " + tweet.getLang() + "\n\n");
                //if (tweet.getLang().equals("en")) {
                tweetList.add(tweet.getText());
                //}
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }

    System.out.println("************ TWEET LIST: " + tweetList.size());
    return tweetList;
}

From source file:twit.TwitterConnector.java

/**
 * Mencari tweet yang mengandung keyword tertentu
 * @param n merupakan jumlah tweet terbaru
 * @param keyword merupakan kata kunci yang ingin dicari
 * @return List yang mengandung keyword//from   w w  w .  j  a va  2 s  .  c om
 */
public List<Status> searchKeyword(int n, String keyword) {
    try {
        query = new Query(keyword);
        query.setCount(n);
        QueryResult result;
        result = twitter.search(query);
        tweets = result.getTweets();

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return tweets;
}

From source file:twitah.Metodos.java

/**
 * Used to search for twits//  w w  w . j a va2 s.  com
 *
 * @param busca String where we enter the content to search
 */
public static void buscarTwit(String busca) {

    Query query = new Query(busca);
    QueryResult result;
    try {
        result = twitter.search(query);
        for (Status status : result.getTweets()) {
            System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());

        }
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:twitter.TweetGet.java

public void query(String queryString) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("2MZnm7LM7Ik9W3hzcXJOBaNER")
            .setOAuthConsumerSecret("0GER2kH3o1gOAyfPEDd870Iiuiu6XbQDayAXWfUBxU5APg4Le6")
            .setOAuthAccessToken("18972247-HgBP0djVaLw4U9fSX4lUdhKpZcqsJIAgnUCW3DRS5")
            .setOAuthAccessTokenSecret("bn8EQoOyGSRVUNX6elTmX9Wt9jiFJaxDaCZDk3U3hQB0g");

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    Query query = new Query(queryString);
    query.setCount(20);//from   ww  w  . j  a  v  a 2 s  .  c o m
    QueryResult result;
    try {
        result = twitter.search(query);
        tweets = result.getTweets();

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
}

From source file:TwitterAnalytics.TwitterAPI.java

public void getTweets(List<String> keywords) throws TwitterException {
    statusCache.clear();// w  ww  . j  av  a2  s .  c o  m

    Query query = makeQuery(keywords);
    query.count(maxQuery);
    QueryResult res = twitter.search(query);
    statusCache = res.getTweets();
}

From source file:twitterapi.TwitterAPI.java

public static void timeline() throws TwitterException, SQLException {
    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query("ssrotterdam");
    query.setCount(100);//from   w  w w .j ava 2s  .  c  o m
    /**
     ** setSince kan alleen tot 7 dagen terug worden gebruikt***
     */

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        String locationCity = null;
        String locationCountry = null;
        if (status.getPlace() != null) {
            cityVar = status.getPlace().getName();
            countryVar = status.getPlace().getCountry();
        } else {
            countryVar = null;
            cityVar = null;
        }

        java.util.Date utilDate = status.getCreatedAt();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        date = sqlDate;
        post = status.getText();
        screenName = status.getUser().getScreenName();
        try {
            ImportIntoSQL.TwitterImport();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:twitterAPI.Twitter_testing.java

public void getSearchTweets(String regex) {
    //String queryStr = "@RobotGrrl";
    try {//from w w w.  ja  v  a2s  . c om
        //Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(regex);
        query.count(100);
        System.out.println(query.getCount());

        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {

            searchHandler sh = new searchHandler();
            sh.nama = status.getUser().getScreenName();
            sh.tweet = status.getText();

            StringBuffer address = new StringBuffer();
            address.append("http://twitter.com/#!/");
            address.append(sh.nama);
            address.append("/status/");
            address.append(status.getId());

            String theAddressYouWant = address.toString();
            sh.URL = theAddressYouWant;
            shholder.add(sh);
            //System.out.println(theAddressYouWant); ini buat test bener apa ga url nya , udah bener
            //System.out.println("@" + sh.nama + ":" + sh.tweet);
        }
    } catch (TwitterException e) {
        System.out.println("Search tweets: " + e);
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(/* w w w  . j  ava 2 s  .co  m*/
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}