List of usage examples for twitter4j TwitterStream sample
TwitterStream sample();
From source file:nyu.twitter.lg.FentchTwitter.java
License:Open Source License
public static void invoke() throws Exception { init();/*from w w w . j a v a 2 s. c o m*/ // Create table if it does not exist yet if (Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is already ACTIVE"); } else { // Create a table with a primary hash key named 'name', which holds // a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("id") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active System.out.println("Waiting for " + tableName + " to become ACTIVE..."); Tables.waitForTableToBecomeActive(dynamoDB, tableName); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Emwo2pG").setOAuthConsumerSecret("RM9B7fske5T") .setOAuthAccessToken("19ubQOirq").setOAuthAccessTokenSecret("Lbg3C"); final TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { if (status.getGeoLocation() != null && status.getPlace() != null) { // if (count == 0) { // count++; // } // latitude = status.getGeoLocation().getLatitude(); longtitude = status.getGeoLocation().getLongitude(); place = status.getPlace().getCountry() + "," + status.getPlace().getFullName(); date = status.getCreatedAt().toString(); id = Integer.toString(count); name = status.getUser().getScreenName(); message = status.getText(); System.out.println("---------------------------"); System.out.println("ID:" + count); System.out.println("latitude:" + latitude); System.out.println("longtitude:" + longtitude); System.out.println("place:" + place); System.out.println("name:" + name); System.out.println("message:" + message); System.out.println("data:" + date); System.out.println("-------------8-------------"); insertDB(id, count, name, longtitude, latitude, place, message, date); if (++count > 100) { twitterStream.shutdown(); System.out.println("Information Collection Completed"); } // count = (count+1) % 101; } } @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(); }
From source file:org.apache.asterix.external.input.record.reader.twitter.TwitterPushRecordReader.java
License:Apache License
public TwitterPushRecordReader(TwitterStream twitterStream) { record = new GenericRecord<Status>(); inputQ = new LinkedBlockingQueue<Status>(); this.twitterStream = twitterStream;// this.twitterStream.addListener(new TweetListener(inputQ)); twitterStream.sample(); }
From source file:org.apache.druid.examples.twitter.TwitterSpritzerFirehoseFactory.java
License:Apache License
@Override public Firehose connect(InputRowParser parser, File temporaryDirectory) { final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() { @Override//from w w w .java 2s .co m public void onConnect() { log.info("Connected_to_Twitter"); } @Override public void onDisconnect() { log.info("Disconnect_from_Twitter"); } /** * called before thread gets cleaned up */ @Override public void onCleanUp() { log.info("Cleanup_twitter_stream"); } }; // ConnectionLifeCycleListener final TwitterStream twitterStream; final StatusListener statusListener; final int QUEUE_SIZE = 2000; /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread. */ final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE); final long startMsec = System.currentTimeMillis(); // // set up Twitter Spritzer // twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener); statusListener = new StatusListener() { // This is what really gets called to deliver stuff from twitter4j @Override public void onStatus(Status status) { // time to stop? if (Thread.currentThread().isInterrupted()) { throw new RuntimeException("Interrupted, time to stop"); } try { boolean success = queue.offer(status, 15L, TimeUnit.SECONDS); if (!success) { log.warn("queue too slow!"); } } catch (InterruptedException e) { throw new RuntimeException("InterruptedException", e); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // This notice will be sent each time a limited stream becomes unlimited. // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity. log.warn("Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onException(Exception ex) { log.error(ex, "Got exception"); } @Override public void onStallWarning(StallWarning warning) { log.warn("Got stall warning: %s", warning); } }; twitterStream.addListener(statusListener); twitterStream.sample(); // creates a generic StatusStream log.info("returned from sample()"); return new Firehose() { private final Runnable doNothingRunnable = new Runnable() { @Override public void run() { } }; private long rowCount = 0L; private boolean waitIfmax = (getMaxEventCount() < 0L); private final Map<String, Object> theMap = new TreeMap<>(); // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper(); private boolean maxTimeReached() { if (getMaxRunMinutes() <= 0) { return false; } else { return (System.currentTimeMillis() - startMsec) / 60000L >= getMaxRunMinutes(); } } private boolean maxCountReached() { return getMaxEventCount() >= 0 && rowCount >= getMaxEventCount(); } @Override public boolean hasMore() { if (maxCountReached() || maxTimeReached()) { return waitIfmax; } else { return true; } } @Nullable @Override public InputRow nextRow() { // Interrupted to stop? if (Thread.currentThread().isInterrupted()) { throw new RuntimeException("Interrupted, time to stop"); } // all done? if (maxCountReached() || maxTimeReached()) { if (waitIfmax) { // sleep a long time instead of terminating try { log.info("reached limit, sleeping a long time..."); Thread.sleep(2000000000L); } catch (InterruptedException e) { throw new RuntimeException("InterruptedException", e); } } else { // allow this event through, and the next hasMore() call will be false } } if (++rowCount % 1000 == 0) { log.info("nextRow() has returned %,d InputRows", rowCount); } Status status; try { status = queue.take(); } catch (InterruptedException e) { throw new RuntimeException("InterruptedException", e); } theMap.clear(); HashtagEntity[] hts = status.getHashtagEntities(); String text = status.getText(); theMap.put("text", (null == text) ? "" : text); theMap.put("htags", (hts.length > 0) ? Lists.transform(Arrays.asList(hts), new Function<HashtagEntity, String>() { @Nullable @Override public String apply(HashtagEntity input) { return input.getText(); } }) : ImmutableList.<String>of()); long[] lcontrobutors = status.getContributors(); List<String> contributors = new ArrayList<>(); for (long contrib : lcontrobutors) { contributors.add(StringUtils.format("%d", contrib)); } theMap.put("contributors", contributors); GeoLocation geoLocation = status.getGeoLocation(); if (null != geoLocation) { double lat = status.getGeoLocation().getLatitude(); double lon = status.getGeoLocation().getLongitude(); theMap.put("lat", lat); theMap.put("lon", lon); } else { theMap.put("lat", null); theMap.put("lon", null); } if (status.getSource() != null) { Matcher m = sourcePattern.matcher(status.getSource()); theMap.put("source", m.find() ? m.group(1) : status.getSource()); } theMap.put("retweet", status.isRetweet()); if (status.isRetweet()) { Status original = status.getRetweetedStatus(); theMap.put("retweet_count", original.getRetweetCount()); User originator = original.getUser(); theMap.put("originator_screen_name", originator != null ? originator.getScreenName() : ""); theMap.put("originator_follower_count", originator != null ? originator.getFollowersCount() : ""); theMap.put("originator_friends_count", originator != null ? originator.getFriendsCount() : ""); theMap.put("originator_verified", originator != null ? originator.isVerified() : ""); } User user = status.getUser(); final boolean hasUser = (null != user); theMap.put("follower_count", hasUser ? user.getFollowersCount() : 0); theMap.put("friends_count", hasUser ? user.getFriendsCount() : 0); theMap.put("lang", hasUser ? user.getLang() : ""); theMap.put("utc_offset", hasUser ? user.getUtcOffset() : -1); // resolution in seconds, -1 if not available? theMap.put("statuses_count", hasUser ? user.getStatusesCount() : 0); theMap.put("user_id", hasUser ? StringUtils.format("%d", user.getId()) : ""); theMap.put("screen_name", hasUser ? user.getScreenName() : ""); theMap.put("location", hasUser ? user.getLocation() : ""); theMap.put("verified", hasUser ? user.isVerified() : ""); theMap.put("ts", status.getCreatedAt().getTime()); List<String> dimensions = Lists.newArrayList(theMap.keySet()); return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap); } @Override public Runnable commit() { // ephemera in, ephemera out. return doNothingRunnable; // reuse the same object each time } @Override public void close() { log.info("CLOSE twitterstream"); twitterStream.shutdown(); // invokes twitterStream.cleanUp() } }; }
From source file:org.apache.s4.example.twitter.TwitterInputAdapter.java
License:Apache License
public void connectAndRead() throws Exception { ConfigurationBuilder cb = new ConfigurationBuilder(); Properties twitterProperties = new Properties(); File twitter4jPropsFile = new File(System.getProperty("user.home") + "/twitter4j.properties"); if (!twitter4jPropsFile.exists()) { logger.error(//from www .j a va 2s .c o m "Cannot find twitter4j.properties file in this location :[{}]. Make sure it is available at this place and includes user/password credentials", twitter4jPropsFile.getAbsolutePath()); return; } twitterProperties.load(new FileInputStream(twitter4jPropsFile)); cb.setDebugEnabled(Boolean.valueOf(twitterProperties.getProperty("debug"))) .setUser(twitterProperties.getProperty("user")) .setPassword(twitterProperties.getProperty("password")); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener statusListener = new StatusListener() { @Override public void onException(Exception ex) { logger.error("error", ex); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { logger.error("error"); } @Override public void onStatus(Status status) { messageQueue.add(status); } @Override public void onScrubGeo(long userId, long upToStatusId) { logger.error("error"); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { logger.error("error"); } }; twitterStream.addListener(statusListener); twitterStream.sample(); }
From source file:org.drools.examples.twittercbr.TwitterCBR.java
License:Apache License
/** * Main method// w w w . j a v a 2 s.co m */ public static void main(String[] args) throws TwitterException, IOException { if (args.length == 0) { System.out.println("Please provide the rules file name to load."); System.exit(0); } // Creates a knowledge base final KnowledgeBase kbase = createKnowledgeBase(args[0]); // Creates a knowledge session final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); // Gets the stream entry point final WorkingMemoryEntryPoint ep = ksession.getWorkingMemoryEntryPoint("twitter"); // Connects to the twitter stream and register the listener new Thread(new Runnable() { @Override public void run() { StatusListener listener = new TwitterStatusListener(ep); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }).start(); // Starts to fire rules in Drools Fusion ksession.fireUntilHalt(); }
From source file:org.opencredo.twitter.si.SampleTwitterStreamInboundChannelAdapter.java
License:Apache License
@Override public TwitterStream refresh(TwitterStreamConfiguration twitterStreamConfiguration) throws TwitterException { TwitterStream stream = super.refresh(twitterStreamConfiguration); stream.sample(); return stream; }
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 ww . j a v a 2s . c o m 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.socialsketch.tool.rubbish.experiments.PrintSampleStream.java
License:Apache License
/** * Main entry of this application./*from w w w .j a v a2 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.xmlsh.twitter.stream.java
License:BSD License
@Override public int run(List<XValue> args) throws Exception { Options opts = new Options(sCOMMON_OPTS + ",p=port:,track:,sample,json,sanitize", SerializeOpts.getOptionDefs()); opts.parse(args);/* w w w . j a v a2 s. co m*/ mSerializeOpts = this.getSerializeOpts(opts); final boolean bJson = opts.hasOpt("json"); final boolean bSanitize = opts.hasOpt("sanitize"); args = opts.getRemainingArgs(); final OutputPort port = mShell.getEnv().getOutputPort(opts.getOptStringRequired("port"), true); StatusListener listener = new StatusListener() { public void onStatus(Status status) { try { if (bJson) { String json = DataObjectFactory.getRawJSON(status); PrintWriter writer = port.asPrintWriter(mSerializeOpts); writer.println(json); writer.close(); } else { TwitterWriter mWriter = new TwitterWriter(port.asXMLStreamWriter(mSerializeOpts), bSanitize); mWriter.startDocument(); mWriter.startElement(TwitterWriter.kTWITTER_NS, "twitter"); mWriter.writeDefaultNamespace(); mWriter.write("status", status); mWriter.endElement(); mWriter.endDocument(); mWriter.closeWriter(); port.writeSequenceTerminator(mSerializeOpts); } } catch (Exception e) { onException(e); } } 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 arg0) { // TODO Auto-generated method stub } }; try { TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. // FilterQuery filter = new FilterQuery().track(Util.toStringArray(args)); // twitterStream.filter(filter); if (opts.hasOpt("sample")) twitterStream.sample(); else twitterStream.filter(new FilterQuery().track(opts.getOptStringRequired("track").split(","))); } finally { } return 0; }
From source file:public_streaming.PublicStream.java
License:Apache License
public static void main(String[] args) throws Exception { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build(); TwitterStream twStream = new TwitterStreamFactory(configuration).getInstance(); twStream.addListener(new MyStatusListener()); twStream.sample();//public_timeline }