List of usage examples for twitter4j TwitterStream addListener
TwitterStream addListener(StreamListener listener);
From source file:org.elasticsearch.river.twitter.TwitterRiver.java
License:Apache License
/** * Twitter Stream Builder/* w w w .jav a 2 s .c om*/ * @return */ private TwitterStream buildTwitterStream() { logger.debug("creating TwitterStreamFactory"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(oauthConsumerKey).setOAuthConsumerSecret(oauthConsumerSecret) .setOAuthAccessToken(oauthAccessToken).setOAuthAccessTokenSecret(oauthAccessTokenSecret); if (proxyHost != null) cb.setHttpProxyHost(proxyHost); if (proxyPort != null) cb.setHttpProxyPort(Integer.parseInt(proxyPort)); if (proxyUser != null) cb.setHttpProxyUser(proxyUser); if (proxyPassword != null) cb.setHttpProxyPassword(proxyPassword); if (raw) cb.setJSONStoreEnabled(true); // We force SSL usage cb.setUseSSL(true); TwitterStream stream = new TwitterStreamFactory(cb.build()).getInstance(); stream.addListener(new StatusHandler()); return stream; }
From source file:org.primeoservices.cfgateway.twitter.TwitterUserStream.java
License:Apache License
/** * /*from ww w. j a v a 2s.co m*/ */ @Override protected void initStream(final TwitterStream stream) { stream.addListener(this); stream.user(); }
From source file:org.rtsa.storm.TwitterSpout.java
License:Apache License
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;/* w w w . j a v a2 s.com*/ StatusListener listener = new StatusListener() { public void onStatus(Status status) { if (status.getText().length() != 0 && status.getLang().equals("en")) { queue.offer(status); } } public void onDeletionNotice(StatusDeletionNotice sdn) { } public void onTrackLimitationNotice(int i) { } public void onScrubGeo(long l, long l1) { } public void onException(Exception ex) { } 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:org.selman.tweetamo.TweetamoClient.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: [language] [search topic]"); }//from ww w.ja v a 2 s . c o m kinesisClient = new AmazonKinesisClient(new ClasspathPropertiesFileCredentialsProvider()); waitForStreamToBecomeAvailable(STREAM_NAME); LOG.info("Publishing tweets to stream : " + STREAM_NAME); StatusListener listener = new StatusListener() { public void onStatus(Status status) { try { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(STREAM_NAME); putRecordRequest.setData(TweetSerializer.toBytes(status)); putRecordRequest.setPartitionKey(status.getUser().getScreenName()); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); LOG.info("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); } catch (Exception e) { LOG.error("Failed to putrecord", e); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onScrubGeo(long arg0, long arg1) { } @Override public void onStallWarning(StallWarning arg0) { } }; ClasspathTwitterCredentialsProvider provider = new ClasspathTwitterCredentialsProvider(); TwitterCredentials credentials = provider.getTwitterCredentials(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(credentials.getConsumerKey()) .setOAuthConsumerSecret(credentials.getConsumerSecret()) .setOAuthAccessToken(credentials.getAccessToken()) .setOAuthAccessTokenSecret(credentials.getAccessTokenSecret()); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); twitterStream.addListener(listener); FilterQuery filterQuery = new FilterQuery(); filterQuery.language(new String[] { args[0] }); filterQuery.track(new String[] { args[1] }); twitterStream.filter(filterQuery); }
From source file:org.smarttechie.servlet.SimpleStream.java
public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out) { listener = new StatusListener() { @Override/*w w w . j av a 2s .c o m*/ public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { Twitter twitter = new TwitterFactory().getInstance(); User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); System.out.println(""); String profileLocation = user.getLocation(); System.out.println(profileLocation); long tweetId = status.getId(); System.out.println(tweetId); String content = status.getText(); System.out.println(content + "\n"); JSONObject obj = new JSONObject(); obj.put("User", status.getUser().getScreenName()); obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''")); obj.put("Id", status.getId()); obj.put("UserId", status.getUser().getId()); //obj.put("User", status.getUser()); obj.put("Message", status.getText().replaceAll("'", "''")); obj.put("CreatedAt", status.getCreatedAt().toString()); obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId()); //Get user retweeteed String otheruser; try { if (status.getCurrentUserRetweetId() != -1) { User user2 = twitter.showUser(status.getCurrentUserRetweetId()); otheruser = user2.getScreenName(); System.out.println("Other user: " + otheruser); } } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage().toString()); } obj.put("IsRetweet", status.isRetweet()); obj.put("IsRetweeted", status.isRetweeted()); obj.put("IsFavorited", status.isFavorited()); obj.put("InReplyToUserId", status.getInReplyToUserId()); //In reply to obj.put("InReplyToScreenName", status.getInReplyToScreenName()); obj.put("RetweetCount", status.getRetweetCount()); if (status.getGeoLocation() != null) { obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude()); obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude()); } JSONArray listHashtags = new JSONArray(); String hashtags = ""; for (HashtagEntity entity : status.getHashtagEntities()) { listHashtags.add(entity.getText()); hashtags += entity.getText() + ","; } if (!hashtags.isEmpty()) obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1)); if (status.getPlace() != null) { obj.put("PlaceCountry", status.getPlace().getCountry()); obj.put("PlaceFullName", status.getPlace().getFullName()); } obj.put("Source", status.getSource()); obj.put("IsPossiblySensitive", status.isPossiblySensitive()); obj.put("IsTruncated", status.isTruncated()); if (status.getScopes() != null) { JSONArray listScopes = new JSONArray(); String scopes = ""; for (String scope : status.getScopes().getPlaceIds()) { listScopes.add(scope); scopes += scope + ","; } if (!scopes.isEmpty()) obj.put("Scopes", scopes.substring(0, scopes.length() - 1)); } obj.put("QuotedStatusId", status.getQuotedStatusId()); JSONArray list = new JSONArray(); String contributors = ""; for (long id : status.getContributors()) { list.add(id); contributors += id + ","; } if (!contributors.isEmpty()) obj.put("Contributors", contributors.substring(0, contributors.length() - 1)); System.out.println("" + obj.toJSONString()); insertNodeNeo4j(obj); //out.println(obj.toJSONString()); String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';"; executeQuery(session, statement); } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @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(); fq.track(parametros); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:org.socialsketch.tool.rubbish.experiments.PrintSampleStream.java
License:Apache License
/** * Main entry of this application.//from ww w .j a v a 2 s. c o m * * @param args */ public static void main(String[] args) throws TwitterException { TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); } @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(); } }; twitterStream.addListener(listener); twitterStream.sample(); //twitterStream. }
From source file:org.socialsketch.tool.rubbish.twitterstream.PrintFilterStream.java
License:Apache License
/** * Main entry of this application.//w w w.j a va2s .co m * * @param args follow(comma separated user ids) track(comma separated filter terms) * @throws twitter4j.TwitterException */ public static void main(String[] args) throws TwitterException { // if (args.length < 1) { // System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]"); // System.exit(-1); // } StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); } @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(); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); ArrayList<Long> follow = new ArrayList<Long>(); ArrayList<String> track = new ArrayList<String>(); // for (String arg : args) { // if (isNumericalArgument(arg)) { // for (String id : arg.split(",")) { // follow.add(Long.parseLong(id)); // } // } else { // track.addAll(Arrays.asList(arg.split(","))); // } // } track.add("void setup draw"); track.add("void size"); long[] followArray = new long[follow.size()]; for (int i = 0; i < follow.size(); i++) { followArray[i] = follow.get(i); } String[] trackArray = track.toArray(new String[track.size()]); // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.filter(new FilterQuery(0, followArray, trackArray)); }
From source file:org.threeriverdev.twitterreporter.TwitterBot.java
License:Apache License
public static void main(String... args) throws Exception { FilterQuery query = new FilterQuery(); List<double[]> locations = new ArrayList<double[]>(); // Create a grid over the continental US. // TODO: Originally (2009ish), these were recommended by Twitter. Not sure if it's relevant now or not -- // could we achieve the same results with 1 big block? for (double swLat = 25.0; swLat <= 49.0; swLat = swLat + GRIDSIZE) { for (double swLon = -125.0; swLon <= -67.0; swLon = swLon + GRIDSIZE) { double neLat = swLat + GRIDSIZE; double neLon = swLon + GRIDSIZE; double[] swLocation = new double[2]; swLocation[0] = swLon;/*from w ww . j a v a2 s .c o m*/ swLocation[1] = swLat; locations.add(swLocation); double[] neLocation = new double[2]; neLocation[0] = neLon; neLocation[1] = neLat; locations.add(neLocation); } } query.locations(locations.toArray(new double[0][0])); try { URL url = TwitterBot.class.getResource("/oauth.properties"); Properties p = new Properties(); InputStream inStream = url.openStream(); p.load(inStream); ConfigurationBuilder confBuilder = new ConfigurationBuilder(); confBuilder.setOAuthConsumerKey(p.getProperty("consumer.key")); confBuilder.setOAuthConsumerSecret(p.getProperty("consumer.secret")); confBuilder.setOAuthAccessToken(p.getProperty("access.token")); confBuilder.setOAuthAccessTokenSecret(p.getProperty("access.token.secret")); Configuration conf = confBuilder.build(); TwitterStream twitterStream = new TwitterStreamFactory(conf).getInstance(); twitterStream.addListener(new TweetProcessor()); twitterStream.filter(query); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.todoke.countstream.Main.java
License:Apache License
public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: java org.todoke.hashcount.Main [comma separated terms to track]"); System.exit(-1);//from w w w . j a v a 2 s .c om } logger.info("terms to track: " + args[0]); String[] terms = args[0].split(","); FilterQuery query = new FilterQuery().track(terms); TwitterStream stream = new TwitterStreamFactory().getInstance(); StringBuffer path = new StringBuffer(args[0].length()); for (String term : terms) { if (0 != path.length()) { path.append("-"); } path.append(term.replaceAll("#", "")); } Callback callback = new Callback(terms); Counter counter = new Counter(callback); stream.addListener(counter); stream.filter(query); }
From source file:org.wso2.carbon.inbound.custom.poll.TwitterStreamData.java
License:Open Source License
/** * Setting up a connection with Twitter Stream API with the given * credentials//w ww . jav a 2 s .co m * * @throws TwitterException */ private void setupConnection() throws TwitterException { if (log.isDebugEnabled()) { log.debug("Starting to setup the connection with the twitter streaming endpoint"); } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessSecret); StatusListener statusStreamsListener; UserStreamListener userStreamListener; SiteStreamsListener siteStreamslistener; TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance(); String twitterOperation = properties.getProperty(TwitterConstant.TWITTER_OPERATION); if (twitterOperation.equals(TwitterConstant.FILTER_STREAM_OPERATION) || twitterOperation.equals(TwitterConstant.FIREHOSE_STREAM_OPERATION) || twitterOperation.equals(TwitterConstant.LINK_STREAM_OPERATION) || twitterOperation.equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) { statusStreamsListener = new StatusListenerImpl(); twitterStream.addListener(statusStreamsListener); } else if (twitterOperation.equals(TwitterConstant.USER_STREAM_OPERATION)) { userStreamListener = new UserStreamListenerImpl(); twitterStream.addListener(userStreamListener); } else if (twitterOperation.equals(TwitterConstant.SITE_STREAM_OPERATION)) { siteStreamslistener = new siteStreamsListenerImpl(); twitterStream.addListener(siteStreamslistener); } else { handleException("The operation :" + twitterOperation + " not found"); } /* Synchronously retrieves public statuses that match one or more filter predicates.*/ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.FILTER_STREAM_OPERATION)) { FilterQuery query = new FilterQuery(); if (languages != null) { query.language(languages); } if (tracks != null) { query.track(tracks); } if (follow != null) { query.follow(follow); } if (filterLevel != null) { query.filterLevel(filterLevel); } query.count(count); twitterStream.filter(query); } /* Returns a small random sample of all public statuses. */ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) { if (languages != null) { if (languages.length == 1) { twitterStream.sample(languages[1]); } else { handleException("A language can be used for the sample operation"); } } twitterStream.sample(); } /* Asynchronously retrieves all public statuses.*/ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)) { if (countParam != null) { twitterStream.firehose(count); } } /* User Streams provide a stream of data and events specific to the authenticated user.This provides to access the Streams messages for a single user. */ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.USER_STREAM_OPERATION)) { if (tracks != null) { twitterStream.user(tracks); } twitterStream.user(); } /* * Link Streams provide asynchronously retrieves all statuses containing 'http:' and 'https:'. */ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.LINK_STREAM_OPERATION)) { if (countParam != null) { twitterStream.links(count); } } /* * User Streams provide a stream of data and events specific to the * authenticated user.This provides to access the Streams messages for a * single user. */ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.RETWEET_STREAM_OPERATION)) { twitterStream.retweet(); } /* * Site Streams allows services, such as web sites or mobile push * services, to receive real-time updates for a large number of users. * Events may be streamed for any user who has granted OAuth access to * your application. Desktop applications or applications with few users * should use user streams. */ if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION)) .equals(TwitterConstant.SITE_STREAM_OPERATION)) { twitterStream.site(withFollowings, follow); } }