Skip to content

Commit

Permalink
added user service and serialization tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dhaeb committed Sep 1, 2014
1 parent 92488c3 commit 2c07be6
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 27 deletions.
Binary file modified doc/Schnittstelle.dia
Binary file not shown.
52 changes: 27 additions & 25 deletions src/main/scala/com/tboonx/github/brocounting/App.scala
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.tboonx.github.brocounting

import com.mongodb.casbah.commons.{MongoDBObjectBuilder, MongoDBObject}
import org.scalatra.ScalatraServlet
import javax.servlet.ServletContext
import org.scalatra.LifeCycle
import org.scalatra.CorsSupport
import com.mongodb.casbah.MongoClient
import com.mongodb.casbah.{Imports, MongoCollection, MongoDB, MongoClient}
import com.tboonx.github.brocounting.model._
import com.novus.salat._
import com.novus.salat.annotations._
import com.novus.salat.global._

// JSON-related libraries
Expand All @@ -16,29 +16,18 @@ import org.json4s.{DefaultFormats, Formats}
// JSON handling support from Scalatra
import org.scalatra.json._

/**
* @author ${user.name}
*/
object App {

def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)

def main(args : Array[String]) {
println( "Hello World!" )
println("concat arguments = " + foo(args))
}

}

class ScalaraRestfulApiDef extends ScalatraServlet with JacksonJsonSupport with CorsSupport {
// Sets up automatic case class to JSON output serialization, required by
// the JValueResult trait.
protected implicit val jsonFormats: Formats = DefaultFormats
val mongoClient = MongoClient("localhost", 27017)
val mongoHost = Option(System.getProperty("mongohost")) getOrElse "localhost"
val mongoPort : Int = Option(System.getProperty("mongoport")) getOrElse("27017") toInt
val mongoDbName = Option(System.getProperty("mongodb")) getOrElse "brocounting"
private val db: MongoDB = MongoClient(mongoHost, mongoPort).apply(mongoDbName)

options("/*") {
response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"))
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Origin", "*")
response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"))
}

Expand All @@ -53,20 +42,33 @@ class ScalaraRestfulApiDef extends ScalatraServlet with JacksonJsonSupport with
Hello to scalatra
</html>
}


put("/user/upsert"){
println(parsedBody)
val addableUser: User = parsedBody.extract[User]
val addableUserAsDbObject: Imports.DBObject = grater[User].asDBObject(addableUser)
db("user").update(MongoDBObject("_id" -> addableUser.name), addableUserAsDbObject, true)
}

delete("/user/delete") {
val deletableUser: User = parsedBody.extract[User]
val users = db("user")
val deletableUserAsMongoObject: Imports.DBObject = grater[User].asDBObject(deletableUser)
val deletableInDB: MongoCollection#T = users.findOne(deletableUserAsMongoObject).get
if(deletableUser.password == deletableInDB.get("password")){
users.remove(deletableUserAsMongoObject)
}
}

get("/hello_mongo") {
val db = mongoClient("brocounting_test")
val firstObject = db("user") findOne()
val firstObject = db("user") findOne()
firstObject.get
}

put("/session") {
val user = parsedBody.extract[User]
val db = mongoClient("brocounting_test")
db("user").insert(grater[User].asDBObject(user))
println("finshed inserting testuser: "+user.user_name);

Session("session123")
println("finshed inserting testuser: "+user.name)
}
}

Expand Down
20 changes: 18 additions & 2 deletions src/main/scala/com/tboonx/github/brocounting/model/Model.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
package com.tboonx.github.brocounting.model

import com.novus.salat.EnumStrategy
import com.novus.salat.annotations._
/**
* Created by dhaeb on 31.08.14.
*/

case class User(user_name: String, user_password: String)
case class Session(response: String)
object ModelConstants {
@EnumAs(strategy = EnumStrategy.BY_ID)
object AccountKind extends Enumeration {
type AccountKind = Value
val PAYPAL, CASH, GIRO_ACOUNT = Value
}
}

import ModelConstants.AccountKind._
import org.joda.time.DateTime

case class User(@Key("_id") name: String, password: String, tags : List[Tag], session : Option[Session])
case class Transaction(agent : String, account : String, amount : BigDecimal, date : DateTime, tags : List[Tag], note : String)
case class Account(@Key("_id") bic : String, name : String, balance : BigDecimal, kind : AccountKind, miscellaneous : Option[Map[String, String]])
case class Session(@Key("_id") hash: String)
case class Tag(@Key("_id") name : String, icon : Array[Byte], enabled : Boolean)
57 changes: 57 additions & 0 deletions src/test/scala/com/github/tboonx/TestModel.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.github.tboonx

import com.mongodb.casbah.Imports
import com.novus.salat._
import com.novus.salat.global._
import com.novus.salat.annotations._
import com.tboonx.github.brocounting.model._
import org.json4s._
import org.json4s.jackson.JsonMethods
import org.scalatest.FunSpec

/**
* Created by dhaeb on 31.08.14.
*/
class UserSpec extends FunSpec {

protected implicit val jsonFormats: Formats = DefaultFormats

describe("A user instance") {

val parsedInput: JValue = JsonMethods.parse("{\"name\":\"dab\",\"password\":\"123456\", \"session\" : {\"hash\" : \"asdf\"}}", true)

it("should be compilable to json without sepecifying an session hash"){
val fixtureWithoutHash = parsedInput.removeField( (value : JField) => {
"session".equals(value._1)
})
val user: User = Extraction.extract[User](fixtureWithoutHash)
assert("dab" === user.name)
assert("123456" === user.password)
assert(List() === user.tags)
assert(user.session.isInstanceOf[Option[Session]])
}

it("should be serializable to a mongo object without session and tags"){
val user : User = new User("dab", "123456", List(), Option[Session](null))
val expected = "{ \"_id\" : \"dab\" , \"password\" : \"123456\" , \"tags\" : [ ]}"
assert(expected === grater[User].asDBObject(user).toString)
}

it("should be compilable to json using scalatra-json") {
val user: User = Extraction.extract[User](parsedInput)
assert(user.name === "dab")
assert(user.password === "123456")
assert(user.tags === List())
assert(user.session.get === new Session("asdf"))
}

it("should be serializable to a mongo db object using salat"){
val user : User = new User("dan", "123456", List(new Tag("eat", Array(), true), new Tag("sleep", Array(), false), new Tag("code", Array(), false)), Option(new Session("myRandomlyGeneratedSessionHash")))
val userDbObject: Imports.DBObject = grater[User].asDBObject(user)
val expected = "{ \"_id\" : \"dan\" , \"password\" : \"123456\" , \"tags\" : [ { \"_id\" : \"eat\" , \"icon\" : <Binary Data> , \"enabled\" : true} , { \"_id\" : \"sleep\" , \"icon\" : <Binary Data> , \"enabled\" : false} , { \"_id\" : \"code\" , \"icon\" : <Binary Data> , \"enabled\" : false}] , \"session\" : { \"_id\" : \"myRandomlyGeneratedSessionHash\"}}"
assert(expected === userDbObject.toString)
}

}
}

0 comments on commit 2c07be6

Please sign in to comment.