List of usage examples for twitter4j Query Query
public Query(String query)
From source file:nl.b3p.viewer.stripes.TwitterActionBean.java
License:Open Source License
public Resolution create() throws JSONException { JSONObject json = new JSONObject(); json.put("success", Boolean.FALSE); String error = null;/*from w ww . j av a 2 s .c o m*/ try { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query(term); if (latestId != null) { Long longVal = Long.valueOf(latestId); query.setSinceId(longVal); } QueryResult result = twitter.search(query); JSONArray tweets = new JSONArray(); for (Status tweet : result.getTweets()) { //System.out.println(tweet.getFromUser() + ":" + tweet.getText()); JSONObject t = new JSONObject(); t.put("id_str", String.valueOf(tweet.getId())); t.put("text", tweet.getText()); t.put("user_from", tweet.getUser().getScreenName()); t.put("img_url", tweet.getUser().getProfileImageURL()); JSONObject geo = new JSONObject(); if (tweet.getGeoLocation() != null) { geo.put("lat", tweet.getGeoLocation().getLatitude()); geo.put("lon", tweet.getGeoLocation().getLongitude()); } t.put("geo", geo); tweets.put(t); } json.put("tweets", tweets); if (tweets.length() > 0) { json.put("maxId", String.valueOf(result.getMaxId())); } else { json.put("maxId", String.valueOf(latestId)); } json.put("success", Boolean.TRUE); } catch (Exception e) { error = e.toString(); if (e.getCause() != null) { error += "; cause: " + e.getCause().toString(); } } if (error != null) { json.put("error", error); } return new StreamingResolution("application/json", new StringReader(json.toString())); }
From source file:nl.isaac.dotcms.twitter.util.TwitterUtil.java
License:Creative Commons License
public List<CustomStatus> search(String from) { try {//w w w.j av a 2s. com Query query = new Query(from); QueryResult result; result = twitter.search(query); List<CustomStatus> tweets = formatStatus(result.getTweets()); return tweets; } catch (TwitterException te) { throw new RuntimeException(te.toString(), te); } }
From source file:nz.co.lolnet.james137137.lolnettwitchaddonbc.TwitterAPI.java
public List<Status> getLatestStatus() { List<Status> twitchTweets = new ArrayList<>(); try {/* w ww . j av a2 s. c om*/ Query query = new Query("lolnetNZ twitch.tv"); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { if (tweet.getUser().getId() == 495479479 && tweet.getSource().contains("http://www.twitch.tv")) { twitchTweets.add(tweet); } } } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); } return twitchTweets; }
From source file:ontoSentiment.Busca.java
public void buscarPorAssunto(String busca, String lang) throws TwitterException { int totalTweets = 0; long maxID = -1; Query q = new Query(busca + " -filter:retweets -filter:links -filter:replies -filter:images"); q.setCount(Util.TWEETS_PER_QUERY); // How many tweets, max, to retrieve q.resultType(Query.ResultType.recent); // Get all tweets q.setLang(lang);//from w w w . j a v a2 s. c om QueryResult r = Util.getTwitter().search(q); do { for (Status s : r.getTweets()) { totalTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } //System.out.printf("O tweet de id %s disse as %s, @%-20s disse: %s\n", new Long(s.getId()).toString(), s.getCreatedAt().toString(), s.getUser().getScreenName(), Util.cleanText(s.getText())); System.out.println(Util.cleanText(s.getText())); } q = r.nextQuery(); if (q != null) { q.setMaxId(maxID); r = Util.getTwitter().search(q); System.out.println("Total tweets: " + totalTweets); System.out.println("Maximo ID: " + maxID); Util.imprimirRateLimit(Util.RATE_LIMIT_OPTION_SEARCH_TWEETS); } } while (q != null); }
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** * Entry point for a Lappsgrid service./*from www .ja va 2 s . c o m*/ * <p> * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container} * payload. * <p> * Errors and exceptions that occur during processing should be wrapped in a {@code Data} * object with the discriminator set to http://vocab.lappsgrid.org/ns/error * <p> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br /> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br /> * * @param input A JSON string representing a Data object * @return A JSON string containing a Data object with a Container payload. */ @Override public String execute(String input) { Data<String> data = Serializer.parse(input, Data.class); String discriminator = data.getDiscriminator(); // Return ERRORS back if (Discriminators.Uri.ERROR.equals(discriminator)) { return input; } // Generate an error if the used discriminator is wrong if (!Discriminators.Uri.GET.equals(discriminator)) { return generateError( "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator); } Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false) .build(); // Authentication using saved keys Twitter twitter = new TwitterFactory(config).getInstance(); String key = readProperty(KEY_PROPERTY); if (key == null) { return generateError("The Twitter Consumer Key property has not been set."); } String secret = readProperty(SECRET_PROPERTY); if (secret == null) { return generateError("The Twitter Consumer Secret property has not been set."); } twitter.setOAuthConsumer(key, secret); try { twitter.getOAuth2Token(); } catch (TwitterException te) { String errorData = generateError(te.getMessage()); logger.error(errorData); return errorData; } // Get query String from data payload Query query = new Query(data.getPayload()); // Set the type to Popular or Recent if specified // Results will be Mixed by default. if (data.getParameter("type") == "Popular") query.setResultType(Query.POPULAR); if (data.getParameter("type") == "Recent") query.setResultType(Query.RECENT); // Get lang string String langCode = (String) data.getParameter("lang"); // Verify the validity of the language code and add it to the query if it's valid if (validateLangCode(langCode)) query.setLang(langCode); // Get date strings String sinceString = (String) data.getParameter("since"); String untilString = (String) data.getParameter("until"); // Verify the format of the date strings and set the parameters to query if correctly given if (validateDateFormat(untilString)) query.setUntil(untilString); if (validateDateFormat(sinceString)) query.setSince(sinceString); // Get GeoLocation if (data.getParameter("address") != null) { String address = (String) data.getParameter("address"); double radius = (double) data.getParameter("radius"); if (radius <= 0) radius = 10; Query.Unit unit = Query.MILES; if (data.getParameter("unit") == "km") unit = Query.KILOMETERS; GeoLocation geoLocation; try { double[] coordinates = getGeocode(address); geoLocation = new GeoLocation(coordinates[0], coordinates[1]); } catch (Exception e) { String errorData = generateError(e.getMessage()); logger.error(errorData); return errorData; } query.geoCode(geoLocation, radius, String.valueOf(unit)); } // Get the number of tweets from count parameter, and set it to default = 15 if not specified int numberOfTweets; try { numberOfTweets = (int) data.getParameter("count"); } catch (NullPointerException e) { numberOfTweets = 15; } // Generate an ArrayList of the wanted number of tweets, and handle possible errors. // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed ArrayList<Status> allTweets; Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter); String tweetsDataDisc = tweetsData.getDiscriminator(); if (Discriminators.Uri.ERROR.equals(tweetsDataDisc)) return tweetsData.asPrettyJson(); else { allTweets = (ArrayList<Status>) tweetsData.getPayload(); } // Initialize StringBuilder to hold the final string StringBuilder builder = new StringBuilder(); // Append each Status (each tweet) to the initialized builder for (Status status : allTweets) { String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : " + status.getText() + "\n"; builder.append(single); } // Output results Container container = new Container(); container.setText(builder.toString()); Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container); return output.asPrettyJson(); }
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 {//from ww w . j ava 2 s . c o m 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.asterix.external.input.record.reader.twitter.TwitterPullRecordReader.java
License:Apache License
public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new GenericRecord<Status>(); }
From source file:org.apache.blur.demo.twitter.TwitterSearchQueueReader.java
License:Apache License
private void initResult(int count) throws TwitterException, InterruptedException { log.info("Initializing result for query[" + searchCriteria + "] with count[" + count + "]"); query = new Query(searchCriteria); query.setCount(count);//from w w w .ja v a 2 s. co m result = twitter.search(query); }
From source file:org.apache.blur.demo.twitter.Whiteboard.java
License:Apache License
/** * @param args/*from www .j a 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
public List<Status> pollConsume() throws TwitterException { String keywords = te.getProperties().getKeywords(); Query query = new Query(keywords); if (te.getProperties().isFilterOld()) { query.setSinceId(lastId);//from w w w. j a v a2 s . co m } LOG.debug("Searching twitter with keywords: {}", keywords); return search(query); }