Skip to content

Instantly share code, notes, and snippets.

@mccv
Created October 3, 2011 15:14
Show Gist options
  • Save mccv/1259343 to your computer and use it in GitHub Desktop.
Save mccv/1259343 to your computer and use it in GitHub Desktop.
OAuth with finagle streaming
import java.net._
import java.util.UUID
import com.twitter.conversions.time._
import com.twitter.finagle.builder.ClientBuilder
import com.twitter.util._
import java.nio.charset.Charset
import org.jboss.netty.buffer.{ChannelBuffers, ChannelBuffer}
import org.jboss.netty.handler.codec.http._
import com.twitter.finagle.stream.Stream
import com.twitter.joauth._
case class OAuthCredentials(token: String, consumerKey: String, tokenSecret: String, consumerSecret: String)
class OAuthStreamingClient(hostname: String, port: Int, creds: OAuthCredentials, path: String) {
val scheme = "https"
val address = new InetSocketAddress(hostname, port)
val clientFactory = ClientBuilder()
.codec(new Stream)
.tls(hostname)
.hosts(Seq(address))
.hostConnectionLimit(1)
.buildFactory()
val signatureMethod = OAuthParams.HMAC_SHA1
val realm = "https://www.twitter.com"
val oauthVersion = OAuthParams.ONE_DOT_OH
val oauthStr = """OAuth realm="%s",
oauth_consumer_key="%s",
oauth_token="%s",
oauth_signature_method="%s",
oauth_signature="%s",
oauth_timestamp="%s",
oauth_nonce="%s",
oauth_version="%s"
""".replaceAll(",\\s+",",")
def buildHeader() = {
val timestampSecs = Time.now.inSeconds
val timestampStr = "" + timestampSecs
val nonce = UUID.randomUUID().toString()
val oauthParams = OAuth1Params(creds.token, creds.consumerKey, nonce, timestampSecs, timestampStr,
null, signatureMethod, oauthVersion)
val normStr = StandardNormalizer(scheme, hostname, port, "GET", path, List(), oauthParams)
val sig = Signer()(normStr, creds.tokenSecret, creds.consumerSecret)
oauthStr.format(realm, creds.consumerKey, creds.token, signatureMethod, URLEncoder.encode(sig), timestampSecs, nonce, oauthVersion).trim
}
def go() {
val request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path)
val authHeader = buildHeader()
request.setHeader("Host", hostname)
request.setHeader("Authorization", authHeader)
val client = clientFactory.make()()
val clientRes = client(request)(1.second)
if (clientRes.httpResponse.getStatus.getCode != 200) {
println("error, code " + clientRes.httpResponse.getStatus.getCode)
println("body " + clientRes.httpResponse.getContent().toString(Charset.defaultCharset))
} else {
clientRes.messages foreach { channelBuffer =>
Future {
println("result: " + channelBuffer.toString(Charset.defaultCharset))
}
}
}
}
}
@robey
Copy link

robey commented Oct 4, 2011

you could use a list and mkString on line 30 to simplify that.

@StarWindMoonCloud
Copy link

What's the StandardNormalizer and Signer here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment