Created
April 23, 2012 18:49
-
-
Save eltimn/2473018 to your computer and use it in GitHub Desktop.
Save PayPayInfo in Lift-MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.xml.NodeSeq | |
import net.liftweb._ | |
import common._ | |
import json._ | |
import json.ext.{EnumSerializer, JsonBoxSerializer} | |
import mongodb.JObjectParser | |
import mongodb.record.BsonRecord | |
import mongodb.record.field.MongoFieldFlavor | |
import record.{Field, FieldHelpers, MandatoryTypedField} | |
import paypal.{PayPalInfo, PaypalTransactionStatus} | |
import util.Helpers.tryo | |
import com.mongodb.DBObject | |
abstract class PayPalInfoField[OwnerType <: BsonRecord[OwnerType]](rec: OwnerType) | |
extends Field[JObject, OwnerType] | |
with MandatoryTypedField[JObject] | |
with MongoFieldFlavor[JObject] | |
{ | |
implicit val formats = owner.meta.formats + new EnumSerializer(PaypalTransactionStatus) + new JsonBoxSerializer + FieldSerializer[PayPalInfo]() | |
def asJValue = value | |
def setFromJValue(jvalue: JValue) = setBox(Full(jvalue.asInstanceOf[JObject])) | |
def asXHtml = <div></div> | |
def defaultValue = JObject(Nil) | |
def setFromAny(in: Any): Box[JObject] = in match { | |
case jv: JObject => Full(set(jv)) | |
case Some(jv: JObject) => Full(set(jv)) | |
case Full(jv: JObject) => Full(set(jv)) | |
case seq: Seq[_] if !seq.isEmpty => seq.map(setFromAny).apply(0) | |
case (s: String) :: _ => setFromString(s) | |
case null => Full(set(null)) | |
case s: String => setFromString(s) | |
case None | Empty | Failure(_, _, _) => Full(set(null)) | |
case o => setFromString(o.toString) | |
} | |
// assume string is json | |
def setFromString(in: String): Box[JObject] = { | |
// use lift-json to parse string into a JObject | |
Full(set(JsonParser.parse(in).asInstanceOf[JObject])) | |
} | |
def toForm: Box[NodeSeq] = Empty | |
def owner = rec | |
/* | |
* Convert this field's value into a DBObject so it can be stored in Mongo. | |
*/ | |
def asDBObject: DBObject = JObjectParser.parse(value) | |
// set this field's value using a DBObject returned from Mongo. | |
def setFromDBObject(dbo: DBObject): Box[JObject] = | |
setFromJValue(JObjectParser.serialize(dbo).asInstanceOf[JObject]) | |
def ppiAsJValue(ppi: PayPalInfo): Box[JObject] = tryo((Extraction.decompose(ppi) transform { | |
case JField("r", x) => JNothing | |
case JField("bitmap$init$0", x) => JNothing | |
case JField("bitmap$init$1", x) => JNothing | |
case JField("bitmap$init$2", x) => JNothing | |
}).asInstanceOf[JObject]) | |
def setFromPpi(ppi: PayPalInfo): Box[JObject] = setBox(ppiAsJValue(ppi)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment