Example usage for twitter4j Twitter search

List of usage examples for twitter4j Twitter search

Introduction

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

Prototype

QueryResult search(Query query) throws TwitterException;

Source Link

Document

Returns tweets that match a specified query.

Usage

From source file:samples.TwitterSentiment.java

private static String[] get_twits(Date tempdate, String querystr) {

    ArrayList<String> res = new ArrayList<String>();
    try {//from   w w w  .j a  v a 2s. c  om
        twitter4j.Twitter twitter = getTwitter();

        Query query = new Query(querystr);
        query.setCount(5000);
        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {
            //System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
            res.add("@" + status.getUser().getScreenName() + ":" + status.getText());
        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterSentiment.class.getName()).log(Level.SEVERE, null, ex);
    }

    return res.toArray(new String[] {});
}

From source file:StringMatching.GetTweet.java

/**
 * @param args the command line arguments
 *//*from  ww  w  .ja v  a2s  .co m*/
public static void main(String[] args) throws JSONException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH")
            .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK")
            .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA")
            .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC")
            .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("jonathan.benedict")
            .setHttpProxyPassword("rollingonthefloor");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    JSONObject obj = new JSONObject();
    int counterTweet = 0;
    FileWriter file = new FileWriter("C:\\Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt");
    file.flush();
    try {
        Query query = new Query("barca".toLowerCase());
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                counterTweet++;
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                obj.put("user", tweet.getUser().getScreenName());
                obj.put("tweets", tweet.getText());

                //Tulis file ke dalam txt

                try {
                    file.write(obj.toString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + obj);

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        } while (counterTweet < 1000);

        file.close();
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.exit(0);
}

From source file:summarizer.NewApplication.java

private void HashtagSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HashtagSearchButtonActionPerformed
    // TODO add your handling code here:
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("uEeExq1FHARMvAGTJAY0dGxPh")
            .setOAuthConsumerSecret("jMcofTKFsayd4bpA6HFNlgkMfiveoS3ffRSCy9FCSs9pWYqdAD")
            .setOAuthAccessToken("2443437752-PrbVsDrQCxthX3T7lV3dtHs3FCXFXfBBHsdNrOS")
            .setOAuthAccessTokenSecret("MbauBu7R6vUUKqFD9ogK7VTIfce4nmvewYsgYqBOQ2ZbC");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    String hashtag;// ww  w .  j  av a 2s .co m
    hashtag = HashtagTextField.getText();
    Query query = new Query(hashtag);
    query.count(100);
    if (TwitterComboBox.getSelectedIndex() == 0) {
        query.resultType(Query.ResultType.mixed);
    } else if (TwitterComboBox.getSelectedIndex() == 0) {
        query.resultType(Query.ResultType.recent);
    } else {
        query.resultType(Query.ResultType.popular);
    }
    QueryResult result = null;
    try {
        result = twitter.search(query);
    } catch (TwitterException ex) {
        Logger.getLogger(NewApplication.class.getName()).log(Level.SEVERE, null, ex);
    }
    String alltweets = "", temp = "";

    for (Status status : result.getTweets()) {
        temp = status.getText();
        temp = temp.replaceAll("[\\t\\n\\r]", " ");
        if (!"".equals(temp)) {
            if ("RT".equals(temp.substring(0, 2))) {
                temp = temp.split(":", 2)[1];
            }
            alltweets += (temp + "\n");
        }
    }
    InputTextArea.setText(alltweets);
}

From source file:teambootje.TwitterAPI.java

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

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        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:timeline.CmdSearchTerm.java

