List of usage examples for twitter4j QueryResult getTweets
List<Status> getTweets();
From source file:org.primefaces.examples.service.TwitterAPIService.java
License:Apache License
public List<Status> asyncSearch(String query) { TwitterListener listener = new TwitterAdapter() { @Override//from ww w. j av 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 ww w. j a v a 2 s . c o 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.j a v a 2s.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.shredzone.flufftron.service.TwitterService.java
License:Open Source License
/** * Polls new fluff tweets for a {@link Person}. * * @param person//from w w w.ja v a 2 s . c om * {@link Person} to find fluff tweets for * @throws TwitterException * if the fluff tweets could not be retrieved */ public void pollNewFluffs(Person person) throws TwitterException { Timeline timeline = person.getTimeline(); String user = timeline.getTwitter(); if (user == null || user.isEmpty()) { return; } Query q = new Query().resultType("recent").rpp(50); q.query(HASHTAG + " @" + user); if (timeline.getLastId() != 0) { q.setSinceId(timeline.getLastId()); } Date lastFluff = timeline.getLastFluff(); QueryResult r = twitter.search(q); // The iterator is a workaround because twitter4j seems to be built in a funny // way that allows Generics and JDK1.4, but breaks compatibility with Java 7. Iterator<Tweet> it = r.getTweets().iterator(); while (it.hasNext()) { Tweet tweet = it.next(); if (user.equalsIgnoreCase(tweet.getFromUser())) { // ignore eigenflausch continue; } Fluff fluff = new Fluff(); fluff.setPersonId(person.getId()); fluff.setTwitId(tweet.getId()); fluff.setCreated(tweet.getCreatedAt()); fluff.setFrom(tweet.getFromUser()); fluff.setText(tweet.getText()); fluffDao.save(fluff); if (lastFluff == null || (fluff.getCreated() != null && fluff.getCreated().after(lastFluff))) { lastFluff = fluff.getCreated(); } } timeline.setLastId(r.getMaxId()); timeline.setLastFluff(lastFluff); personDao.save(person); }
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.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 w ww . j a va2s . 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.tweetalib.android.model.TwitterStatuses.java
License:Apache License
public void add(QueryResult result) { List<Status> tweets = result.getTweets(); if (tweets != null) { for (int i = 0; i < tweets.size(); i++) { Status tweet = tweets.get(i); add(new TwitterStatus(tweet)); }//from ww w. j a va2s.com } sort(); }
From source file:org.wandora.application.tools.extractors.twitter.AbstractTwitterExtractor.java
License:Open Source License
public void searchTwitter(Query[] queries, int pages, TopicMap tm) { if (tm == null || queries == null || queries.length == 0) return;/*from w ww . jav a2 s. c o m*/ initializeTwitter(); if (pin == null || pin.length() == 0) { try { AccessToken accessToken = null; String authorizationURL = requestToken.getAuthorizationURL(); TwitterAuthorizationDialog authorizer = new TwitterAuthorizationDialog(); authorizer.open(authorizationURL); if (authorizer.wasAccepted()) { pin = authorizer.getPin(); } else { return; } if (pin != null && pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException ex) { log("Invalid Twitter authorization. Please, check the PIN code '" + pin + "' and try again."); //log(ex); pin = null; return; } } try { Topic twitterSearchTopic = tm.createTopic(); if (twitterSearchTopic != null) { long stamp = System.currentTimeMillis(); twitterSearchTopic.addSubjectIdentifier(new Locator(TWITTER_SEARCH_BODY + "/" + stamp)); twitterSearchTopic.setBaseName("Twitter search " + stamp); twitterSearchTopic.addType(getTwitterSearchType(tm)); Topic twitterSearchDateType = getTwitterSearchDateType(tm); if (twitterSearchDateType != null) { Date d = new Date(stamp); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dStr = sdf.format(d); twitterSearchTopic.setData(twitterSearchDateType, TMBox.getLangTopic(twitterSearchTopic, DEFAULT_LANG), dStr); } for (Query currentQuery : queries) { if (currentQuery == null) continue; int currentPage = 0; log("Processing Twitter query '" + currentQuery.getQuery() + "'"); while (currentQuery != null) { if (forceStop()) { log("Aborting..."); break; } currentPage++; hlog("Requesting search result page " + currentPage + (pages == 0 ? "" : " of " + pages)); QueryResult result = twitter.search(currentQuery); Topic twitterSearchQueryType = getTwitterSearchQueryType(tm); if (twitterSearchQueryType != null) { twitterSearchTopic.setData(twitterSearchQueryType, TMBox.getLangTopic(twitterSearchTopic, DEFAULT_LANG), currentQuery.getQuery()); } ArrayList tweets = (ArrayList) result.getTweets(); for (Object tweet : tweets) { if (tweet != null && tweet instanceof Status) { Status t = (Status) tweet; Topic topic = reifyTweet(t, tm); topic.addType(twitterSearchTopic); } } try { Thread.currentThread().sleep(SLEEP_TIME_BETWEEN_SEARCHES); } catch (Exception e) { // ...WAKE UP... } if (pages == 0 || currentPage < pages) { currentQuery = result.nextQuery(); } else { currentQuery = null; } } log("Number of processed search result pages is " + currentPage); } } } catch (TopicMapException tme) { log("A topic map exception " + tme.getMessage() + " occurred while searching Twitter messages."); tme.printStackTrace(); } catch (TwitterException te) { log("A Twitter exception " + te.getMessage() + " occurred while searching messages."); te.printStackTrace(); } ; }
From source file:org.xmlsh.twitter.search.java
License:BSD License
@Override public int run(List<XValue> args) throws Exception { Options opts = new Options(sCOMMON_OPTS + ",q=query:,geo=geocode:,lang:,locale:,t=result_type:,until:,since_id:,max_id:,include_entities:,sanitize", SerializeOpts.getOptionDefs()); opts.parse(args);//from ww w . ja va2s. co m mSerializeOpts = this.getSerializeOpts(opts); final boolean bSanitize = opts.hasOpt("sanitize"); args = opts.getRemainingArgs(); try { Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query(); if (opts.hasOpt("query")) query.setQuery(opts.getOptStringRequired("query")); if (opts.hasOpt("lang")) query.setLang(opts.getOptStringRequired("lang")); if (opts.hasOpt("locale")) query.setLocale(opts.getOptStringRequired("locale")); if (opts.hasOpt("result_type")) query.setResultType(opts.getOptStringRequired("result_type")); if (opts.hasOpt("until")) query.setUntil(opts.getOptStringRequired("until")); if (opts.hasOpt("since_id")) query.setSinceId(opts.getOptValue("since_id").toLong()); if (opts.hasOpt("since")) query.setUntil(opts.getOptStringRequired("since")); if (opts.hasOpt("max_id")) query.setSinceId(opts.getOptValue("max_id").toLong()); QueryResult result = twitter.search(query); List<Status> tweets = result.getTweets(); OutputPort out = this.getStdout(); mWriter = new TwitterWriter(out.asXMLStreamWriter(mSerializeOpts), bSanitize); mWriter.startDocument(); mWriter.startElement("twitter"); mWriter.writeDefaultNamespace(); for (Status t : tweets) mWriter.write(t); mWriter.endElement(); mWriter.endDocument(); mWriter.closeWriter(); out.release(); } finally { } return 0; }
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 {//from www . j av a2s . c om 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; } }