2013年3月6日水曜日

Hosebirdを使ってユーザーストリームを取得する

TwitterAPIも1.1になったりと色々盛り上がっている中、新しいライブラリのHosebirdをTwitterが公開しました。

米Twitter、Streaming API向けJavaクライアント「Hosebird Client」をオープンソースに

TwitterがAPIのクライアントライブラリをOSSにするのは初めてとのこと。

面白いのが、Twitter4jを利用していること。どの程度のことができるのかはわかりませんが、
今までTwitter4jを利用して作成したアプリケーションの拡張なんかがお手軽にできるかもしれませんね。

というわけで、TwitterなのでScalaでコードを書いてみました。sbt 0.12.2, scala2.9.3で動きます。

name := "hosebird"
version := "0.1.0"
scalaVersion := "2.9.3"
libraryDependencies += "com.twitter" % "hbc-core" % "1.3.0"
libraryDependencies += "commons-lang" % "commons-lang" % "2.6"
view raw build.sbt hosted with ❤ by GitHub
package jp.numa08.hosebird
import com.twitter.hbc.ClientBuilder
import com.twitter.hbc.core._
import com.twitter.hbc.core.processor.StringDelimitedProcessor;
import com.twitter.hbc.httpclient.auth.OAuth1
import com.twitter.hbc.core.endpoint.UserstreamEndpoint;
import scala.collection.JavaConversions._
import java.util.concurrent.LinkedBlockingQueue
import org.apache.commons.lang.StringEscapeUtils
object MyApp extends App {
val oauth = new OAuth1("consumerKey", "consumerSecret", "token", "tokenSecret")
val texts = new LinkedBlockingQueue[String](100000)
val client = new ClientBuilder()
.hosts(Constants.USERSTREAM_HOST)
.authentication(oauth)
.processor(new StringDelimitedProcessor(texts))
.endpoint(new UserstreamEndpoint())
.build()
client.connect
Stream.continually(texts.take).foreach(json => { val out = StringEscapeUtils.unescapeJava(json)
println(out)})
}
view raw MyApp.scala hosted with ❤ by GitHub



ClientBuilder#hostとClientBuilder#endpoint を変えてあげれば他のストリームもお手軽に取得できます。


あ、FirehoseだからHosebirdなのか。今気がついた・・・・。

GitHub





0 件のコメント:

コメントを投稿