Skip to content
This repository has been archived by the owner on Jan 27, 2019. It is now read-only.

Commit

Permalink
Sample updated to Play 2.1
Browse files Browse the repository at this point in the history
  • Loading branch information
leon committed Feb 8, 2013
1 parent 5e640f6 commit a91b08d
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 29 deletions.
2 changes: 1 addition & 1 deletion sample/app/Global.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import com.mongodb.casbah.Imports._
import play.api._
import libs.ws.WS
import models._
import se.radley.plugin.salat._

Expand All @@ -8,7 +9,6 @@ object Global extends GlobalSettings {
override def onStart(app: Application) {
if (User.count(DBObject(), Nil, Nil) == 0) {
Logger.info("Loading Testdata")

User.save(User(
username = "leon",
password = "1234",
Expand Down
26 changes: 26 additions & 0 deletions sample/app/controllers/Actions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package controllers

import models._
import play.api.mvc._
import play.api.libs.json._

object Actions extends Results with BodyParsers {

/**
* Simplifies handling incoming json by wrapping validation and returning BadRequest if it fails
* @param action the underlying action
* @tparam A a class that has an implicit Read available
* @return a response
*/
def JsonAction[A](action: A => Result)(implicit reader: Reads[A]): EssentialAction = {
Action(parse.json) { implicit request =>
request.body.validate[A].fold(
valid = { json =>
action(json)
},
invalid = (e => BadRequest(JsError.toFlatJson(e)).as("application/json"))
)
}
}
}

15 changes: 0 additions & 15 deletions sample/app/controllers/Application.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,9 @@ object Application extends Controller {
Ok(views.html.list(users))
}

def listByCountry(country: String) = Action {
val users = User.findByCountry(country)
Ok(views.html.list(users))
}

def view(id: ObjectId) = Action {
User.findOneById(id).map( user =>
Ok(views.html.user(user))
).getOrElse(NotFound)
}

def create(username: String) = Action {
val user = User(
username = username,
password = "1234"
)
User.save(user)
Ok(views.html.user(user))
}

}
43 changes: 43 additions & 0 deletions sample/app/controllers/api/Users.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package controllers.api

import play.api.mvc._
import play.api.libs.json._
import models._
import controllers.Actions._

import com.mongodb.casbah.WriteConcern
import se.radley.plugin.salat._
import se.radley.plugin.salat.Binders._
import mongoContext._

object Users extends Controller {

def index() = Action {
val users = User.findAll().toList
Ok(Json.toJson(users))
}

def create = JsonAction[User] { user =>
User.save(user, WriteConcern.Safe)
Ok(Json.toJson(user))
}

def view(id: ObjectId) = Action {
User.findOneById(id).map { user =>
Ok(Json.toJson(user))
} getOrElse {
NotFound
}
}

def update(id: ObjectId) = JsonAction[User] { requestUser =>
val user = requestUser.copy(id)
User.save(user, WriteConcern.Safe)
Ok(Json.toJson(user))
}

def delete(id: ObjectId) = Action {
User.removeById(id)
Ok("")
}
}
26 changes: 25 additions & 1 deletion sample/app/models/Address.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
package models

import com.mongodb.casbah.Imports._
import java.util.Date
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Address(
street: String,
zip: String,
country: String
)
)

object Address {
// Conversions
implicit val addressJsonWrite = new Writes[Address] {
def writes(a: Address): JsValue = {
Json.obj(
"street" -> a.street,
"zip" -> a.zip,
"country" -> a.country
)
}
}

implicit val addressJsonRead = (
(__ \ 'street).read[String] ~
(__ \ 'zip).read[String] ~
(__ \ 'country).read[String]
)(Address.apply _)
}
44 changes: 41 additions & 3 deletions sample/app/models/User.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import com.novus.salat._
import com.novus.salat.annotations._
import com.novus.salat.dao._
import com.mongodb.casbah.Imports._
import play.api.libs.json._
import play.api.libs.functional.syntax._

import se.radley.plugin.salat._
import se.radley.plugin.salat.Binders._
import mongoContext._

case class User(
Expand All @@ -16,13 +20,47 @@ case class User(
address: Option[Address] = None,
added: Date = new Date(),
updated: Option[Date] = None,
deleted: Option[Date] = None,
@Key("company_id")company: Option[ObjectId] = None
)

object User extends ModelCompanion[User, ObjectId] {
val dao = new SalatDAO[User, ObjectId](collection = mongoCollection("users")) {}
object User extends UserDAO with UserJson

trait UserDAO extends ModelCompanion[User, ObjectId] {
def collection = mongoCollection("users")
val dao = new SalatDAO[User, ObjectId](collection) {}

// Indexes
collection.ensureIndex(DBObject("username" -> 1), "user_email", unique = true)

// Queries
def findOneByUsername(username: String): Option[User] = dao.findOne(MongoDBObject("username" -> username))
def findByCountry(country: String) = dao.find(MongoDBObject("address.country" -> country))
def authenticate(username: String, password: String): Option[User] = findOne(DBObject("username" -> username, "password" -> password))
}

/**
* Trait used to convert to and from json
*/
trait UserJson {

implicit val userJsonWrite = new Writes[User] {
def writes(u: User): JsValue = {
Json.obj(
"id" -> u.id,
"username" -> u.username,
"address" -> u.address,
"added" -> u.added,
"updated" -> u.updated
)
}
}
implicit val userJsonRead = (
(__ \ 'id).read[ObjectId] ~
(__ \ 'username).read[String] ~
(__ \ 'password).read[String] ~
(__ \ 'address).readNullable[Address] ~
(__ \ 'added).read[Date] ~
(__ \ 'updated).readNullable[Date] ~
(__ \ 'company).readNullable[ObjectId]
)(User.apply _)
}
7 changes: 7 additions & 0 deletions sample/conf/api.routes
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

# User
GET /user controllers.api.Users.index()
POST /user controllers.api.Users.create()
GET /user/:id controllers.api.Users.view(id: ObjectId)
PUT /user/:id controllers.api.Users.update(id: ObjectId)
DELETE /user/:id controllers.api.Users.delete(id: ObjectId)
6 changes: 3 additions & 3 deletions sample/conf/routes
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
# This file defines all application routes (Higher priority routes first)
# ~~~~

-> /api api.Routes

# Home page
GET / controllers.Application.list
GET /by-country/:country controllers.Application.listByCountry(country)
GET /create/:username controllers.Application.create(username)
GET /view/:id controllers.Application.view(id: ObjectId)
GET /:id controllers.Application.view(id: ObjectId)

# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
9 changes: 5 additions & 4 deletions sample/project/Build.scala
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import sbt._
import Keys._
import PlayProject._
import play.Project._

object ApplicationBuild extends Build {

val appName = "sample"
val appVersion = "1.0"

val appDependencies = Seq(
"se.radley" %% "play-plugins-salat" % "1.1"
"se.radley" %% "play-plugins-salat" % "1.2"
)

val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
val main = play.Project(appName, appVersion, appDependencies).settings(
routesImport += "se.radley.plugin.salat.Binders._",
templatesImport += "org.bson.types.ObjectId"
templatesImport += "org.bson.types.ObjectId",
resolvers += Resolver.sonatypeRepo("snapshots")
)

}
2 changes: 1 addition & 1 deletion sample/project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version=0.11.3
sbt.version=0.12.2
2 changes: 1 addition & 1 deletion sample/project/plugins.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ resolvers ++= Seq(
)

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0.3")
addSbtPlugin("play" % "sbt-plugin" % "2.1.0")

0 comments on commit a91b08d

Please sign in to comment.