License:Apache License

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, IOException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length != 6)) {

        System.err.println("Please provide command as following.");
        System.err.println("java -cp twitter4j-multi-oauth-0.5.jar "
                + "timeline.CmdSearchTerm consumer_key consumer_secret" + " user_token user_secret output_path "
                + "term ");
        System.exit(-1);// w ww  . j  a v  a2s  .c o m
    }

    AppOAuth AppOAuths = new AppOAuth();
    String endpoint = "/search/tweets";

    String consumer_key = null;
    try {
        consumer_key = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    String consumer_secret = null;
    try {
        consumer_secret = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument" + args[1] + " must be an String.");
        System.exit(-1);
    }
    String user_token = null;
    try {
        user_token = StringEscapeUtils.escapeJava(args[2]);
    } catch (Exception e) {
        System.err.println("Argument" + args[2] + " must be an String.");
        System.exit(-1);
    }
    String user_secret = null;
    try {
        user_secret = StringEscapeUtils.escapeJava(args[3]);
    } catch (Exception e) {
        System.err.println("Argument" + args[3] + " must be an String.");
        System.exit(-1);
    }

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[4]);
    } catch (Exception e) {
        System.err.println("Argument" + args[4] + " must be an String.");
        System.exit(-1);
    }

    String term = "";
    try {
        term = StringEscapeUtils.escapeJava(args[5]);
    } catch (Exception e) {
        System.err.println("Argument" + args[5] + " must be an String.");
        System.exit(-1);
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, consumer_key, consumer_secret, user_token,
                user_secret);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls - 2;
        int RemainingCallsCounter = 0;
        System.out.println("Remianing Calls: " + RemainingCalls);

        // screen_name / user_id provided by arguments
        System.out.println("Trying to create output directory");
        String filesPath = OutputDirPath + "/";
        File theDir = new File(filesPath);

        // If the directory does not exist, create it
        if (!theDir.exists()) {

            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        String fileName = filesPath + term.replace(" ", "");
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");

        Query query = new Query(term);
        QueryResult result;

        List<Status> statuses = new ArrayList<>();
        int totalTweets = 0;
        int numberOfTweetsToGet = 5000;
        long lastID = Long.MAX_VALUE;

        while (totalTweets < numberOfTweetsToGet) {
            if (numberOfTweetsToGet - totalTweets > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweetsToGet - totalTweets);
            }
            try {
                result = twitter.search(query);
                statuses.addAll(result.getTweets());

                if (statuses.size() > 0) {
                    for (Status status : statuses) {
                        String rawJSON = TwitterObjectFactory.getRawJSON(status);
                        writer.println(rawJSON);

                        totalTweets += 1;

                        if (status.getId() < lastID) {
                            lastID = status.getId();
                        }
                    }
                } else {
                    break;
                }
                System.out.println("totalTweets: " + totalTweets);
                statuses.clear();

            } catch (TwitterException e) {
                // e.printStackTrace();

                System.out.println("Tweets Get Exception: " + e.getMessage());

                // If rate limit reached then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    System.out.println("No more remianing calls");
                }

                if (totalTweets < 1) {
                    writer.close();
                    // Remove file if tweets not found
                    File fileToDelete = new File(fileName);
                    fileToDelete.delete();
                    break;
                }
            }
            query.setMaxId(lastID - 1);

            // If rate limit reached then switch Auth user
            RemainingCallsCounter++;
            if (RemainingCallsCounter >= RemainingCalls) {

                System.out.println("No more remianing calls");
                break;
            }
        }

        if (totalTweets > 0) {
            System.out.println("Total dumped tweets of " + term + " are: " + totalTweets);
        } else {

            // Remove file if tweets not found
            File fileToDelete = new File(fileName);
            fileToDelete.delete();
        }
        writer.close();
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get term results because: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:tiofortwitter.TioForTwitter.java

/**
 * @param args the command line arguments
 *//*from  ww w  .j  a v  a  2s.  c om*/
public static void main(String[] args) throws JSONException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH")
            .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK")
            .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA")
            .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    JSONObject obj = new JSONObject();
    int counterTweet = 0;
    FileWriter file = new FileWriter("Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt");
    file.flush();
    try {
        Query query = new Query("Satria");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                counterTweet++;
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                obj.put("user", tweet.getUser().getScreenName());
                obj.put("tweets", tweet.getText());

                //Tulis file ke dalam txt

                try {
                    file.write(obj.toString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + obj);

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        } while (counterTweet < 1000);

        file.close();
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.exit(0);
}

From source file:tweet.Miner.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param toSearch  /*from  w ww .j  a v a 2  s .  c  om*/
 */
public List<Status> mine(String toSearch) {
    List<Status> results = new ArrayList<Status>();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
            .setOAuthAccessToken(OAUTH_ACCESS_TOKEN).setOAuthAccessTokenSecret(OAUTH_ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        Query query = new Query(toSearch);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            results.addAll(result.getTweets());
            for (Status tweet : tweets) {
                System.out.println(
                        tweet.getId() + " @ " + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);

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

    return results;
}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 */// w ww  . jav  a2s  . 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: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);/*w  w w. jav  a2 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: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 a v a  2s.co  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();
        }
    }
}