List of usage examples for twitter4j TwitterStream addListener
TwitterStream addListener(StreamListener listener);
From source file:com.accumulobook.designs.graph.TwitterGraph.java
License:Apache License
public static void ingest(final String[] args, final BatchWriter writer, int seconds) throws Exception { String token = args[0];//ww w . j av a2 s . c om String tokenSecret = args[1]; String consumerKey = args[2]; String consumerSecret = args[3]; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(new TGStatusListener(writer)); AccessToken accessToken = new AccessToken(token, tokenSecret); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); twitterStream.setOAuthAccessToken(accessToken); System.out.println("processing twitter stream ..."); twitterStream.sample(); Thread.sleep(seconds * 1000); System.out.println("shutting down twitter stream."); twitterStream.shutdown(); writer.flush(); }
From source file:com.babatunde.twittergoogle.Utility.java
public void postToGoogle(PlusDomains s, String id, String hashtag) { try {/*from w w w . j a v a2 s. c o m*/ final PlusDomains serve = s; final String circleID = id; listener = new StatusListener() { @Override public void onStatus(Status status) { String msg = status.getUser().getName() + " - " + "@" + status.getUser().getScreenName() + " - " + status.getText(); System.out.println(msg); //Create a list of ACL entries if (serve != null && (!circleID.isEmpty() || (circleID != null))) { PlusDomainsAclentryResource resource = new PlusDomainsAclentryResource(); resource.setType("domain").setType("circle").setId(circleID); //Get Emails of people in the circle. List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>(); aclEntries.add(resource); Acl acl = new Acl(); acl.setItems(aclEntries); acl.setDomainRestricted(true); // Required, this does the domain restriction // Create a new activity object Activity activity = new Activity() .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)).setAccess(acl); try { // Execute the API request, which calls `activities.insert` for the logged in user activity = serve.activities().insert("me", activity).execute(); } catch (IOException ex) { Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onException(Exception ex) { ex.printStackTrace(); } }; } catch (Exception e) { } TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance(); twitterStream.addListener(listener); String str[] = { hashtag }; twitterStream.shutdown(); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex); } twitterStream.filter(new FilterQuery().track(str)); }
From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java
License:Apache License
public static void setUserStreamListener(String username, UserStreamListener listener) { // Invokde timeline retrieving thread. // Stream API (only home) // Thread created in TwitterStream.sample() TwitterStream twitterStream = streamFactory.getInstance(); twitterStream.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret")); twitterStream.setOAuthAccessToken(TwitterFactoryAdapter.getAccessToken(username)); twitterStream.addListener(listener); twitterStream.user();//w w w.ja va 2 s .c o m }
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 ww w . j a va2s .com 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 ww w . j a v a 2s. c o 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. *///w ww . j a va2s. c om 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. ja va 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.mech2015task.App.java
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(CONSUMER_KEY); builder.setOAuthConsumerSecret(CONSUMER_SECRET); builder.setOAuthAccessToken(ACCESS_TOKEN); builder.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); // ??Twitter4J??API???betastream.twitter.com??????? builder.setUserStreamBaseURL("https://userstream.twitter.com/2/"); // Configuration? Configuration configuration = builder.build(); /* Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET) .setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET) .build();/*from w w w . jav a 2 s. c o m*/ */ TwitterStream twStream = new TwitterStreamFactory(configuration).getInstance(); //TwitterStream twStream = new TwitterStreamFactory().getInstance(); twStream.addListener(new MyStatusListener()); twStream.user(); //twStream.sample(); }
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 {/*from ww w . j av a 2s . c o 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.mycompany.twittersearch.Stream.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . ja va 2s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener(); twitterStream.addListener(listener); twitterStream.sample(); }