Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

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

Prototype

public Query(String query) 

Source Link

Usage

From source file:org.primefaces.examples.mobile.TwitterView.java

License:Open Source License

public void search() {
    try {/* w  w w  .j ava 2s  .c o m*/
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(keyword);
        tweets = twitter.search(query).getTweets();
    } catch (TwitterException exception) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Please try again");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        RequestContext.getCurrentInstance().update("main:messages");
    }
}

From source file:org.primefaces.examples.service.TwitterAPIService.java

License:Apache License

public List<Status> asyncSearch(String query) {

    TwitterListener listener = new TwitterAdapter() {
        @Override/*from   w w  w  .  ja  v a  2  s.co m*/
        public void searched(QueryResult queryResult) {
            asyncTweets = queryResult.getTweets();
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            logger.severe(e.getMessage());
        }
    };

    AsyncTwitter twitter = new AsyncTwitterFactory().getInstance();
    twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret));
    twitter.addListener(listener);
    Query q = new Query(query);
    twitter.search(q);
    return asyncTweets;
}

From source file:org.rhq.plugins.twitter.FeedComponent.java

License:Open Source License

/**
 * Gather measurement data/*from   w w  w  .j  a v a  2s  .co m*/
 *  @see org.rhq.core.pluginapi.measurement.MeasurementFacet#getValues(org.rhq.core.domain.measurement.MeasurementReport, java.util.Set)
 */
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {

    for (MeasurementScheduleRequest req : metrics) {
        if (req.getName().equals("tweetCount")) {
            Twitter twitter = tFactory.getInstance();
            Paging paging = new Paging();

            MeasurementDataNumeric res;
            if (isSearch) {
                Query q = new Query(keyword);
                q.setSinceId(lastId);
                if (lastId == NOT_YET_SET)
                    q.setRpp(1);
                else
                    q.setRpp(20);
                QueryResult qr = twitter.search(q);
                List<Tweet> tweets = qr.getTweets();
                res = new MeasurementDataNumeric(req, (double) tweets.size());

                eventPoller.addTweets(tweets);
                if (tweets.size() > 0)
                    lastId = tweets.get(0).getId();
            } else {
                List<Status> statuses;
                if (lastId == NOT_YET_SET) {
                    paging.setCount(1);
                } else {
                    paging.setCount(100);
                }
                paging.setSinceId(lastId);
                statuses = twitter.getUserTimeline(keyword, paging);
                res = new MeasurementDataNumeric(req, (double) statuses.size());

                eventPoller.addStatuses(statuses);
                if (statuses.size() > 0)
                    lastId = statuses.get(0).getId();

            }
            report.addData(res);
        }
    }
}

From source file:org.richfaces.examples.tweetstream.dataserver.source.TwitterSourceLocal.java

License:Open Source License

@Override
public void fetchContent() {
    //Check if updating content is needed
    //If not skip because this can be called on every page load
    System.out.println("&&&&&&&&&&& fetchContent\n\n\n\n\n");
    if (false) {/*from   w  w w . ja  va 2  s  .  co m*/
        //      if (performSearch())
        {
            twitterAggregate = new TwitterAggregate();

            Twitter twitter = new TwitterFactory().getInstance();
            List<twitter4j.Tweet> t4jTweets = null;
            try {
                Query query = new Query(TRACK);
                QueryResult result = twitter.search(query);
                t4jTweets = result.getTweets();
                for (twitter4j.Tweet t4jTweet : t4jTweets) {
                    log.info("@" + t4jTweet.getFromUser() + " - " + t4jTweet.getText());

                    //Create a local tweet object from the t4j
                    Tweet tweet = new Tweet();
                    tweet.setText(t4jTweet.getText());
                    tweet.setId(t4jTweet.getFromUserId());
                    tweet.setProfileImageUrl(t4jTweet.getProfileImageUrl());
                    tweet.setScreenName(t4jTweet.getFromUser());
                    tweet.setHashTags(TwitterAggregateUtil.pullHashtags(t4jTweet.getText()));

                    twitterAggregate = TwitterAggregateUtil.updateTwitterAggregate(tweet, twitterAggregate);
                }
            } catch (TwitterException te) {
                te.printStackTrace();
                log.info("Failed to search tweets: " + te.getMessage());
            }
        }
    }

}

From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java

License:Open Source License

/**
 * Searches for the query defined in the configuration and adds the results.
 *//*ww  w  . ja  v a  2 s . co m*/
