List of usage examples for twitter4j Twitter search
QueryResult search(Query query) throws TwitterException;
From source file:org.apache.aries.sample.twitter.TwitterQuery.java
License:Apache License
public void start(BundleContext context) throws Exception { Twitter twitter = new Twitter(); Query query = new Query("from:theasf"); try {/* www . j ava 2 s . c om*/ QueryResult result = twitter.search(query); List<Tweet> tweets = result.getTweets(); System.out.println("hits:" + tweets.size()); for (Tweet tweet : tweets) { System.out.println(tweet.getFromUser() + ":" + StringEscapeUtils.unescapeXml(tweet.getText())); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.blur.demo.twitter.Whiteboard.java
License:Apache License
/** * @param args//from w ww.ja v a2 s . com * @throws TwitterException */ public static void main(String[] args) throws TwitterException { Twitter twitter = new TwitterFactory(new ConfigurationBuilder().build()).getInstance(); OAuth2Token token = twitter.getOAuth2Token(); System.out.println(token.getTokenType()); try { Query query = new Query("Apache"); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }
From source file:org.apache.camel.component.twitter.consumer.search.SearchConsumer.java
License:Apache License
private List<Status> search(Query query) throws TwitterException { Integer numberOfPages = 1;//w ww.j ava 2s.c o m if (ObjectHelper.isNotEmpty(te.getProperties().getLang())) { query.setLang(te.getProperties().getLang()); } if (ObjectHelper.isNotEmpty(te.getProperties().getCount())) { query.setCount(te.getProperties().getCount()); } if (ObjectHelper.isNotEmpty(te.getProperties().getNumberOfPages())) { numberOfPages = te.getProperties().getNumberOfPages(); } LOG.debug("Searching with " + numberOfPages + " pages."); Twitter twitter = te.getProperties().getTwitter(); QueryResult qr = twitter.search(query); List<Status> tweets = qr.getTweets(); for (int i = 1; i < numberOfPages; i++) { if (!qr.hasNext()) { break; } qr = twitter.search(qr.nextQuery()); tweets.addAll(qr.getTweets()); } if (te.getProperties().isFilterOld()) { for (Status t : tweets) { checkLastId(t.getId()); } } return tweets; }
From source file:org.apache.camel.component.twitter.producer.SearchProducer.java
License:Apache License
@Override public void process(Exchange exchange) throws Exception { long myLastId = lastId; // KEYWORDS// w ww . j a v a 2 s .co m // keywords from header take precedence String keywords = exchange.getIn().getHeader(TwitterConstants.TWITTER_KEYWORDS, String.class); if (keywords == null) { keywords = te.getProperties().getKeywords(); } if (keywords == null) { throw new CamelExchangeException("No keywords to use for query", exchange); } Query query = new Query(keywords); // filter of older tweets if (te.getProperties().isFilterOld() && myLastId != 0) { query.setSinceId(myLastId); } // language String lang = exchange.getIn().getHeader(TwitterConstants.TWITTER_SEARCH_LANGUAGE, String.class); if (lang == null) { lang = te.getProperties().getLang(); } if (ObjectHelper.isNotEmpty(lang)) { query.setLang(lang); } // number of elemnt per page Integer count = exchange.getIn().getHeader(TwitterConstants.TWITTER_COUNT, Integer.class); if (count == null) { count = te.getProperties().getCount(); } if (ObjectHelper.isNotEmpty(count)) { query.setCount(count); } // number of pages Integer numberOfPages = exchange.getIn().getHeader(TwitterConstants.TWITTER_NUMBER_OF_PAGES, Integer.class); if (numberOfPages == null) { numberOfPages = te.getProperties().getNumberOfPages(); } Twitter twitter = te.getProperties().getTwitter(); log.debug("Searching twitter with keywords: {}", keywords); QueryResult results = twitter.search(query); List<Status> list = results.getTweets(); for (int i = 1; i < numberOfPages; i++) { if (!results.hasNext()) { break; } log.debug("Fetching page"); results = twitter.search(results.nextQuery()); list.addAll(results.getTweets()); } if (te.getProperties().isFilterOld()) { for (Status t : list) { long newId = t.getId(); if (newId > myLastId) { myLastId = newId; } } } exchange.getIn().setBody(list); // update the lastId after finished the processing if (myLastId > lastId) { lastId = myLastId; } }
From source file:org.codice.ddf.catalog.twitter.source.TwitterSource.java
License:Open Source License
@Override public SourceResponse query(QueryRequest request) throws UnsupportedQueryException { Twitter instance = twitterFactory.getInstance(); try {//from ww w . j a v a 2 s .c o m instance.getOAuth2Token(); } catch (TwitterException e) { throw new UnsupportedQueryException("Unable to get OAuth2 token.", e); } TwitterFilterVisitor visitor = new TwitterFilterVisitor(); request.getQuery().accept(visitor, null); Query query = new Query(); query.setCount(request.getQuery().getPageSize()); if (visitor.hasSpatial()) { GeoLocation geoLocation = new GeoLocation(visitor.getLatitude(), visitor.getLongitude()); query.setGeoCode(geoLocation, visitor.getRadius(), Query.Unit.km); } if (visitor.getContextualSearch() != null) { query.setQuery(visitor.getContextualSearch().getSearchPhrase()); } if (visitor.getTemporalSearch() != null) { Calendar.Builder builder = new Calendar.Builder(); builder.setInstant(visitor.getTemporalSearch().getStartDate()); Calendar calendar = builder.build(); query.setSince(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH)); builder = new Calendar.Builder(); builder.setInstant(visitor.getTemporalSearch().getEndDate()); calendar = builder.build(); query.setUntil(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH)); } QueryResult queryResult; try { queryResult = instance.search().search(query); } catch (TwitterException e) { throw new UnsupportedQueryException(e); } List<Result> resultList = new ArrayList<>(queryResult.getCount()); resultList.addAll(queryResult.getTweets().stream().map(status -> new ResultImpl(getMetacard(status))) .collect(Collectors.toList())); return new SourceResponseImpl(request, resultList); }
From source file:org.getlantern.firetweet.loader.support.TweetSearchLoader.java
License:Open Source License
@NonNull @Override//w ww . j a va 2s.c o m public List<Status> getStatuses(@NonNull final Twitter twitter, final Paging paging) throws TwitterException { final Query query = new Query(processQuery(mQuery)); query.setRpp(paging.getCount()); if (paging.getMaxId() > 0) { query.setMaxId(paging.getMaxId()); } return twitter.search(query); }
From source file:org.glassfish.jersey.sample.sse.TwitterBean.java
License:Open Source License
/** * Since twitter uses the v1.1 API we use twitter4j to get * the search results using OAuth/*from ww w. ja v a 2 s. c o m*/ * @return a JsonArray containing tweets * @throws TwitterException * @throws IOException */ public JsonArray getFeedData() throws TwitterException, IOException { Properties prop = new Properties(); // try { //load a properties file prop.load(this.getClass().getResourceAsStream("twitter4j.properties")); //get the property value and print it out String consumerKey = prop.getProperty("oauth.consumerKey"); String consumerSecret = prop.getProperty("oauth.consumerSecret"); String accessToken = prop.getProperty("oauth.accessToken"); String accessTokenSecret = prop.getProperty("oauth.accessTokenSecret"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Query query = new Query("glassfish"); QueryResult result = twitter.search(query); JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); for (Status status : result.getTweets()) { jsonArrayBuilder.add(Json.createObjectBuilder().add("text", status.getText()).add("created_at", status.getCreatedAt().toString())); System.out.println( "@" + status.getUser().getScreenName() + ":" + status.getText() + status.getCreatedAt()); } return jsonArrayBuilder.build(); }
From source file:org.kawalpemilukada.web.controller.SentimentAnalysis.java
private void cariText(JSONArray returnVals, Twitter twitter, String topic) throws ParseException { try {//from w ww . j a v a 2 s .c om Query query = new Query(topic); query.setCount(100); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { JSONObject returnVal = new JSONObject(); returnVal.put("Text", tweet.getText()); //returnVal.put("HashtagEntities", tweet.getHashtagEntities().toString()); //returnVal.put("UserMentionEntities", tweet.getUserMentionEntities().toString()); returnVal.put("FavoriteCount", tweet.getFavoriteCount()); returnVal.put("RetweetCount", tweet.getRetweetCount()); returnVal.put("UserImg", tweet.getUser().getBiggerProfileImageURLHttps().toString()); returnVal.put("UserLink", "https://twitter.com/" + CommonServices.getVal(tweet.getUser().getScreenName())); returnVal.put("CreatedAt", JakartaTime(tweet.getCreatedAt()).toString()); returnVals.add(returnVal); } } while ((query = result.nextQuery()) != null); } catch (TwitterException te) { te.printStackTrace(); } }
From source file:org.kuali.mobility.conference.controllers.ConferenceController.java
License:Open Source License
@RequestMapping(value = "twitter-search", method = RequestMethod.GET) public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam, @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam); QueryResult result = null;/*from w ww. j av a2 s. c o m*/ query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01"); query.setCount(100); query.setResultType(Query.MIXED); String json = ""; List<String> tweetList = new ArrayList<String>(); try { result = twitter.search(query); } catch (TwitterException e) { System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage()); } String tweetInfo = ""; for (Status status : result.getTweets()) { tweetInfo = "{"; tweetInfo += "\"id\" : \"" + status.getId() + "\", "; tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", "; tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", "; tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", "; tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", "; tweetInfo += "\"status\" : \"" + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", "; tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\","; tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\""; tweetInfo += "}"; tweetList.add(tweetInfo); } json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]"; return new ResponseEntity<String>(json, HttpStatus.OK); }
From source file:org.luwrain.app.twitter.Base.java
License:Open Source License
static private TweetWrapper[] search(Twitter twitter, String text, int numPages) { NullCheck.notNull(twitter, "twitter"); NullCheck.notEmpty(text, "text"); if (numPages < 1) throw new IllegalArgumentException("numPages must be greater than zero"); final LinkedList<TweetWrapper> wrappers = new LinkedList<TweetWrapper>(); try {/*from w ww.j a v a 2 s.com*/ Query query = new Query(text); QueryResult result; int pageNum = 1; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); System.out.println("" + tweets.size()); for (Status tweet : tweets) wrappers.add(new TweetWrapper(tweet)); if (pageNum >= numPages) return wrappers.toArray(new TweetWrapper[wrappers.size()]); ++pageNum; } while ((query = result.nextQuery()) != null); } catch (TwitterException e) { e.printStackTrace(); return null; } return wrappers.toArray(new TweetWrapper[wrappers.size()]); }