Monday, August 6, 2012

Play 2 - Code Snippets & Link List (Playframework Scala)

Link List:

Tutorials:
Play 2.0: Akka, Rest, Json and dependencies
Play 2, Akka, Websockets, Backbone.js and Leaflet – just having fun, really
Play!ing (2.0) with Twitter Bootstrap, WebSockets, Akka and OpenLayers
Getting Started with Play 2, Scala, and Squeryl
Tutorial: Play Framework 2 with Scala, Anorm, JSON, CoffeeScript, jQuery & Heroku

Plugins:
Maven Plugin (Play 2)


Code Snippets:

jsonp support
// Controller Action
def jsonTest = Action { implicit request =>
   // create a json object
   val json = Json.toJson(Map("test" -> "hallo world"))
   // look for the callback parameter in the request 
   request.queryString.get("callback").flatMap(_.headOption) match {
      // return jsonp object 
      case Some(callback) => Ok(Jsonp(callback, json)) 
      //  objectreturn a json
      case None => Ok(json)
   }
}


akka actor usage with promise

Actor
case class Request()
case class Response()

object MyActor {
 
 implicit val timeout = Timeout(20 second)
 
 lazy val default = {
  val actor = Akka.system.actorOf(Props[MyActor])
  actor
 }
 
 def test() = {
  (default ? Request()).asPromise
 }
}

class MyActor extends Actor {

 def receive = {
  case Request => {
   sender ! Response 
  }
 }
 
}

Controller
object Application extends Controller {
 def test = Action { implicit request =>
  val promise = MyActor.test()
  Async {
   promise.map(promise => {
    promise match {
     case Response => Ok("Got Response from Actor")
    }
   })
   
  }
 }
}


18 comments: