Wednesday, 5 February 2014

Twitter4J: Read public sample stream from Twitter

Today I am going to show you how to use Twitter4J to read a public sample stream of tweets from Twitter. Twitter4J is an unofficial Java library for the Twitter API and you can use it easily to integrate Twitter services in your application. Besides reading streams you can do a lot more like post or search Tweets. Twitter itself provides a bunch of documentation for developers and also a chapter on their Streaming API. This API gives you low latency access to Twitter's global stream of Tweet data.

You can get twitter4j-core from Maven central repository. For the streaming functionality you also need the twitter4j-stream library:

<dependency>
   <groupid>org.twitter4j</groupid>
   <artifactid>twitter4j-core</artifactid>
   <version>[3.0,)</version>
<dependency>
<dependency>
    <groupid>org.twitter4j</groupid>
    <artifactid>twitter4j-stream</artifactid>    
    <version>[3.0,)</version>
</dependency> 

Access to Twitters Streaming API is done by OAuth and you have to register your application first to get the needed set of credentials. After signing in with your regular Twitter account you can generate the following credentials and write it down in a twitter4j.properties file.

oauth.consumerKey=************
oauth.consumerSecret=************
oauth.accessToken=************
oauth.accessTokenSecret=************

To read the stream you can get a TwitterStream from the TwitterStreamFactory. Then you implement a Listener called StatusListener with a bunch of methods and your almost done. In the end you start streaming by calling the sample() method (that will stream from the Twitter sample stream).

import twitter4j.*;

public class TwitterStreamingClient {

   public static void main(String[] args) {

      TwitterStream stream = new TwitterStreamFactory().getInstance();
      stream.addListener(new StatusListener() {

         @Override
         public void onStatus(Status status) {
             System.out.println(status.getText());
         }

         @Override
         public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}

         @Override
         public void onTrackLimitationNotice(int i) {}

         @Override
         public void onScrubGeo(long l, long l2) {}

         @Override
         public void onStallWarning(StallWarning stallWarning) {}

         @Override
         public void onException(Exception e) {}
      });
      stream.sample();
   }
}

The Status object gives you all information about a Tweet like content, user, geolocation and many others. Check the Twitter4J documentation for more details.

See also