private void search() {
    // get query from configuration
    String query = source.getPropertyValue(TwitterProperties.SEARCH_PROPERTY);

    if (query == null || query.isEmpty()) {
        return;
    }

    QueryResult searchResult = null;

    try {
        Query twitterQuery = new Query(query);
        // set requested number of tweets
        twitterQuery.setCount(getNumberOfSearchTweets());

        // add possible geo location parameter
        addSearchGeoLocation(twitterQuery);

        // if defined set since id
        String sinceId = source.getPropertyValue(TwitterProperties.SEARCH_SINCE_ID_PROPERTY);
        if (sinceId != null && !sinceId.isEmpty()) {
            long sinceIdVal = new Long(sinceId);
            twitterQuery.setSinceId(sinceIdVal);
        }
        searchResult = twitterAPI.search(twitterQuery);
    } catch (TwitterException e) {
        log("Could not search for " + query + "(" + e.getMessage() + ")", LogService.LOG_WARNING);
        return;
    }

    if (searchResult == null) {
        return;
    }

    String sinceId = parseSinceId(searchResult);

    if (sinceId != null) {
        // set it in configuration
        source.addProperty(TwitterProperties.SEARCH_SINCE_ID_PROPERTY, sinceId);
    }

    List<Status> tweets = searchResult.getTweets();

    log("Got " + tweets.size() + " tweets for search " + query, LogService.LOG_DEBUG);

    // add all tweets
    addTweetList(tweets);
}

From source file:org.thehecklers.feed.TwitterFeed.java

License:Apache License

public TwitterFeed(String query) {
    //        this.setConsumer("Put Consumer Key Here", "Put Consumer Secret Here");
    //        this.setToken("Put Token Here", "Put Token Secret Here");

    this.twInstance = TwitterFactory.getSingleton();
    ////from   w w  w. j a  va 2 s .  co m
    //        twInstance.setOAuthConsumer(this.getConsumerKey(), this.getConsumerSecret());
    //        twInstance.setOAuthAccessToken(new AccessToken(this.getToken(), this.getTokenSecret()));

    try {
        resultSet = twInstance.search(new Query(query));
        messages = resultSet.getTweets();
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterFeed.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.todoke.countsearch.Main.java

License:Apache License

static int search(String term, String date) {
    Callback callback = new Callback(new String[] { term });
    Twitter twitter = new TwitterFactory().getInstance();
    int count = 0;
    try {/*from  ww  w  .  j  a  v a 2  s .  c  o  m*/
        int page = 1;
        List<Tweet> tweets;
        do {
            Query query = new Query(term);
            query.rpp(100);
            query.until(date);
            query.setPage(page);
            QueryResult qs = twitter.search(query);
            tweets = qs.getTweets();
            boolean outOfRange = false;
            for (Tweet tweet : tweets) {

                try {
                    if (tweet.getCreatedAt().after(format.parse(date))) {
                        callback.increment(tweet.getText(), tweet.getCreatedAt());
                        count++;
                    } else {
                        //                        System.out.println(tweet.getCreatedAt());
                        outOfRange = true;
                    }
                } catch (ParseException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
            if (outOfRange) {
                break;
            }
            page++;
        } while (tweets.size() != 0);
    } catch (TwitterException e) {
        e.printStackTrace();
        //            System.exit(-1);
    }
    return count;
}

From source file:org.wandora.application.tools.extractors.twitter.AbstractTwitterExtractor.java

License:Open Source License

@Override
public boolean _extractTopicsFrom(String str, TopicMap tm) throws Exception {
    Query q = new Query(str);
    searchTwitter(new Query[] { q }, 1, tm);
    return true;//w w  w  .  j a  va  2s.  c om
}

From source file:org.wandora.application.tools.extractors.twitter.TwitterExtractorUI.java

License:Open Source License

public Query[] getSearchQuery() {
    String query = queryTextField.getText();
    String lang = langTextField.getText().trim();
    String until = untilTextField.getText().trim();
    String since = sinceTextField.getText().trim();
    GeoLocation geol = solveGeoLocation();
    double distance = solveDistance();
    ArrayList<Query> queries = new ArrayList();

    Query q = new Query(query);

    if (lang.length() > 0)
        q.setLang(lang);/*from   w  ww . j a v a  2s .  co  m*/
    if (until.length() > 0)
        q.setUntil(until);
    if (since.length() > 0)
        q.setSince(since);
    if (geol != null)
        q.setGeoCode(geol, distance, Query.KILOMETERS);

    q.count(100);

    queries.add(q);

    return queries.toArray(new Query[] {});
}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromSearch(String search, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {//w w  w.j  a va2  s.  c  o  m

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        Query query = new Query(search);
        QueryResult items = twitter.search(query);
        for (Status r : items.getTweets()) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterApi.class.getName()).log(Level.WARNING, null, ex);
        return result;
    }
}