Created
May 9, 2014 07:26
-
-
Save Arneball/b89ad0ac7a1ae81b3099 to your computer and use it in GitHub Desktop.
Retrofit
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 arneball on 2014-05-08. | |
*/ | |
import java.util.{List => JList} | |
import retrofit.client.Response | |
import retrofit.http.{Path, GET} | |
import retrofit.{RetrofitError, Callback, RestAdapter} | |
import collection.JavaConversions._ | |
object RetroFit extends App { | |
implicit def fun2cb[T >: Null](pf: Either[RetrofitError, T] => Unit) = new Callback[T]{ | |
override def success(p1: T, p2: Response): Unit = pf(Right(p1)) | |
override def failure(p1: RetrofitError): Unit = pf(Left(p1)) | |
} | |
val ghService = new RestAdapter.Builder().setEndpoint("https://api.github.com").build().create(classOf[GithubService]) | |
println{ | |
val callback: Callback[JList[Repo]] = fun2cb{ | |
case Right(success) => | |
val scalaRepos = success.filter{ _.language.toLowerCase == "scala" }.mkString("\n") | |
println("Got scala repos " + scalaRepos) | |
case Left(RetroError(401, _)) => | |
throw new Exception("UnAuthorized") | |
case Left(RetroError(code, _)) => | |
throw new Exception("Got error code " + code) | |
} | |
ghService.listRepos("arneball", callback) | |
} | |
object RetroError { | |
def unapply(r: RetrofitError) = Some(r.getResponse.getStatus, r.getBody.toString) | |
} | |
} | |
trait GithubService { | |
@GET("/users/{user}/repos") | |
def listRepos(@Path("user") user: String, cb: Callback[JList[Repo]]) | |
} | |
case class Repo(name: String, git_url: String, language: String) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment