Created
February 22, 2015 06:23
-
-
Save smallufo/d157b146e14dc017c461 to your computer and use it in GitHub Desktop.
Listening to twitter keywords , implemented by Twitter4j and RxJava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by smallufo on 2015-02-22. | |
*/ | |
package twitter; | |
import rx.Observable; | |
import rx.subjects.PublishSubject; | |
import rx.subjects.Subject; | |
import twitter4j.*; | |
import twitter4j.conf.ConfigurationBuilder; | |
import java.util.List; | |
public class TrackerByTwitter4j { | |
private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(getClass()); | |
private final String consumerKey = "xxx"; | |
/** consumer secret */ | |
private final String secretKey = "xxx"; | |
private final String accessToken = "xxx"; | |
private final String accessSecret = "xxx"; | |
Subject<Status , Status> subject = PublishSubject.create(); | |
private TwitterStream twitterStream ; | |
public TrackerByTwitter4j() { | |
ConfigurationBuilder cb = new ConfigurationBuilder(); | |
cb.setDebugEnabled(true) | |
.setOAuthConsumerKey(consumerKey) | |
.setOAuthConsumerSecret(secretKey) | |
.setOAuthAccessToken(accessToken) | |
.setOAuthAccessTokenSecret(accessSecret); | |
twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); | |
twitterStream.addListener(new StatusAdapter() { | |
@Override | |
public void onStatus(Status status) { | |
super.onStatus(status); | |
subject.onNext(status); | |
} | |
}); | |
} | |
public Observable<Status> track(List<String> tracks) throws TwitterException { | |
FilterQuery fq = new FilterQuery(); | |
twitterStream.filter(fq.track(tracks.toArray(new String[tracks.size()]))); | |
return subject.asObservable(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package twitter; | |
import org.junit.Test; | |
import org.slf4j.Logger; | |
import twitter4j.Status; | |
import java.util.Arrays; | |
public class TrackerByTwitter4jTest { | |
private Logger logger = org.slf4j.LoggerFactory.getLogger(getClass()); | |
@Test | |
public void testTrack() throws Exception { | |
TrackerByTwitter4j tracker = new TrackerByTwitter4j(); | |
tracker.track(Arrays.asList("taiwan")) | |
.map(Status::getText) | |
.toBlocking() | |
.forEach(s -> logger.info("{}", s)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OkHttp version : https://gist.github.com/smallufo/efd39c8997db8f43dca9