Example usage for twitter4j Query setCount

List of usage examples for twitter4j Query setCount

Introduction

In this page you can find the example usage for twitter4j Query setCount.

Prototype

public void setCount(int count) 

Source Link

Document

sets the number of tweets to return per page, up to a max of 100

Usage

From source file:sentinets.ImportTweets.java

License:Open Source License

private List<Status> getTweets(String queryStr, int countOfTweets) {
    Query query = new Query(queryStr);
    query.setCount(countOfTweets);
    query.setLang("en");
    QueryResult result = null;/*from   w  w w.ja  va  2s .c  o m*/
    List<Status> tweets = new ArrayList<Status>();
    do {
        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("Failed to search tweets: " + e.getMessage());

        }
        tweets.addAll(result.getTweets());
    } while ((query = result.nextQuery()) != null && tweets.size() <= countOfTweets);
    return tweets;
}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void search(HashMap args) {
    KrollDict arg = new KrollDict(args);
    Query query = new Query(arg.getString("query"));
    query.setLang(arg.optString("lang", ""));
    query.setCount(arg.optInt("count", 20));
    if (arg.optString("since", "") != "") {
        query.setSince(arg.getString("since"));
    }// w  w w  . jav a  2 s .  c  o  m
    desc = arg.optBoolean("descending", false);
    success = (KrollFunction) arg.get("success");
    lastID = Long.parseLong(arg.optString("lastID", "-1"));
    twitter.search(query);
}

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 .j a  va2 s. co  m
     ** 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);//from w ww  .j  a  v a  2  s.  c om
    }

    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:tweet.Miner.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param toSearch  /*from  w  w w  . ja v a 2  s  . co m*/
 */
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:tweetdownloader.cnr_stable.version.TweetDownload.java

/**
 * this method return an ArrayList of dataOfTweets
 * @param allMyTweets/*from   ww  w. ja va 2  s . c om*/
 * @return allMyTweet
 */
public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) {
    {
        try {
            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
            for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
                dataOfTweet tweet = new dataOfTweet();

                //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                if (searchTweetsRateLimit.getRemaining() == 0) {
                    try {
                        //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());
                        Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                    } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                }
                Query q = new Query(SEARCH_TERM);
                q.setCount(TWEETS_PER_QUERY);
                q.setLang("it");

                if (maxID != -1) {
                    q.setMaxId(maxID - 1);
                }

                QueryResult r = twitter.search(q);

                if (r.getTweets().isEmpty()) {
                    break;
                }
                for (Status s : r.getTweets()) {

                    totalTweets++;
                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }
                    if (s.isRetweeted() == false) {

                        tweet.setUsername(s.getUser().getScreenName());
                        tweet.setCreatedAt(s.getCreatedAt().toString());
                        tweet.setTweetText(s.getText());

                        if (s.getGeoLocation() != null) {
                            tweet.setLat(s.getGeoLocation().getLatitude());
                            tweet.setLongi(s.getGeoLocation().getLongitude());
                        }
                    }
                }
                allMyTweets.add(tweet);
            }
        } catch (TwitterException ex) {
            java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return allMyTweets;
}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *//*from  w ww.  ja  v  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);
    QueryResult result;/* ww w. j a  v  a 2 s  .c  o m*/
    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 .ja  va  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();
        }
    }
}

From source file:TwitterDownload.TwitterHandler.java

public List<Status> getSearchTweets(String searchPhrase, int pageSize) {
    if (pageSize > 18000)
        pageSize = 18000;/*  w  w w .j  a va  2s  .  c o  m*/

    ArrayList<Status> tweets = new ArrayList<Status>();
    //boolean last = false;

    try {
        Query query = new Query(searchPhrase);

        int limit = getRemainingSearchRateLimit();

        while (tweets.size() < pageSize && query != null && limit > 0) {
            if (pageSize - tweets.size() > 100)
                query.setCount(100);
            else
                query.setCount(pageSize - tweets.size());

            QueryResult result = twitter.search(query);

            tweets.addAll(result.getTweets());

            query = result.nextQuery();

            limit = getRemainingSearchRateLimit();
        }

        return (List<Status>) tweets;
    } catch (TwitterException ex) {
        String s = ex.toString();
        if (ex.exceededRateLimitation())
            return null;
    } catch (IllegalStateException ex) {
        String s = ex.toString();
    }
    return null;
}