List of usage examples for twitter4j FilterQuery FilterQuery
public FilterQuery()
From source file:com.isdp.twitterposter.TwitterManager.java
License:Open Source License
public void startTwitterStream() { TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance(); StatusListener listener = new StatusListener() { @Override/*from w ww . ja v a 2 s . c om*/ public void onStatus(Status status) { try { System.out.println("Text recieved: @" + status.getUser().getScreenName() + " - " + status.getText() + "\n"); StringTokenizer st = new StringTokenizer(status.getText(), " "); //first token indicates search engine String searchEngine = st.nextToken(); //burn the next random token String randToken = st.nextToken(); //next token indicates max number of results to return int maxResults = Integer.parseInt(st.nextToken()); String searchString = ""; while (st.hasMoreTokens()) { searchString += st.nextToken() + " "; } if (searchEngine.equals(GoogleManager.TAG_YELP)) { String[] results = GoogleManager.getInstance().trySearch(searchString, GoogleManager.SEARCH_YELP); if (results != null) { for (int i = 0; i < results.length && i < maxResults; ++i) { String tweetMsg = Util.truncateString(results[i], TWITTER_CHARACTER_LIMIT); System.out.println("Tweeting" + tweetMsg); tweet(tweetMsg); } } else if (results == null || results.length == 0) { tweet(Util.generateRandomString(7) + "\n" + "No results found!"); } } else if (searchEngine.equals(GoogleManager.TAG_WIKI)) { String[] results = GoogleManager.getInstance().trySearch(searchString, GoogleManager.SEARCH_WIKI); if (results != null) { for (int i = 0; i < results.length && i < maxResults; ++i) { String tweetMsg = Util.generateRandomString(3) + "\n" + Util.shortenText(results[i]); tweetMsg = Util.truncateString(tweetMsg, TWITTER_CHARACTER_LIMIT); System.out.println("Tweeting " + tweetMsg); tweet(tweetMsg); } } else if (results == null || results.length == 0) { tweet(Util.generateRandomString(7) + "\n" + "No results found!"); } } } catch (Exception e) { } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { System.out.println( "onDeletionNotice: Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out .println("onTrackLimitationNotice: Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println( "onScrubGeo: Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("onStallWarning: Got stall warning:" + warning); } @Override public void onException(Exception ex) { System.out.println("onException" + ex.toString()); } }; twitterStream.addListener(listener); FilterQuery tweetFilterQuery = new FilterQuery(); tweetFilterQuery.follow(new long[] { FOLLOW_ID }); twitterStream.filter(tweetFilterQuery); }
From source file:com.isdp.twitterposterandroid.TwitterManager.java
License:Open Source License
public void startTwitterStream() { TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance(); StatusListener listener = new StatusListener() { @Override/*from w w w.ja v a 2 s . co m*/ public void onStatus(Status status) { try { Log.d("Text recieved", "@" + status.getUser().getScreenName() + " - " + status.getText() + "\n"); StringTokenizer st = new StringTokenizer(status.getText(), " "); //first token indicates search engine String searchEngine = st.nextToken(); //burn the next random token String randToken = st.nextToken(); //next token indicates max number of results to return int maxResults = Integer.parseInt(st.nextToken()); String searchString = ""; while (st.hasMoreTokens()) { searchString += st.nextToken() + " "; } if (searchEngine.equals(GoogleManager.TAG_YELP)) { String[] results = GoogleManager.getInstance().trySearch(searchString, GoogleManager.SEARCH_YELP); if (results != null) { for (int i = 0; i < results.length && i < maxResults; ++i) { String tweetMsg = Util.truncateString(results[i], TWITTER_CHARACTER_LIMIT); Log.d("Tweeting", tweetMsg); tweet(tweetMsg); } } else if (results == null || results.length == 0) { tweet(Util.generateRandomString(7) + "\n" + "No results found!"); } } else if (searchEngine.equals(GoogleManager.TAG_WIKI)) { String[] results = GoogleManager.getInstance().trySearch(searchString, GoogleManager.SEARCH_WIKI); if (results != null) { for (int i = 0; i < results.length && i < maxResults; ++i) { String tweetMsg = Util.generateRandomString(3) + "\n" + Util.shortenText(results[i]); tweetMsg = Util.truncateString(tweetMsg, TWITTER_CHARACTER_LIMIT); Log.d("Tweeting", tweetMsg); tweet(tweetMsg); } } else if (results == null || results.length == 0) { tweet(Util.generateRandomString(7) + "\n" + "No results found!"); } } } catch (Exception e) { } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { Log.d("onDeletionNotice", "Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { Log.d("onTrackLimitationNotice", "Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { Log.d("onScrubGeo", "Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { Log.d("onStallWarning", "Got stall warning:" + warning); } @Override public void onException(Exception ex) { Log.d("onException", ex.toString()); } }; twitterStream.addListener(listener); FilterQuery tweetFilterQuery = new FilterQuery(); tweetFilterQuery.follow(new long[] { FOLLOW_ID }); twitterStream.filter(tweetFilterQuery); }
From source file:com.left8.evs.utilities.dsretriever.TweetsRetriever.java
License:Open Source License
/** * Method that handles the Twitter streaming API. <br> * <b>WARNING:</b> Method does not terminate by itself, due to the fact that * the streamer runs in a different thread. * @param keywords The keywords for which the streamer searches for tweets. * @param mongoDB A handler for the MongoDB database. * @param config A configuration object. *//*www . j a v a 2s .c o m*/ public final void retrieveTweetsWithStreamingAPI(String[] keywords, MongoHandler mongoDB, Config config) { ConfigurationBuilder cb = getAuthorization(); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); final StatusListener listener; listener = new StatusListener() { @Override public final void onStatus(Status status) { //Insert tweet to MongoDB mongoDB.insertSingleTweetIntoMongoDB(status, "NULL"); } @Override public final void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { Utilities.printMessageln("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public final void onTrackLimitationNotice(int numberOfLimitedStatuses) { Utilities.printMessageln("Got track limitation notice:" + numberOfLimitedStatuses); } @Override public final void onScrubGeo(long userId, long upToStatusId) { Utilities.printMessageln("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public final void onStallWarning(StallWarning warning) { Utilities.printMessageln("Got stall warning:" + warning); } @Override public final void onException(Exception ex) { ex.printStackTrace(System.out); } }; FilterQuery fq = new FilterQuery(); fq.language("en"); //Set language of tweets to "English" fq.track(keywords); //Load the search terms twitterStream.addListener(listener); //Start listening to the stream twitterStream.filter(fq); //Apply the search filters }
From source file:com.microsoft.example.TwitterSampleSpout.java
License:Apache License
@Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;//from w w w . j ava 2 s .c o m StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(status); } @Override public void onDeletionNotice(StatusDeletionNotice sdn) { } @Override public void onTrackLimitationNotice(int i) { } @Override public void onScrubGeo(long l, long l1) { } @Override public void onException(Exception ex) { } @Override public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; TwitterStream twitterStream = new TwitterStreamFactory( new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance(); twitterStream.addListener(listener); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); twitterStream.setOAuthAccessToken(token); if (keyWords.length == 0) { twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); twitterStream.filter(query); } }
From source file:com.mycompany.omnomtweets.Search.java
public static void main(String[] args) throws TwitterException { System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.NullLoggerFactory"); if (args.length >= 1) { candidate = Candidate.valueOf(args[0]); System.out.println("Getting tweets on " + candidate.name); } else {/* w w w . j a va 2s.co m*/ //System.out.println("You didn't give me a candidate, so you get TRUMP"); } //System.out.println("Starting at: " + sdf.format(new Date())); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(candidate.consumerKey) .setOAuthConsumerSecret(candidate.consumerSecret).setOAuthAccessToken(candidate.accessToken) .setOAuthAccessTokenSecret(candidate.accessTokenSecret); final ArrayList<Status> statuses = new ArrayList<>(); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { public void onStatus(Status status) { statuses.add(status); writeToStdErr(status); //Removed because writing to STD OUT instead. //System.out.println("statuses: " + statuses.size()); if (statuses.size() >= 100) { /*System.out.println("Writing " + statuses.size() + " to file " + "at: " + sdf.format(new Date()));*/ writeTweetsToFile(statuses, candidate.name + "StreamTweets.txt"); statuses.clear(); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { //System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } public void onScrubGeo(long userId, long upToStatusId) { //System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } public void onException(Exception ex) { //ex.printStackTrace(); } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); String keywords[] = candidate.aliases; fq.track(keywords); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:com.producer.TwitterProducer.java
License:Apache License
public static void main(String[] args) { if (args.length == 0) { System.out.println(/*from w w w . j a va 2s . com*/ "SimpleCounter {broker-list} {topic} {type old/new} {type sync/async} {delay (ms)} {count}"); return; } /* get arguments */ String brokerList = args[0]; String topic = args[1]; String age = args[2]; String sync = args[3]; /* * In order to create the spout, you need to get twitter credentials * If you need to use Twitter firehose/Tweet stream for your idea, * create a set of credentials by following the instructions at * * https://dev.twitter.com/discussions/631 * */ String custkey = "WXDgVgeJMwHEn0Z9VHDx5j93h"; String custsecret = "DgP9CsaPtG87urpNU14fZySXOjNX4j4v2PqmeTndcjjYBgLldy"; String accesstoken = "3243813491-ixCQ3HWWeMsthKQvj5MiBvNw3dSNAuAd3IfoDUw"; String accesssecret = "aHOXUB4nbhZv2vbAeV15ZyTAD0lPPCptCr32N0PX7OaMe"; producer = new DemoProducerOld(topic); /* start a producer */ producer.configure(brokerList, sync); producer.start(); //long startTime = System.currentTimeMillis(); System.out.println("Starting..."); producer.produce("Starting..."); ConfigurationBuilder config = new ConfigurationBuilder().setOAuthConsumerKey(custkey) .setOAuthConsumerSecret(custsecret).setOAuthAccessToken(accesstoken) .setOAuthAccessTokenSecret(accesssecret); // create the twitter stream factory with the config TwitterStream twitterStream; TwitterStreamFactory fact = new TwitterStreamFactory(config.build()); // get an instance of twitter stream twitterStream = fact.getInstance(); // message to kafka Map<String, String> headers = new HashMap<String, String>(); //filter non-english tweets FilterQuery tweetFilterQuery = new FilterQuery(); tweetFilterQuery.language(new String[] { "en" }); // tweetFilterQuery.locations(new double[][] { { -180, -90 }, { 180, 90 } }); // provide the handler for twitter stream twitterStream.addListener(new TweetListener()); twitterStream.filter(tweetFilterQuery); // start the sampling of tweets twitterStream.sample(); // TODO ADD timestamp //long endTime = System.currentTimeMillis(); //System.out.println("... and we are done. This took " + (endTime - startTime) + " ms."); //producer.produce("... and we are done. This took " + (endTime - startTime) + " ms."); /* close shop and leave */ //producer.close(); //System.exit(0); }
From source file:com.project.shlok.TopicsAnalyzer.TwitterReader.java
/** * getTweets//from w w w. j a v a 2 s.co m * Reads tweets based on a specific query * @param String - query to be tracked * @return None * */ public void getTweets(String query) { FilterQuery fq = new FilterQuery(); fq.track(query); twitterStreamListener.setQuery(query); twitterStream.addListener(twitterStreamListener); twitterStream.filter(fq); }
From source file:com.richardstansbury.tweetfollow.TwitterHelper.java
License:Open Source License
/** * Starts a filter query of the Twitter Streaming API. * * @param keywords array of string keywords *//*from w ww. ja va2s .com*/ public void start(String[] keywords) { _twitter.filter((new FilterQuery()).track(keywords)); }
From source file:com.saugereau.spout.TwitterSpout.java
License:Apache License
@Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;// w w w . j a v a 2s . co m StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(status); } @Override public void onDeletionNotice(StatusDeletionNotice sdn) { } @Override public void onTrackLimitationNotice(int i) { LOG.info("Got track limitation notice:" + i); } @Override public void onScrubGeo(long l, long l1) { } @Override public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; _twitterStream = new TwitterStreamFactory(new ConfigurationBuilder().setJSONStoreEnabled(true).build()) .getInstance(); _twitterStream.addListener(listener); _twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); _twitterStream.setOAuthAccessToken(token); if (keyWords.length == 0) { _twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); query.language(new String[] { "en" }); _twitterStream.filter(query); } }
From source file:com.sinfonier.spouts.Twitter.java
License:Apache License
@Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { xml = new XMLProperties(spoutName, ComponentType.SPOUT, xmlPath); _collector = collector;/*from w w w .j a va2s . c o m*/ SinfonierUtils.broadcastWorker((String) conf.get(Config.TOPOLOGY_NAME), context); twitterStream = createTwitterStream(); queue = new LinkedBlockingQueue<String>(1000); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(TwitterObjectFactory.getRawJSON(status)); } @Override public void onDeletionNotice(StatusDeletionNotice sdn) { } @Override public void onTrackLimitationNotice(int i) { } @Override public void onScrubGeo(long l, long l1) { } @Override public void onException(Exception e) { } @Override public void onStallWarning(StallWarning warning) { } }; twitterStream.addListener(listener); List<Object> rawKeywords = xml.getList("keyword"); // String rawKeywords = xml.get("keywords"); if (rawKeywords.isEmpty()) { twitterStream.sample(); } else { List<String> keywords = new ArrayList<String>(); for (Object field : rawKeywords) { keywords.add(((String) field).trim()); } FilterQuery query = new FilterQuery().track(keywords.toArray(new String[keywords.size()])); twitterStream.filter(query); } }