Listening to status updates

When the Configuration object is available, we can start setting up the code to monitor status updates and receive that data into our application.

Firstly, we need to acquire the TwitterStream object with this:

TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

Next, we will need to create a listener that will be receiving the status updates. The listener is created with this:

StatusListener listener = new StatusListener() {
@Override
public void onStatus(Status status) {
System.out.println(status.getUser().getName() + " : " +
status.getText());
}

@Override
public void onDeletionNotice(StatusDeletionNotice
statusDeletionNotice) {
}

@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
}

@Override
public void onScrubGeo(long userId, long upToStatusId) {
}

@Override
public void onStallWarning(StallWarning warning) {
}

@Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};

We can see that there are quite a few methods from the StatusListener interface that need to be implemented. However, we will only be interested in the following to capture status updates:

void onStatus(Status status)

To handle any exceptions that can occur, we will be interested in this:

void onException(Exception ex)

When we have a StatusListener available, we can plug it into the TwitterStream by calling this:

twitterStream.addListener(listener);

The last step is to initiate a connection and start listening to the updates. For this, we will use the following method:

twitterStream.filter();

However, this method needs a criterion to select what kind of status updates we will listen to. For this, we will use the FilterQuery class:

twitterStream.filter(
new FilterQuery()
.track("Yahoo", "Google", "Microsoft")
.language("en")
);

Here, the following call specifies what kind of keywords we are looking for in the tweets:

.track("Yahoo", "Google", "Microsoft")

This limits tweets only to the English language:

.language("en")

As soon as .filter() is called, the StatusListener will start receiving updates and that can be seen in the console.

The whole code will look like this:

TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();
twitterStream.addListener(listener);
twitterStream.filter(
new FilterQuery()
.track("Yahoo", "Google", "Microsoft")
.language("en")
);

Here, the configuration and listener variables are the ones we have created before.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.142.85