Implementing for Twitter live Stream

If you don’t regularly read xkcd, please start now.

telnet 2211

The above command will log you into a server I am running. It is running a filter of Twitter looking for posts containing “keyboard” and replacing that word with “leopard”. (See if you don’t get the joke) This was surprisingly easy to write using the twitter4j library and Java 7’s new Asynchronous Socket Channels. It was also fast enough to handle at least 100 concurrent listeners when I was doing local testing.

For purposes of this post I will focus only on the Twitter4j integration.

Twitter4j uses StatusListener objects to consume StatusStreams. This is where I break up the message and replace my words.

StatusListener listener = new StatusListener() {

public void onStatus(Status status) {
String tweet = status.getText();
tweet = tweet.toLowerCase();
int index = tweet.indexOf("keyboard");
tweet = status.getText();
tweet = tweet.subSequence(0, index) + "leopard" + tweet.subSequence(index + 8, tweet.length());

queue.transfer("@" + status.getUser().getScreenName() + " - " + tweet);


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) {

Now we configure Twitter4j to consume the stream.

ConfigurationBuilder cb = new ConfigurationBuilder();

long[] ids = {};
String[] tags = {"keyboard"};

FilterQuery query = new FilterQuery(0, ids, tags);

TwitterStream twitterStream = new TwitterStreamFactory(;

StatusStream stream = twitterStream.getFilterStream(query);

while (true) {;

The code should be rather self explanatory. FilterQuery creates a query which is submitted by Twitter4J to instruct Twitter to stream back tweets containing “keyboard”. I create a stream using my credentials and then loop to process each event. None of these are particularly exciting, and this code should be called in a main function or some background thread because it will block as written.