Skip to content

Instantly share code, notes, and snippets.

@NicolaeNMV
Created March 12, 2014 17:48
Show Gist options
  • Save NicolaeNMV/9512269 to your computer and use it in GitHub Desktop.
Save NicolaeNMV/9512269 to your computer and use it in GitHub Desktop.
/**
* Cache a remote resource with WS and put it into cache with Playframework 2.2.0
*
* Here I'm doing the caching of google images, but you can easily adapt it to your needs
*/
package controllers
import play.api.cache.Cache
import play.api._
import play.api.mvc._
import play.api.libs.ws._
import play.api.Play.current
import scala.concurrent.duration.Duration
object Application extends Controller {
def getPhoto(google_id: String, size: String) = Action.async { implicit request =>
val url = "https://plus.google.com/s2/photos/profile/%s?sz=%s".format(google_id, size)
val defaultCacheDuration = Duration(12, "hours")
def OkImage(bytes: Array[Byte]) = {
Ok(bytes).withHeaders(
("Cache-Control", "public, max-age=%s, no-transform".format(defaultCacheDuration.toSeconds)),
("Content-Disposition", """inline;filename="""""),
("Content-Type", "image/jpeg"))
}
def getAndUpdateCache(): Future[SimpleResult] = {
WS.url(url).withFollowRedirects(true).get().flatMap { response =>
response.status match {
case 200 => {
val bytes: Array[Byte] = response.ahcResponse.getResponseBodyAsByteBuffer().array()
Cache.set(url, bytes, defaultCacheDuration)
Future.successful(OkImage(bytes))
}
case _ => {
NotFound
}
}
}
}
val bytesCache: Option[Array[Byte]] = Cache.getAs[Array[Byte]](url)
bytesCache match {
case None => getAndUpdateCache()
case Some(bytes) => Future.successful(OkImage(bytes))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment