Skip to content

Instantly share code, notes, and snippets.

@kritzikratzi
Created January 3, 2011 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kritzikratzi/763533 to your computer and use it in GitHub Desktop.
Save kritzikratzi/763533 to your computer and use it in GitHub Desktop.
package org.sd.doodle.server.lib
import org.sd.doodle.server.model.DrawingModel
import net.liftweb.http.{Req, GetRequest, PostRequest,
LiftRules, JsonResponse, PlainTextResponse, XmlResponse}
import net.liftweb.util.Helpers
import net.liftweb.common._
import net.liftweb.http.js.JE._
import net.liftweb.mapper._
import net.liftweb._
import http._
import SHtml._
import S._
import Helpers._
import scala.xml._
object REST {
def dispatch: LiftRules.DispatchPF = {
// Req(url_pattern_list, suffix, request_type)
case Req("api" :: "ping" :: Nil, _, GetRequest) => () => Full(XmlResponse(<pong>pong</pong>))
case r@Req("api" :: "get" :: "latest" :: Nil, _, GetRequest) => () => Full(getLatest(r.param("howMany")))
case r@Req("api" :: "get" :: "since" :: Nil, _, GetRequest) => () => Full(getNew(r.param("lastId")))
case r@Req("api" :: "get" :: "drawing" :: Nil, _, GetRequest) => () => Full(getDrawing(r.param("id")))
case r@Req("api" :: "put" :: Nil, _, PostRequest) => () => Full(put(r.param("timestamp"), r.param( "username" ), r.param("content")))
}
def getDrawing( id: Box[String] ) = {
var x = DrawingModel.findAll( By( DrawingModel.id, id.open_!.toLong), MaxRows( 1 ) );
// Console.println( x.first.content.toString() )
var y:NodeSeq = if( x.size == 0 ) (<error />) else bind( "v", (
<response>
<id><v:id /></id>
<timestamp><v:timestamp /></timestamp>
<username><v:username/></username>
<content><v:content /></content>
</response>
), "id" -> x.first.id, "timestamp" -> x.first.timestamp, "content" -> x.first.content.toString(), "username" -> x.first.username.toString() )
XmlResponse( y.first )
}
def getLatest(howMany:Box[String]) = {
var max = if( howMany.isEmpty ) 10L else howMany.open_!.toLong
var x = DrawingModel.findAll( MaxRows( max ), OrderBy( DrawingModel.id, Descending ) )
var y = x.flatMap( dr => bind( "v", (<id><v:id /></id>), "id" -> dr.id ) )
XmlResponse( (<response>{y}</response>) )
}
def getNew(lastId: Box[String]) = {
var x = DrawingModel.findAll(
By_>( DrawingModel.id, lastId.open_!.toLong),
MaxRows( 30 ),
OrderBy( DrawingModel.id, Descending )
)
var y = x.flatMap( dr => bind( "v", (<id><v:id /></id>), "id" -> dr.id ) )
XmlResponse( (<response>{y}</response>) )
}
def put(timestamp: Box[String], username: Box[String], content: Box[String]) = {
val drawing = DrawingModel.create
drawing.timestamp.setFromAny( new java.util.Date().getTime )
drawing.username.setFromAny( username.open_! )
drawing.content.setFromAny( content.open_! )
drawing.save
XmlResponse( (<response>{drawing.id}</response>) )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment