List of usage examples for twitter4j Query setCount
public void setCount(int count)
From source file:Jums.AllAPI.java
public int TweetCount(String word) { int i = 0;/*from w w w . jav a 2 s . co m*/ try { Query query = new Query(word); query.setCount(100); Date date = this.SetDate(); query.setSince(this.SetSDF()); QueryResult result = this.tw.search(query); for (Status status : result.getTweets()) { if (date.compareTo(status.getCreatedAt()) < 0) { i++; } } } catch (TwitterException te) { System.out.println(te.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } return i; }
From source file:keypoh.TwitterCrawler.java
/** * Function getTimeline/*w w w . ja v a2s .co m*/ * @param key * @return List * @throws Exception */ private List getTimeline(String key) throws Exception { List<String> ans = new LinkedList(); Query query = new Query(key); query.setCount(limit); QueryResult res = tw.search(query); List<Status> tweets = res.getTweets(); for (Status tweet : tweets) { if (tweet.getText() != null) { ans.add(tweet.getText()); } } return ans; }
From source file:mashup.MashTweetManager.java
public static ArrayList<String> getTweets(String topic) throws IOException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthAccessToken(Common.AccessToken) .setOAuthAccessTokenSecret(Common.AccessTokenSecret).setOAuthConsumerKey(Common.ConsumerKey) .setOAuthConsumerSecret(Common.ConsumerSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance();/*from ww w . j ava2s .c om*/ //Twitter twitter = new TwitterFactory().getInstance(); // twitter.setOAuthAccessToken(null); ArrayList<String> tweetList = new ArrayList<>(); try { Query query = new Query(topic.toLowerCase().trim()); query.setCount(100); query.setLocale("en"); query.setLang("en"); QueryResult result = null; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { String data = tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", ""); HinghlishStopWords.removeStopWords(data.trim()); // Remove Special... Characters // Remove stop words tweetList.add(tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", "")); } } while ((query = result.nextQuery()) != null); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); } return tweetList; }
From source file:moderation.Moderate.java
public List getTwitterpost() { List posts = new ArrayList(); try {/* w w w .j a va2s . co m*/ List savedpost = getSavedList(album_id); String tagname = this.hash; Twitter twitter = setting.TwitterToken.twitterObject(); Query query = new Query(tagname); query.setCount(50); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("\n\n\n" + tweet); PostModel post = new PostModel(); post.setAlbum_id(this.album_id); if (savedpost.contains(tweet.getId())) post.setStatus("old"); else post.setStatus("new"); post.setPost_id("" + tweet.getId()); post.setSender_name(URLEncoder.encode(tweet.getUser().getScreenName(), "UTF-8")); post.setCaption_text(URLEncoder.encode(tweet.getText(), "UTF-8")); post.setSender_pic(tweet.getUser().getProfileImageURL()); post.setSender_id("" + tweet.getUser().getId()); for (MediaEntity mediaEntity : tweet.getMediaEntities()) { post.setImage_standard(mediaEntity.getMediaURL()); post.setImage_low(mediaEntity.getMediaURL()); } post.setPost_time(tweet.getCreatedAt().toString()); post.setType("twitter_post"); post.setLink(null); post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id() + "&type=" + post.getType() + "&post_time=" + post.getPost_time() + "&link=" + post.getLink() + "&pic_low=" + post.getImage_low() + "&pic_standard=" + post.getImage_standard() + "&post_message=" + post.getCaption_text() + "&sender_name=" + post.getSender_name() + "&sender_id=" + post.getSender_id() + "&sender_pic=" + post.getSender_pic()); posts.add(post); } this.twitternext = result.nextQuery(); } catch (Exception e) { System.err.println("Exception occure in getTwitter " + e); } return posts; }
From source file:net.lacolaco.smileessence.twitter.task.SearchTask.java
License:Open Source License
public static Query getBaseQuery(MainActivity activity, String queryString) { Configuration config = activity.getResources().getConfiguration(); Query query = new Query(); query.setQuery(queryString);//from w ww . ja v a 2s . c o m query.setLang(config.locale.getLanguage()); query.setCount(TwitterUtils.getPagingCount(activity)); query.setResultType(Query.RECENT); return query; }
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 ww w.ja va 2 s .co m 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
/** Contacts the Twitter API and gets any number of tweets corresponding to a certain query. The main * purpose of this function is to avoid the limit of 100 tweets that can be extracted at once. * * @param numberOfTweets the number of tweets to be printed * @param query the query to be searched by the twitter client * @param twitter the twitter client// w w w .ja v a2 s .c o m * * @return A JSON string containing a Data object with either a list containing the tweets as a payload * (when successful) or a String payload (for errors). */ private Data getTweetsByCount(int numberOfTweets, Query query, Twitter twitter) { ArrayList<Status> tweets = new ArrayList<>(); if (!(numberOfTweets > 0)) { // Default of 15 tweets numberOfTweets = 15; } // Set the last ID to the maximum possible value as a default long lastID = Long.MAX_VALUE; int original; try { while (tweets.size() < numberOfTweets) { // Keep number of original to avoid infinite looping when not getting enough tweets original = tweets.size(); // If there are more than 100 tweets left to be extracted, extract // 100 during the next query, since 100 is the limit to retrieve at once if (numberOfTweets - tweets.size() > 100) query.setCount(100); else query.setCount(numberOfTweets - tweets.size()); // Extract tweets corresponding to the query then add them to the list QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); // Iterate through the list and get the lastID to know where to start from // if there are more tweets to be extracted for (Status status : tweets) if (status.getId() < lastID) lastID = status.getId(); query.setMaxId(lastID - 1); // Break the loop if the tweet count didn't change. This would prevent an infinite loop when // tweets for the specified query are not available if (tweets.size() == original) break; } } catch (TwitterException te) { // Put the list of tweets in Data format then output as JSon String. // Since we checked earlier for errors, we assume that an error occuring at this point due // to Rate Limits is caused by a too high request. Thus, we output the retrieved tweets and log // the error String errorDataJson = generateError(te.getMessage()); logger.error(errorDataJson); if (te.exceededRateLimitation() && tweets.size() > 0) { Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } else { return Serializer.parse(errorDataJson, Data.class); } } // Return a special error message if no tweets are found if (tweets.size() == 0) { String noTweetsMessage = "No tweets found for the following query. " + "Note: Twitter's REST API only retrieves tweets from the past week."; String errorDataJson = generateError(noTweetsMessage); return Serializer.parse(errorDataJson, Data.class); } else { // Put the list of tweets in Data format then output as JSon String. Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } }
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;//from ww w.j av a 2s.co 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//from w ww .j av a2 s . c o 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.bireme.interop.toJson.TweetLoader.java
License:Open Source License
public TweetLoader(final Twitter twitter, final String userId, final Query query, final int total, final Date lowerDate, final boolean useRetweets) { if (twitter == null) { throw new NullPointerException("twitter"); }/*from w ww . j a v a2 s . c om*/ if ((userId == null) && (query == null)) { throw new NullPointerException("userId AND query"); } if ((total <= 0) && (lowerDate == null)) { throw new IllegalArgumentException("total AND lowerDate"); } this.twitter = twitter; this.userId = userId; this.query = query; this.total = total; this.lowerDate = lowerDate; this.useRetweets = useRetweets; tweetIterator = null; retweetIterator = null; pageNum = 0; curTweet = 0; max_id = Long.MAX_VALUE; if (query != null) { query.setCount(MAX_PAGE_SIZE); } }