TweetStream4J – Twitter Streaming API in Java
I spent some time a few days back on the initial release of TweetStream4J. It is a Java library to interact with the new Twitter Streaming API (v1). Admittedly the initial release is one day old and a bit rough around the edges but still very useful.
I just wanna show here on the blog the example usage in order to persuade people to pick it up, or develop similarly built libraries in other languages.
My implementation revolves around an interface called TwitterStream Handler:
1 2 3 4 5 6 7 8 9 10 11 12 | public interface TwitterStreamHandler { //incoming tweet public void addTweet(STweet t); //incoming deletion request public void addLimit(STweet l); //incoming limit public void addDeletion(SDeletion d); } |
The handler is set to handle individual tweet, deletion, and limit request from twitter, and the objects they take as parameters are sent directly from the Streaming API, so a simple implmenetation of addTweet(STweet t) might look like:
1 2 3 4 | @Override void addTweet(STweet t) { System.out.println(t.getText() + " (by " + t.getUser().getScreenName() + ")"; } |
Once you have a useful handler, its time to put it to work. To use the ‘sample’ method is as easy as:
1 2 3 4 | TwitterStreamConfiguraion tws = new TwitterStreamConfiguration("username", "xx"); TwitterStream ts = TweetRiver.sample(tws, handler); (new Thread(ts)).start(); |
and the streaming will begin. If you’d rather track keywords or users as specified by the Twitter API site, you can use the ‘filter’ method.
1 2 3 4 5 6 7 8 9 | TwitterStreamConfiguration tws = new TwitterStreamConfiguration("username", "xx"); //build a list of strings to track Collection<String> tracks = new ArrayList<String>(); tracks.add("obama"); tracks.add("bush"); //start streaming TwitterStream ts = TweetRiver.filter(tws, handler, null, tracks); (new Thread(ts)).start(); |
The implementation covers the higher-level methods like ‘retweet’ and ‘firehose’ inaccessible to normal users, and has a full JavaDoc … so try it out and maybe contribute some code.
(BSD License)
Renaud 5:57 pm on January 20, 2010 Permalink
thanks John, got it working in minutes! here’s the maven deps just in case:
commons-logging
commons-logging
1.1.1
net.sf.json-lib
json-lib
2.3
john 6:01 pm on January 20, 2010 Permalink
Thanks I’m glad you had success. Let me know on github if you find any issues I haven’t already marked. Enjoy! I think the interfaces turned out to be a really nice solution
Giancarlo Frison 1:56 pm on March 12, 2010 Permalink
Thanks John!
remember to add:
commons-beanutils
commons.collections
ezmorph
to the dependencies as well. Good tool!
Giancarlo Frison 2:02 pm on March 12, 2010 Permalink
forget the readme..