Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created April 29, 2010 14:08
Show Gist options
  • Save ymnk/383647 to your computer and use it in GitHub Desktop.
Save ymnk/383647 to your computer and use it in GitHub Desktop.
A self-contained sample code to tweet with OAuth in scala
* Replace XXXs in Tweet.scala with your
consumer_token,
consumer_secret,
access_token,
token_secret.
* Try following commands,
$ scalac Tweet.scala Consumer.scala
$ scala Tweet
/**
Copyright (c) 2010 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*/
package com.jcraft.oauth
import java.net.{URL, HttpURLConnection}
/**
* <pre>
* val url = new URL("http://example.com/foo")
* val urlConn = url.openConnection.asInstanceOf[HttpURLConnection]
*
* import com.jcraft.oauth.Consumer
* val consumer = new Consumer(CONSUMER_KEY, CONSUMER_SECRET)
* consumer.sign(rulConn, ACCESS_TOKEN, TOKEN_SECRET)
*
* urlConn.connect
* urlConn.getReponseCode
* </pre>
*
* Comments will refer to 'OAuth Core 1.0'[1].
*
* [1] http://oauth.net/core/1.0/
*/
class Consumer(private val consumer_key: String,
private val consumer_secret: String){
import Consumer._
def sign(request: HttpURLConnection,
access_token: String, token_secret: String ): HttpURLConnection = {
sign(request, "", access_token, token_secret)
}
def sign(request: HttpURLConnection,
query_string: String, // for POST
access_token: String, token_secret: String ): HttpURLConnection = {
sign(HTTPMethod(request.getRequestMethod),
request.getURL.toString,
Some(query_string),
Some((access_token, token_secret))) match {
case (k, v) => request.setRequestProperty(k, v)
}
request
}
def sign(method: HTTPMethod.Value,
url: String,
query_string: Option[String],
token: Option[(String, String)] // (access_token, token_secret)
): (String, String) = {
val (base_url, user_params) = normalize(url, query_string)
/**
* "7. Accessing ProtectedResources" has defined following parameters.
*/
val oauth_params = Set(
"oauth_consumer_key" -> consumer_key,
"oauth_signature_method" -> "HMAC-SHA1",
"oauth_timestamp" -> (System.currentTimeMillis / 1000).toString,
"oauth_nonce" -> System.nanoTime.toString,
"oauth_version" -> "1.0" // Optional
) ++ (token.map{t => Set("oauth_token" -> t._1)} getOrElse Set[(String,String)]())
/**
* 9.1.3. Concatenate Request Elements
*/
val signature_base_string =
method.toString + "&" +
urlencoder(url) + "&" +
(sort((user_params ++ oauth_params).toSeq) map {
case (k, v) => urlencoder(k) + "%3D" + urlencoder(v)
} mkString "%26")
/**
* 9.2. HMAC-SHA1
*/
val signature = {
import javax.crypto
val SHA1 = "HmacSHA1"
val key = urlencoder(consumer_secret) + "&" +
(token map {t => urlencoder(t._2)} getOrElse "")
val mac = crypto.Mac.getInstance(SHA1)
mac.init(new crypto.spec.SecretKeySpec(key.getBytes, SHA1))
new String(b64encoder(mac.doFinal(signature_base_string.getBytes)))
}
("Authorization",
"OAuth " + ((oauth_params + ("oauth_signature" -> signature)) map {
case (k, v) => "%s=\"%s\"".format(k, urlencoder(v))
} mkString ","))
}
}
object Consumer{
private def normalize(url: String, query_string: Option[String]) = {
val(normalized_url, query) = url.split('?') match {
case Array(url, query) => (url , query)
case _ => (url , "")
}
(normalized_url,
(query + "&" + query_string.getOrElse("")).split("&").
filter(s => {s != "=" && s != ""}).
foldLeft(Set[(String,String)]()){
case (s, b) => s + {b.split("=") match{
case Array(k) => (urldecoder(k) ->"")
case Array(k,v) => (urldecoder(k) -> urldecoder(v))
}}
} map { case (k,v)=>(urlencoder(k), urlencoder(v)) }
)
}
/**
* 5.1 Parameter Encoding
* Characters in the unreserved character set MUST NOT be encoded,
* and '~' is included in the unreserved character.
* URLEncoder will encode ' ' to '+'.
*/
private val urlencoder =
(s:String) => java.net.URLEncoder.encode(s, "UTF-8").
replace ("*", "%42").
replace ("+", "%20").
replace ("%7E", "~")
private val urldecoder =
(s:String) => java.net.URLDecoder.decode(s, "UTF-8")
/**
* 9.1.1 Normalize Request Parameters
* If two or more parameters share the same name, they are sorted by their value.
*/
private def sort(s:Seq[(String,String)]) = {
def sorter(x: (String,String), y: (String, String)): Boolean =
(x._1<y._1) || ((x._1 == y._1) && x._2<y._2)
util.Sorting.stableSort(s, sorter _)
}
object HTTPMethod extends Enumeration{
val GET = Value("GET")
val POST = Value("POST")
val HEAD = Value("HEAD")
val PUT = Value("PUT")
val DELETE = Value("DELETE")
def apply(s:String) =
elements.find(_.toString == s.toUpperCase) .
getOrElse (throw new RuntimeException("unkown method"))
}
private val b64encoder = Base64.encode _
// The following code is from JSch(http://www.jcraft.com/jsch/).
private object Base64{
val b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".getBytes
def encode(buf:Array[Byte]) = {
val tmp = new Array[Byte](buf.length*2)
var i:Int = 0
var j:Int = 0
var k:Int = 0
var foo = (buf.length/3)*3;
i=0; j=0;
while(j<foo){
k=(buf(j)>>>2)&0x3f
tmp(i)=b64(k); i += 1
k=(buf(j)&0x03)<<4|(buf(j+1)>>>4)&0x0f
tmp(i)=b64(k); i += 1
k=(buf(j+1)&0x0f)<<2|(buf(j+2)>>>6)&0x03
tmp(i)=b64(k); i += 1
k=buf(j+2)&0x3f;
tmp(i)=b64(k); i += 1
j += 3
}
foo=buf.length-foo;
if(foo==1){
k=(buf(j)>>>2)&0x3f;
tmp(i)=b64(k); i += 1
k=((buf(j)&0x03)<<4)&0x3f;
tmp(i)=b64(k); i += 1
tmp(i)='='; i += 1
tmp(i)='='; i += 1
}
else if(foo==2){
k=(buf(j)>>>2)&0x3f;
tmp(i)=b64(k); i += 1
k=(buf(j)&0x03)<<4|(buf(j+1)>>>4)&0x0f;
tmp(i)=b64(k); i += 1
k=((buf(j+1)&0x0f)<<2)&0x3f;
tmp(i)=b64(k); i += 1
tmp(i)='='; i += 1
}
val bar=new Array[Byte](i);
System.arraycopy(tmp, 0, bar, 0, i);
bar
}
}
}
/**
Copyright (c) 2010 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*/
import java.net._
import com.jcraft.oauth.Consumer
object Tweet{
val CONSUMER_KEY = XXX
val CONSUMER_SECRET = XXX
val ACCESS_TOKEN = XXX
val TOKEN_SECRET = XXX
def main(arg:Array[String]){
val tweet = java.net.URLEncoder.encode("Hello "+(new java.util.Date), "UTF-8")
val url = "http://api.twitter.com/1/statuses/update.xml"
val urlConn = new URL(url).openConnection.asInstanceOf[HttpURLConnection]
urlConn.setRequestMethod("POST")
urlConn.setDoOutput(true);
val consumer = new Consumer(CONSUMER_KEY, CONSUMER_SECRET)
consumer.sign(urlConn, "status="+tweet, ACCESS_TOKEN, TOKEN_SECRET)
val writer = new java.io.PrintWriter(urlConn.getOutputStream)
writer.print("status="+tweet)
writer.close()
println(urlConn.getResponseCode)
println(xml.XML.load(urlConn.getInputStream))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment