天天看點

Spray(6)REST API Project - JSON Marshall and Test Class

Spray(6)REST API Project - JSON Marshall and Test Class

3. How to Write JSON Marshall Class

Enumeration class

package com.sillycat.easysprayrestserver.model

object UserType extends Enumeration {

type UserType = Value

valADMIN, CUSTOMER, SELLER = Value

}

object CartType extends Enumeration {

type CartType = Value

valDIRECT, CHENGDU = Value

}

Case Class

Here is the model class, which should be my POJO, case class in scala

package com.sillycat.easysprayrestserver.model

import org.joda.time.DateTime

caseclass Cart(id: Option[Long], cartName: String, cartType: CartType.Value, user: User, products: Seq[Product])

caseclass Product(id: Option[Long], productName: String, productDesn: String, createDate: DateTime, expirationDate: DateTime)

caseclass User(id: Option[Long], userName: String, age: Int, userType: UserType.Value, createDate: DateTime, expirationDate: DateTime)

Here is the implementation of JSON Marshall

package com.sillycat.easysprayrestserver.model

import spray.httpx.SprayJsonSupport

import spray.json.DefaultJsonProtocol

import spray.json.DeserializationException

import spray.json.JsNumber

import spray.json.JsObject

import spray.json.JsString

import spray.json.JsValue

import spray.json.RootJsonFormat

import org.joda.time.format.DateTimeFormat

import org.joda.time.DateTime

import spray.json.JsArray

import spray.json._

import DefaultJsonProtocol._

class UserJsonProtocol(currentId: Long) extends DefaultJsonProtocol {

privatevaldateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")

implicitobject UserJsonFormat extends RootJsonFormat[User] {

def write(user: User) = JsObject(

Map(

"userName" -> JsString(user.userName),

"age" -> JsNumber(user.age),

"userType" -> JsString(user.userType.toString()),

"createDate" -> JsString(dateTimeFormat.print(new DateTime(user.createDate))),

"expirationDate" -> JsString(dateTimeFormat.print(new DateTime(user.expirationDate)))

) ++

user.id.map( i => Map("id" -> JsNumber(i))).getOrElse(Map[String, JsValue]())

)

def read(jsUser: JsValue) = {

jsUser.asJsObject.getFields("id", "userName", "age", "userType", "createDate", "expirationDate") match {

case Seq(JsNumber(id), JsString(userName), JsNumber(age), JsString(userType), JsString(createDate), JsString(expirationDate)) =>

valcreateDateObject = dateTimeFormat.parseDateTime(createDate)

valexpirationDateObject = dateTimeFormat.parseDateTime(expirationDate)

new User(Some(id.longValue), userName, age.toInt, UserType.withName(userType), createDateObject, expirationDateObject)

case Seq(JsString(userName), JsNumber(age), JsString(userType), JsString(createDate), JsString(expirationDate)) =>

valcreateDateObject = dateTimeFormat.parseDateTime(createDate)

valexpirationDateObject = dateTimeFormat.parseDateTime(expirationDate)

new User( None, userName, age.toInt, UserType.withName(userType), createDateObject, expirationDateObject)

case _ => thrownew DeserializationException("User expected")

}

}

}

}

object ProductJsonProtocol extends DefaultJsonProtocol {

privatevaldateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")

implicitobject ProductJsonFormat extends RootJsonFormat[Product] {

def write(product: Product) = JsObject(

Map(

"productName" -> JsString(product.productName),

"productDesn" -> JsString(product.productDesn),

"createDate"-> JsString(dateTimeFormat.print(new DateTime(product.createDate))),

"expirationDate" -> JsString(dateTimeFormat.print(new DateTime(product.expirationDate)))

) ++

product.id.map( i => Map("id" -> JsNumber(i))).getOrElse(Map[String, JsValue]())

)

def read(jsProduct: JsValue) = {

jsProduct.asJsObject.getFields("id", "productName", "productDesn", "createDate", "expirationDate") match {

case Seq(JsNumber(id), JsString(productName), JsString(productDesn), JsString(createDate), JsString(expirationDate)) =>

valcreateDateObject = dateTimeFormat.parseDateTime(createDate)

valexpirationDateObject = dateTimeFormat.parseDateTime(expirationDate)

new Product(Some(id.longValue), productName, productDesn, createDateObject, expirationDateObject)

case Seq(JsString(productName), JsString(productDesn), JsString(createDate), JsString(expirationDate)) =>

valcreateDateObject = dateTimeFormat.parseDateTime(createDate)

valexpirationDateObject = dateTimeFormat.parseDateTime(expirationDate)

new Product(None, productName, productDesn, createDateObject, expirationDateObject)

case _ => thrownew DeserializationException("Product expected")

}

}

}

}

object CartJsonProtocol extends DefaultJsonProtocol {

implicitobject CartJsonFormat extends RootJsonFormat[Cart] {

implicitvaluserFormatter = (new UserJsonProtocol(1)).UserJsonFormat

implicitvalproductFormatter = ProductJsonProtocol.ProductJsonFormat

def write(cart: Cart) = JsObject(

Map(

"cartName" -> JsString(cart.cartName),

"cartType" -> JsString(cart.cartType.toString()),

"user" -> cart.user.toJson,

"products" -> cart.products.toJson

) ++

cart.id.map( i => Map("id" -> JsNumber(i))).getOrElse(Map[String, JsValue]())

)

def read(jsCart: JsValue) = {

valparams: Map[String, JsValue] = jsCart.asJsObject.fields

Cart(

params.get("id").map(_.convertTo[Int]),

params("cartName").convertTo[String],

CartType.withName(params("cartType").convertTo[String]),

params("user").convertTo[User],

params("products").convertTo[Seq[Product]]

)

}

}

}

4. How to Write Test

First of all, I put the package dependency in build.sbt.

"org.scalatest" % "scalatest_2.10" % "1.9.1" % "test",

"org.specs2" %% "specs2" % "1.13" % "test"

And here is a example for JSONMarchall class

package com.sillycat.easysprayrestserver.model

import org.scalatest.FlatSpec

import org.scalatest.matchers.ShouldMatchers

import spray.json.DefaultJsonProtocol

import spray.json.pimpAny

import spray.json.pimpString

class JSONMarshallSpec extends FlatSpec with ShouldMatchers with DefaultJsonProtocol {

import com.sillycat.easysprayrestserver.model.ProductJsonProtocol._

import com.sillycat.easysprayrestserver.model.CartJsonProtocol._

"Marshalling Product JSON" should "result in an Product Object" in {

valjsonProduct = """{

"id" : 1,

"productName" : "iphone 5",

"productDesn" : "A good mobile device.",

"createDate" : "2012-05-22 13:33",

"expirationDate" : "2012-05-22 14:33"

}"""

valproductAST = jsonProduct.asJson

info("ProductAST: " + productAST.asJsObject)

valproduct: Product = productAST.convertTo[Product]

info("Product Object: " + product.toJson)

assert(product.toJson === productAST)

}

"Marshalling User without ID JSON" should "result in an User Object without id" in {

valjsonUser = """{

"userName":"Carl",

"age": 31,

"userType": "ADMIN",

"createDate": "2012-05-21 12:34",

"expirationDate": "2013-05-12 12:34"

}"""

implicitvalformatter = (new UserJsonProtocol(1)).UserJsonFormat

valuserAST = jsonUser.asJson

info("UserAST: " + userAST.prettyPrint)

valuser: User = userAST.convertTo[User]

info("User Object: " + user.toJson)

assert(user.age === 31)

assert(user.id === None)

}

Run the test

>sbt test

sbt>test-only com.sillycat.easysprayrestserver.model.*

sbt>test-only com.sillycat.easysprayrestserver.model.JSONMarshallSpec

That is it. I works fine.

5. How to Work with Actor

come soon…

6. How to Work with Logback

come soon…

Tips

Error Message:

error while loading AbstractInstant

Solution:

Add some dependency to build.sbt file:

"joda-time" % "joda-time" % "2.2",

"org.joda" % "joda-convert" % "1.3.1"

Error Message:

sbt.ResolveException: download failed: com.chuusai#shapeless_2.10.0-RC1;1.2.3-SNAPSHOT!shapeless_2.10.0-RC1.jar

[warn] ==== sonatype snapshots: tried

[warn] https://oss.sonatype.org/content/repositories/snapshots/com/chuusai/shapeless_2.10.0-RC1/1.2.3-SNAPSHOT/shapeless_2.10.0-RC1-1.2.3-SNAPSHOT.jar

Solution:

>git clone https://github.com/milessabin/shapeless.git

>cd shapeless

>git branch -a

remotes/origin/shapeless-1.2.3

>git checkout shapeless-1.2.3

>sbt package

Even this project is not working.

I try to download this jar from google search result, but I can not find one.

At last I copy that from my colleague's computer and put it in this place>

/Users/carl/.ivy2/cache/com.chuusai/shapeless_2.10.0-RC1/jars/shapeless_2.10.0-RC1-1.2.3-SNAPSHOT.jar

Error Message:

Could not run test com.sillycat.easysprayrestserver.model.JSONMarshallSpec:

java.lang.NoClassDefFoundError: scala/math/ScalaNumericAnyConversions

Solution:

Add 2 dependencies in build.sbt

"org.scalatest" % "scalatest_2.10" % "1.9.1" % "test",

"org.specs2" %% "specs2" % "1.13" % "test"

References:

http://spray.io/documentation/spray-testkit/

http://etorreborre.github.io/specs2/guide/org.specs2.guide.Runners.html#Via+SBT