-
Notifications
You must be signed in to change notification settings - Fork 105
/
TwitterReceiver.java
100 lines (84 loc) · 2.61 KB
/
TwitterReceiver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package org.sparkexample;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.receiver.Receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Twitter stream receiver. Make sure resources/twitter4j.properties contains your Twitter
* authentication values. {@see https://apps.twitter.com}.
*
* This receiver tracks the status messages containing the keyword twitter.
*/
public final class TwitterReceiver extends Receiver<Status> {
private static final Logger LOGGER = LoggerFactory.getLogger(TwitterReceiver.class);
/**
* The keywords to be tracked.
*/
private static final String KEYWORDS = "twitter";
private final TwitterStream twitterStream;
private StatusListener listener;
public TwitterReceiver(StorageLevel storageLevel) {
super(storageLevel);
checkArgument(StorageLevel.MEMORY_ONLY().equals(storageLevel),
String.format("Only [%s] supported.", StorageLevel.MEMORY_ONLY().toString()));
twitterStream = new TwitterStreamFactory().getInstance();
}
@Override
public void onStart() {
if (listener == null) {
listener = new StreamListener();
}
twitterStream.addListener(listener);
twitterStream.filter(createFilter());
}
private FilterQuery createFilter() {
FilterQuery filterQuery = new FilterQuery();
try {
filterQuery.track(KEYWORDS);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new IllegalArgumentException(e);
}
return filterQuery;
}
@Override
public void onStop() {
twitterStream.clearListeners();
twitterStream.cleanUp();
listener = null;
}
private class StreamListener implements StatusListener {
@Override
public void onStatus(Status status) {
store(status);
}
@Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
// Intentionally empty.
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
// Intentionally empty.
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
// Intentionally empty.
}
@Override
public void onStallWarning(StallWarning warning) {
// Intentionally empty.
}
@Override
public void onException(Exception ex) {
LOGGER.warn(ex.getMessage(), ex);
}
}
}