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:edu.american.student.util.TwitterSpider.java

License:Open Source License

/**
 * Grabs the last 100 tweet objects (Status) from a handle
 * @param handle/*from w  w w.j  ava  2 s . co  m*/
 * @return
 * @throws SpiderException
 */
public static List<Status> spider(String handle) throws SpiderException {
    //connect to Twitter
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.getTwitterOAuthConsumerKey())
            .setOAuthConsumerSecret(Constants.getTwitterOAuthConsumerSecret())
            .setOAuthAccessToken(Constants.getTwitterOAuthAccessToken())
            .setOAuthAccessTokenSecret(Constants.getTwitterOAuthAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();
    //get  tweets
    Query query = new Query("from:" + handle.replace("@", ""));
    query.setCount(100);
    QueryResult result;
    try {
        result = twitter.search(query);
        List<Status> toReturn = result.getTweets();
        return toReturn;
    } catch (TwitterException e) {
        String gripe = "Twitter spider failed to...err spider!";
        throw new SpiderException(gripe, e);
    }
}

From source file:edu.mum.cs.wap.TwitterUtil.java

private static List<Status> getStatusesByKeyword(String keyword) {
    try {//from w  w w.j  a v  a2s  . c o m
        Query query = new Query("movie " + keyword + "-filter:retweets");
        query.setCount(8);
        QueryResult result;
        do {
            result = twitter.search(query);
            return result.getTweets();
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return null;
}

From source file:edu.ucsc.twitter.PeriodicTweetsSearch.java

License:Apache License

private Set<Tweet> fetch(Query tweetsQuery, int page) {
    breaker().callStarted();/*from  w  ww  .  j a  v a 2 s  . c o  m*/
    tweetsQuery.setPage(page);
    try {
        final QueryResult result = TwitterEnvironment.getTwitterService().search(tweetsQuery);
        breaker().callSucceeded();
        return Sets.newHashSet(result.getTweets());
    } catch (Exception cause) {
        System.err.println("twitter4j API failed");
        breaker().callFailed(new RuntimeException(cause));
        return ImmutableSet.of();
    }
}

From source file:edu.uml.TwitterDataMining.TwitterConsumer.java

/**
 * Search twitter with the given search term Results will be saved in a file
 * with the same name as the query//from   w  ww.  jav a  2  s .c o  m
 *
 * @param searchTerm The search term to be queried
 * @return a list of tweets
 */
public static List<Status> queryTwitter(String searchTerm) {
    Query query = new Query(searchTerm);
    query.setLang("en"); // we only want english tweets
    // get and format date to get tweets no more than a year old
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String date = sdf.format(new Date(System.currentTimeMillis() - (long) (365 * 24 * 60 * 60 * 1000)));
    query.setSince(date);
    QueryResult result;
    List<Status> tweets = null;

    try {
        //ONLY GETTING FIRST SET OF RESULTS
        result = twitter.search(query);
        tweets = result.getTweets();
        //         for (Status tweet : tweets) {
        //            System.out.println("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText());
        //         }

        // Wait loop for reset
    } catch (TwitterException te) {
        try { // try block for sleep thread
            if (!te.isCausedByNetworkIssue()) {
                // Not really checking for anything else but it is likely that we are out of requests
                int resetTime = te.getRateLimitStatus().getSecondsUntilReset();

                while (resetTime > 0) {
                    Thread.sleep(1000); // 1 second stop
                    System.out.println("seconds till reset: " + resetTime);
                    --resetTime;
                }
            } else {
                te.printStackTrace();
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            System.exit(-1);
        }

    }
    return tweets;
}

From source file:es.portizsan.twitrector.tasks.TweetSearchTask.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    long before = System.currentTimeMillis() - (1000 * 60 * 15);
    try {//w  ww  .  j  av a2  s.co m
        List<Twitrector> trl = new TwitrectorService().getTwitrectors();
        if (trl == null || trl.isEmpty()) {
            logger.log(Level.WARNING, "No Twitrectors found!!!!!");
            return;
        }
        for (Twitrector tr : trl) {
            logger.info("Searching for :" + tr.getQuery());
            String search = tr.getQuery();
            Twitter twitter = new TwitterService().getTwitterInstance();
            Query query = new Query(search);
            query.setLocale("es");
            query.setCount(100);
            if (tr.getLocation() != null) {
                GeoLocation location = new GeoLocation(tr.getLocation().getLatitude(),
                        tr.getLocation().getLongitude());
                Unit unit = Unit.valueOf(tr.getLocation().getUnit().name());
                query.setGeoCode(location, tr.getLocation().getRadius(), unit);
            }
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    if (tweet.getCreatedAt().getTime() < before)
                        continue;
                    Queue queue = QueueFactory.getQueue("default");
                    queue.add(TaskOptions.Builder.withUrl("/tasks/tweetReply")
                            .param("statusId", String.valueOf(tweet.getId()))
                            .param("message", "@" + tweet.getUser().getScreenName() + " "
                                    + String.valueOf(tr.getResponse())));

                    logger.info("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
        }
    } catch (TwitterException te) {
        logger.log(Level.WARNING, "Failed to search tweets: ", te);
    }
}

From source file:es.upm.oeg.entity.extractor.extractor.gate.TwitterCorpus.java

public void createCorpus() {

    repository = new FarolasRepo();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//from  ww  w . jav  a  2s.  c  o  m
    try {
        corpus = Factory.newCorpus("tweetcorpus");
        Query query = new Query(queryString); //"oddfarolas"
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            Document doc = Factory.newDocument(tweet.getText());
            doc.setName(String.valueOf(tweet.getId()));
            corpus.add(doc);

            logger.info(tweet.getId() + "  @" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " -"
                    + tweet.getGeoLocation());
            repository.instanciateNew(String.valueOf(tweet.getId()), tweet.getUser().getScreenName(),
                    tweet.getText(), tweet.getGeoLocation());

        }

    } catch (TwitterException te) {
        logger.error(te);
        logger.error("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    } catch (ResourceInstantiationException ex) {
        logger.error(ex);
    }
    logger.info("corpus size" + corpus.size());

}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void SearchForTermUsingGeolocation(String queryPar, int PageSize, double latitude, double longitude,
        double radius) {
    try {//from   www.  j  ava2  s  .c om
        results = new ArrayList<TwitterPostData>();

        if (queryPar != null) {
            this.pageSize = PageSize;
            this.queryPar = queryPar;
            Query query = new Query(queryPar);
            query.setPage(pageIndex);
            query.setRpp(PageSize);
            query.setResultType(Query.RECENT);
            query.setGeoCode(new GeoLocation(latitude, longitude), radius, "km");
            QueryResult result = twitter.search(query);
            ArrayList tweets = (ArrayList) result.getTweets();
            for (int i = 0; i < tweets.size(); i++) {
                results.add(new TwitterPostData((Tweet) tweets.get(i)));
            }

        }
    } catch (TwitterException ex) {
        System.err.println("Twitter Error");
        // Logger.getLogger(TwitterSearch.class.getName()).log(Level.SEVERE,
        // null, ex);
    }

}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void setNextPage() {
    results = new ArrayList<TwitterPostData>();
    pageIndex++;/*from ww w  .  j  a v  a 2s. c  o  m*/

    Query query = new Query(queryPar);
    query.setRpp(pageSize);
    query.setResultType(Query.RECENT);
    query.setPage(pageIndex);

    QueryResult result;
    try {
        result = twitter.search(query);
        ArrayList tweets = (ArrayList) result.getTweets();

        for (int i = 0; i < tweets.size(); i++) {
            results.add(new TwitterPostData((Tweet) tweets.get(i)));
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

public void setPreviousPage() {
    results = new ArrayList<TwitterPostData>();
    pageIndex--;/*from  ww w .ja  va2  s.  c  om*/

    Query query = new Query(queryPar);
    query.setRpp(pageSize);
    query.setResultType(Query.RECENT);
    query.setPage(pageIndex);

    QueryResult result;
    try {
        result = twitter.search(query);
        ArrayList tweets = (ArrayList) result.getTweets();

        for (int i = 0; i < tweets.size(); i++) {
            results.add(new TwitterPostData((Tweet) tweets.get(i)));
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void SearchForTerm(String queryPar, Integer PageSize) {
    Query query = null;/*from   www  .j a  va 2  s.  c o m*/
    try {
        results = new ArrayList<TwitterPostData>();
        this.pageSize = PageSize;
        if (queryPar != null) {

            this.queryPar = queryPar.replace("%24", "#");
            System.out.println(this.queryPar);
            query = new Query(this.queryPar);
            query.setPage(pageIndex);
            query.setRpp(PageSize);
            query.setResultType(Query.RECENT);
            QueryResult result = twitter.search(query);
            ArrayList tweets = (ArrayList) result.getTweets();
            for (int i = 0; i < tweets.size(); i++) {
                results.add(new TwitterPostData((Tweet) tweets.get(i)));
            }

        }
    } catch (TwitterException ex) {
        System.err.println(ex);
        System.err.println(query);
        // Logger.getLogger(TwitterSearch.class.getName()).log(Level.SEVERE,
        // null, ex);
    }
}