本文整理汇总了Scala中reactivemongo.bson.BSONDocumentReader类的典型用法代码示例。如果您正苦于以下问题:Scala BSONDocumentReader类的具体用法?Scala BSONDocumentReader怎么用?Scala BSONDocumentReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BSONDocumentReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: User
//设置package包名称以及导入依赖的类
package models
import akka.actor.FSM.->
import play.api.data.validation.Constraints._
import play.api.data.format.Formats._
import reactivemongo.bson.{BSONDocumentReader, BSONDocument, BSONDocumentWriter, BSONObjectID}
import play.api.data.{Form, Mapping}
import play.api.data.Forms._
import reactivemongo.bson._
case class User(id:Option[BSONObjectID], user:String,password:String)
object User{
val fldId = "_id"
val fldName = "user"
val fldPassword = "password"
implicit object UserWriter extends BSONDocumentWriter[User]{
def write(user:User):BSONDocument = BSONDocument(
fldId -> user.id.getOrElse(BSONObjectID.generate),
fldName -> user.user,
fldPassword -> user.password
)
}
implicit object UserReader extends BSONDocumentReader[User]{
def read(doc:BSONDocument):User = User(
doc.getAs[BSONObjectID](fldId),
doc.getAs[String](fldName).getOrElse(""),
doc.getAs[String](fldPassword).getOrElse("")
)
}
val form = Form(
mapping(
fldId -> optional(of[String] verifying pattern(
"""[a-fA-F0-9]{24}""".r,
"constraint.objectId",
"error.objectId")),
fldName -> nonEmptyText,
fldPassword -> nonEmptyText){ (id,user,password) =>
User(
id.map(BSONObjectID(_)) ,user,password
)
}{user => Some(user.id.map(_.stringify), user.user, user.password)}
)
}
开发者ID:nabirdinani,项目名称:MySurvey,代码行数:48,代码来源:User.scala
示例2: ReactivemongoProvider
//设置package包名称以及导入依赖的类
package com.evojam.reactivemongo
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.MongoDriver
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter}
import com.evojam.Collection
object ReactivemongoProvider {
def apply[T](dbName: String, collectionName: String)(implicit reader: BSONDocumentReader[T], writer: BSONDocumentWriter[T]): Collection[T] = {
val driver = new MongoDriver
val connection = driver.connection(Seq("localhost"))
val db = connection(dbName)
val collection = db(collectionName)
new ReactivemongoCollection[T](driver, collection, reader, writer)
}
def apply[T](implicit r: BSONDocumentReader[T], w: BSONDocumentWriter[T]): Collection[T] = apply[T]("test", "mongo-driver-benchmarks")
}
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:21,代码来源:ReactivemongoProvider.scala
示例3: StringMapFormatter
//设置package包名称以及导入依赖的类
package com.evojam.documents
import collection.JavaConversions._
import org.bson.Document
import reactivemongo.bson.{BSONString, BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
object StringMapFormatter {
implicit object Handler extends BSONDocumentReader[Map[String, String]] with BSONDocumentWriter[Map[String, String]] {
override def read(bson: BSONDocument): Map[String, String] =
bson.elements.map({case (key, value) => (key, value.asInstanceOf[BSONString].as[String])}).toMap
override def write(t: Map[String, String]): BSONDocument =
BSONDocument(t.toStream.map({case (k,v) => (k, BSONString(v))}))
}
implicit object javaFmt extends DocumentFormat[Map[String, String]] {
override def writes(a: Map[String, String]) = {
val doc = new Document()
a foreach {
case (k, v) => doc.append(k, v)
}
doc
}
override def reads(doc: Document): Map[String, String] =
doc.keySet().map(key => (key, doc.getString(key))).toMap
}
}
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:32,代码来源:StringMapFormatter.scala
示例4: NestedDoc
//设置package包名称以及导入依赖的类
package com.evojam.documents
import org.bson.Document
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
case class NestedDoc(name: String, _id: String, left: Option[NestedDoc], right: Option[NestedDoc])
object NestedDoc {
implicit object NestedDocHandler extends BSONDocumentReader[NestedDoc] with BSONDocumentWriter[NestedDoc]{
override def read(bson: BSONDocument): NestedDoc = {
val left = bson.get("left").map(t => read(t.asInstanceOf[BSONDocument]))
val right = bson.get("right").map(t => read(t.asInstanceOf[BSONDocument]))
NestedDoc(bson.getAs[String]("name").get, bson.getAs[String]("_id").get, left, right)
}
override def write(t: NestedDoc): BSONDocument = {
BSONDocument("_id" -> t._id, "name" -> t.name)
.add("left" -> t.left.map(write))
.add("right" -> t.right.map(write))
}
}
implicit val javaFormat = new DocumentFormat[NestedDoc] {
override def writes(a: NestedDoc): Document = {
val doc = new Document("name", a.name)
a.left.foreach(t => doc.append("left", writes(t)))
a.right.foreach(t => doc.append("right", writes(t)))
doc.append("_id", a._id)
}
override def reads(doc: Document): NestedDoc = {
val left = Option(doc.get[Document]("left", classOf[Document])).map(reads)
val right = Option(doc.get[Document]("right", classOf[Document])).map(reads)
NestedDoc(doc.getString("name"), doc.getString("_id"), left, right)
}
}
}
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:40,代码来源:NestedDoc.scala
示例5: findAll
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BooksFound}
import com.jjabuk.bookstore.persistence.MongoDb
import org.slf4j.LoggerFactory
import reactivemongo.api.ReadPreference
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONObjectID}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}
trait BookQueries {
def findAll(implicit ec: ExecutionContext): Future[BooksFound]
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]]
}
object MongoBookQueries extends BookQueries with MongoDb {
def logger = LoggerFactory.getLogger(this.getClass)
def books: Future[BSONCollection] = database map (_.collection("books"))
implicit def bookReader = new BSONDocumentReader[Book] {
def read(doc: BSONDocument): Book =
Book(
uuid = doc.getAs[BSONObjectID]("_id").get.stringify,
isbn = doc.getAs[String]("isbn").get,
title = doc.getAs[String]("title").get,
review = doc.getAs[String]("review"),
publisher = doc.getAs[String]("publisher")
)
}
def findAll(implicit ec: ExecutionContext): Future[BooksFound] = {
logger.debug(s"Find all books")
books flatMap {
_.find(BSONDocument()).cursor[Book](ReadPreference.Primary).collect[List]()
} map (books => BooksFound(books))
}
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]] = {
logger.debug(s"Find a book by uuid=$uuid")
val selector = BSONDocument("_id" -> BSONObjectID.parse(uuid).get)
books
.flatMap(_.find(selector).one[Book])
.map {
case Some(book) => Some(BooksFound(List(book)))
case _ => Option.empty[BooksFound]
}
}
}
开发者ID:jjabuk,项目名称:bookstore,代码行数:59,代码来源:MongoBookQueries.scala
示例6: findOneOrCreate
//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
package object mongo {
def findOneOrCreate(collection: BSONCollection)
(userQuery: BSONDocument, getNewDoc: => Future[MongoUser]): Future[MongoUser] = {
implicit def mongoEntityWriter: BSONDocumentWriter[MongoEntity] = Macros.writer[MongoEntity]
implicit def mongoThoughtWriter: BSONDocumentWriter[MongoThought] = Macros.writer[MongoThought]
implicit def mongoMessageWriter: BSONDocumentWriter[MongoMessage] = Macros.writer[MongoMessage]
implicit def mongoUserWriter: BSONDocumentWriter[MongoUser] = Macros.writer[MongoUser]
implicit def mongoEntityReader: BSONDocumentReader[MongoEntity] = Macros.reader[MongoEntity]
implicit def mongoThoughtReader: BSONDocumentReader[MongoThought] = Macros.reader[MongoThought]
implicit def mongoMessageReader: BSONDocumentReader[MongoMessage] = Macros.reader[MongoMessage]
implicit def mongoUserReader: BSONDocumentReader[MongoUser] = Macros.reader[MongoUser]
val p = Promise[MongoUser]()
collection.find(userQuery).one[MongoUser].onComplete {
case Success(docOpt) =>
if (docOpt.isDefined) {
p.complete(Try(docOpt.get))
} else {
getNewDoc.onComplete {
case Success(newDocOpt) =>
collection.insert(newDocOpt).onComplete { r =>
collection.find(userQuery).one[MongoUser]
.onComplete {
case Success(docOpt2) =>
val mongoUser = docOpt2.get
p.complete(Try(mongoUser))
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
p.future
}
}
开发者ID:aluxian,项目名称:SusuCatBot,代码行数:50,代码来源:package.scala
示例7: Order
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Order(orderID: Int, accountId: String, date: String, time: String, orderStatus: String, paymentMethod: String, orderLines: Array[OrderLine], totalPrice: Double, rating: Int) {}
object Order {
implicit object OrderReader extends BSONDocumentReader[Order] {
def read(doc: BSONDocument): Order =
Order(
doc.getAs[Int]("orderID").get,
doc.getAs[String]("accountID").get,
doc.getAs[String]("date").get,
doc.getAs[String]("time").get,
doc.getAs[String]("orderStatus").get,
doc.getAs[String]("paymentMethod").get,
doc.getAs[Array[OrderLine]]("orderLines").get,
doc.getAs[Double]("totalPrice").get,
doc.getAs[Int]("rating").get
)
}
}
开发者ID:Smudgey,项目名称:qa_play_ims,代码行数:25,代码来源:Order.scala
示例8: Product
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Product(itemID: String, product: String, images: Array[String], category: Array[String], description: String, var stock: Int, price: Double) {
def hasXAvailable(x: Int): Boolean = {
this.stock >= x
}
// URL: String
def decrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock = stock - quantity
}
def incrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock += quantity
}
}
object Product {
implicit object productReader extends BSONDocumentReader[Product] {
def read(doc: BSONDocument): Product =
Product(
doc.getAs[String]("itemID").get,
doc.getAs[String]("Product").get,
doc.getAs[Array[String]]("images").get,
doc.getAs[Array[String]]("Category").get,
doc.getAs[String]("Description").get,
doc.getAs[Int]("Stock").get,
doc.getAs[Double]("price").get
)
}
}
开发者ID:Smudgey,项目名称:qa_play_ims,代码行数:43,代码来源:Product.scala
示例9: MongoUserRepository
//设置package包名称以及导入依赖的类
package com.example.graphql.service
import reactivemongo.bson.BSONDocumentReader
import reactivemongo.bson.BSONDocumentWriter
import reactivemongo.bson.Macros
import reactivemongo.api.Cursor
import reactivemongo.api.MongoConnection
import reactivemongo.api.MongoDriver
import reactivemongo.api.DefaultDB
import com.example.graphql.model.User
import com.example.graphql.model.Role
import com.example.graphql.model.Address
import java.time.LocalDateTime
import java.util.Locale
import scala.concurrent.Future
class MongoUserRepository extends Repository {
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.bson._
val mongoUri = "mongodb://localhost:27017/mydb?authMode=scram-sha1"
val connection = MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_))
val futureConnection = Future.fromTry(connection)
def db: Future[DefaultDB] = futureConnection.flatMap(_.database("mydb"))
def collection = db.map(_.collection("users"))
implicit def addressWriter: BSONDocumentWriter[Address] = Macros.writer[Address]
implicit def addressReader: BSONDocumentReader[Address] = Macros.reader[Address]
implicit def userWriter: BSONDocumentWriter[User] = Macros.writer[User]
implicit def userReader: BSONDocumentReader[User] = Macros.reader[User]
def findAll(fields: Seq[String]): Future[Seq[User]] = collection.flatMap(
_.find(document())
.projection(fields.foldLeft(document())((doc, field) => doc.merge(field -> BSONInteger(1))))
.cursor[User]()
.collect(Int.MaxValue, Cursor.FailOnError[Seq[User]]())
)
def findById(id: Long): Future[Option[User]] = collection.flatMap(
_.find(document("id" -> BSONLong(id))).one[User]
)
def addUser(email: String, firstName: Option[String], lastName: Option[String], roles: Seq[Role.Value]): Future[User] = {
val user = User(BSONObjectID.generate().time, email, Some(LocalDateTime.now()), firstName, lastName, Some(roles), Some(false), None)
collection.flatMap(_.insert(user).map(_ => user))
}
def activateById(id: Long): Future[Option[User]] = collection.flatMap(
_.findAndUpdate(document("id" -> BSONLong(id)), document("$set" -> document("active" -> BSONBoolean(true))), fetchNewObject = true)
.map(_.result[User])
)
}
开发者ID:reta,项目名称:sangria-akka-http-graphql,代码行数:57,代码来源:MongoUserRepository.scala
示例10: GalleryCommentEntity
//设置package包名称以及导入依赖的类
package com.rozilo.ussemble.models.db
import java.util.{Calendar, Date}
import com.rozilo.ussemble.models.api.GalleryCommentProtocol.GalleryComment
import io.circe.generic.JsonCodec
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, BSONObjectID, BSONString}
import io.circe._
import io.circe.generic.semiauto._
case class GalleryCommentEntity(id: BSONObjectID = BSONObjectID.generate,
body: String,
activity_id: BSONObjectID,
sender_id: BSONObjectID,
var read_by: Option[List[String]] = Some(List()),
createdAt: Option[Date] = Some(Calendar.getInstance.getTime),
updatedAt: Option[Date] = Some(Calendar.getInstance.getTime))
object GalleryCommentEntity {
implicit def toGalleryCommentEntity(comment: GalleryComment): GalleryCommentEntity = GalleryCommentEntity(body = comment.body,
activity_id = BSONObjectID.parse(comment.activity_id).get, sender_id = BSONObjectID.parse(comment.sender_id).get)
import io.circe._
import io.circe.syntax._
import io.circe.generic.auto._
// implicit val jsonEncoder = Encoder[GalleryCommentEntity]
// implicit val jsonDecoder = Decoder[GalleryCommentEntity]
implicit object GalleryCommentBSONReader extends BSONDocumentReader[GalleryCommentEntity] {
def read(doc: BSONDocument): GalleryCommentEntity =
GalleryCommentEntity(
id = doc.getAs[BSONObjectID]("_id").get,
body = doc.getAs[String]("body").get,
activity_id = doc.getAs[BSONObjectID]("activity_id").get,
sender_id = doc.getAs[BSONObjectID]("sender_id").get,
read_by = doc.getAs[List[String]]("read_by")
)
}
implicit object GalleryCommentBSONWriter extends BSONDocumentWriter[GalleryCommentEntity] {
def write(commentEntity: GalleryCommentEntity): BSONDocument =
BSONDocument(
"_id" -> commentEntity.id,
"body" -> BSONString(commentEntity.body),
"activity_id" -> commentEntity.activity_id,
"sender_id" -> commentEntity.sender_id,
"read_by" -> commentEntity.read_by,
"created_at" -> commentEntity.createdAt,
"updated_at" -> commentEntity.updatedAt
)
}
}
开发者ID:Rozilo,项目名称:uss-gallery,代码行数:59,代码来源:GalleryCommentEntity.scala
示例11: isDefined
//设置package包名称以及导入依赖的类
package models
import models.Game._
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import scala.collection.JavaConverters._
sealed trait Game {
def isDefined: Boolean
def id: GameId
def iconUrl: String
def logoUrl: String
//def cypher = s""":Game {id: "${id}", name: "$toString", imageUrl: "$imageUrl", isDefined: "$isDefined"}"""
}
case class SomeGame(id: GameId, name: String, iconUrl: String, logoUrl: String) extends Game {
override def toString: String = name
override def isDefined: Boolean = true
}
case object NoGame extends Game {
override def id = ""
override def toString: String = "Nothing"
override def isDefined: Boolean = false
override def iconUrl: String = defaultImageUrl
override def logoUrl = defaultImageUrl
}
object Game {
implicit def ordering: Ordering[Game] = Ordering.by(g => (g.isDefined, g.toString))
def apply(id: GameId, name: String, imageUrl: String, logoUrl: String): Game = {
if (id == null || id == "" || name == null || name == "") { NoGame }
else if (imageUrl == null || imageUrl.isEmpty || logoUrl == null || logoUrl.isEmpty) {
SomeGame(id, name, defaultImageUrl, defaultImageUrl)
} else { SomeGame(id, name, imageUrl, logoUrl) }
}
def fromApiModel(g: com.lukaspradel.steamapi.data.json.ownedgames.Game): Game = {
g.getAdditionalProperties.asScala.foreach(t => println(s"additionalprop: $t"))
apply(g.getAppid.toString, g.getName, g.getImgIconUrl, g.getImgLogoUrl)
}
val defaultImageUrl = "placeholder.png"
type GameId = String
implicit object Writer extends BSONDocumentWriter[Game] {
def write(game: Game): BSONDocument = BSONDocument(
"isDefined" -> game.isDefined,
"id" -> game.id,
"name" -> game.toString,
"iconUrl" -> game.iconUrl,
"logoUrl" -> game.logoUrl
)
}
implicit object Reader extends BSONDocumentReader[Game] {
override def read(bson: BSONDocument): Game = apply(
bson.getAs[String]("id").get,
bson.getAs[String]("name").get,
bson.getAs[String]("iconUrl").get,
bson.getAs[String]("logoUrl").get
)
}
}
开发者ID:hnrklssn,项目名称:game-check-match,代码行数:61,代码来源:Game.scala
示例12: id
//设置package包名称以及导入依赖的类
package models
import com.mohiva.play.silhouette.api.Identity
import com.mohiva.play.silhouette.impl.providers.SocialProfile
import reactivemongo.bson.{ BSONDocument, BSONDocumentReader, BSONDocumentWriter, BSONNumberLike }
trait ServiceProfile extends Identity with SocialProfile {
type Self <: ServiceProfile
import models.ServiceProfile._
def id: ServiceUserId
def service: String
def visible: Boolean
def displayName: String
def avatarUrl: String
def profileState: ProfileState
def isInGame: Boolean
def currentlyPlaying: Game
def isRegistered: Boolean
def register: Self
override def equals(obj: scala.Any): Boolean = obj match {
case s: ServiceProfile => s.id == id && s.service == service
case _ => false
}
}
object ServiceProfile {
implicit def ordering: Ordering[ServiceProfile] = Ordering.by { p: ServiceProfile => { (p.visible, p.currentlyPlaying, p.profileState, p.displayName) } }
implicit def ordering2: Ordering[ProfileState] = Ordering.by(s => s.priority)
type ServiceUserId = String
sealed trait ProfileState {
def priority: Int
}
case object Online extends ProfileState { override def priority = 4 }
case object Offline extends ProfileState { override def priority = 20 }
case object Busy extends ProfileState { override def priority = 8 }
case object Away extends ProfileState { override def priority = 6 }
case object Snooze extends ProfileState { override def priority = 10 }
case object LookingToTrade extends ProfileState { override def priority = 2 }
case object LookingToPlay extends ProfileState { override def priority = 0 }
implicit object ProfileStateWriter extends BSONDocumentWriter[ProfileState] {
def write(state: ProfileState): BSONDocument = BSONDocument("code" -> stateCode(state))
}
implicit object ProfileStateReader extends BSONDocumentReader[ProfileState] {
override def read(bson: BSONDocument): ProfileState = profileStateFactory(bson.getAs[BSONNumberLike]("code").get.toInt)
}
def stateCode(state: ProfileState): Int = state match {
case Offline => 0
case Online => 1
case Busy => 2
case Away => 3
case Snooze => 4
case LookingToTrade => 5
case LookingToPlay => 6
}
}
开发者ID:hnrklssn,项目名称:game-check-match,代码行数:59,代码来源:ServiceProfile.scala
示例13: service
//设置package包名称以及导入依赖的类
package models
import com.lukaspradel.steamapi.data.json.playersummaries.Player
import models.ServiceProfile.ProfileState
import reactivemongo.bson.{ BSONDocument, BSONDocumentReader, BSONDocumentWriter }
trait SteamProfile extends ServiceProfile {
override type Self = SteamProfile
def service: String = "Steam"
}
trait SteamProfileFactory {
def apply(profileData: Player): SteamProfile
}
object SteamProfile {
implicit object Writer extends BSONDocumentWriter[SteamProfile] {
def write(profile: SteamProfile): BSONDocument = BSONDocument(
"id" -> profile.id,
"service" -> profile.service,
"visible" -> profile.visible,
"displayName" -> profile.displayName,
"avatarUrl" -> profile.avatarUrl,
"profileState" -> profile.profileState,
"isInGame" -> profile.isInGame,
"currentlyPlaying" -> profile.currentlyPlaying
)
}
implicit object Reader extends BSONDocumentReader[SteamProfile] {
def read(doc: BSONDocument): SteamProfile = {
println("asdfADSFGAA SDFAG")
SteamProfileImpl(
doc.getAs[String]("id").get,
doc.getAs[Boolean]("visible").get,
doc.getAs[String]("displayName").get,
doc.getAs[String]("avatarUrl").get,
doc.getAs[ProfileState]("profileState").get,
doc.getAs[Game]("currentlyPlaying").get,
doc.getAs[Boolean]("isRegistered").get
)
}
}
}
开发者ID:hnrklssn,项目名称:game-check-match,代码行数:46,代码来源:SteamProfile.scala
示例14: MongoRepository
//设置package包名称以及导入依赖的类
package io.shedin.crud.mongo
import io.shedin.crud.lib.CrudRepository
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{DefaultDB, MongoConnection, MongoConnectionOptions, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, document}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
// TODO maybe should just mix in AsyncCrudOperations[T] instead of CrudRepository[T]
abstract class MongoRepository[T]
(databaseName: String)
(implicit writer: BSONDocumentWriter[T], reader: BSONDocumentReader[T], manifest: Manifest[T])
extends CrudRepository[T] {
private lazy val mongoUri = s"mongodb://localhost:27017/$databaseName?authMode=scram-sha1"
private lazy val eventualMongoConnection = Future.fromTry(MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_)))
private def mongoDatabase: Future[DefaultDB] = eventualMongoConnection.flatMap(_.database(databaseName))
private def mongoCollection = mongoDatabase.map(_.collection[BSONCollection](simpleName(manifest)))
override def create(resource: T): Future[T] =
mongoCollection.flatMap { bsonCollection =>
bsonCollection.insert(resource).map { writeResult =>
if (writeResult.n == 1) resource
else throw new RuntimeException(s"failed to persist resource [$resource]")
}
}
override def read(resourceId: String): Future[Option[T]] = {
mongoCollection.flatMap(_.find(document("id" -> resourceId)).cursor[T]().collect[List]()) map (_.headOption)
}
override def update(resourceId: String, resource: T): Future[Option[T]] = {
mongoCollection.flatMap(_.update(document("id" -> resourceId), resource)) map { updateWriteResult =>
if (updateWriteResult.n == 0) None
else if (updateWriteResult.n == 1) Some(resource)
else throw new RuntimeException("more than one doc updated") // TODO revisit this
}
}
override def update(resourceId: String, updatePayload: String): Future[Option[AnyRef]] = throw new UnsupportedOperationException
override def delete(resourceId: String): Future[Boolean] =
mongoCollection.flatMap(_.remove(document("id" -> resourceId))) map (_.n > 0)
private def simpleName[T](manifest: Manifest[T]): String =
manifest.runtimeClass.getSimpleName.toLowerCase
}
开发者ID:edinhodzic,项目名称:shedin-crud-mongo,代码行数:53,代码来源:MongoRepository.scala
示例15: MongoBSONSearchableRepositorySpec
//设置package包名称以及导入依赖的类
package com.clemble.query
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocumentWriter, BSONDocumentReader, BSONDocument}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
class MongoBSONSearchableRepositorySpec extends SearchableRepositorySpec {
implicit val format: BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] = new BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] {
override def write(t: Employee): BSONDocument = BSONDocument(
"name" -> t.name,
"salary" -> t.salary
)
override def read(bson: BSONDocument): Employee =
Employee(
bson.getAs[String]("name").get,
bson.getAs[Int]("salary").get
)
}
override val repo: MongoBSONSearchableRepository[Employee] with ProjectionSupport = new MongoBSONSearchableRepository[Employee] with MongoBSONProjectionSupport[Employee] {
override val collection: BSONCollection = {
SpecificationConstants.db.collection[BSONCollection]("employee_bson")
}
override val queryTranslator: QueryTranslator[BSONDocument, BSONDocument] = new MongoBSONQueryTranslator()
override implicit val f: BSONDocumentReader[Employee] = format
}
override def save(employee: Employee): Boolean = {
val fSave = repo.collection.update(BSONDocument("_id" -> employee.name), format.write(employee), upsert = true)
Await.result(fSave, 1 minute).errmsg.isEmpty
}
override def remove(employee: Employee): Boolean = {
val fRemove = repo.collection.remove(BSONDocument("name" -> employee.name))
Await.result(fRemove, 1 minute).errmsg.isEmpty
}
}
开发者ID:clemble,项目名称:scala-query-dsl,代码行数:49,代码来源:MongoBSONSearchableRepositorySpec.scala
示例16: MongoBSONQueryFactorySpecification
//设置package包名称以及导入依赖的类
package com.clemble.query
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentWriter, BSONDocumentReader}
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
class MongoBSONQueryFactorySpecification extends QueryFactorySpecification {
implicit val format: BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] = new BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] {
override def write(t: Employee): BSONDocument = BSONDocument(
"name" -> t.name,
"salary" -> t.salary
)
override def read(bson: BSONDocument): Employee =
Employee(
bson.getAs[String]("name").get,
bson.getAs[Int]("salary").get
)
}
private val collection: BSONCollection = {
SpecificationConstants.db.collection[BSONCollection]("employee_bson_qf")
}
override val queryFactory: QueryFactory[Employee] = new MongoBSONQueryFactory(collection)
override def save(employee: Employee): Boolean = {
val fSave = collection.update(BSONDocument("_id" -> employee.name), format.write(employee), upsert = true)
Await.result(fSave, 1 minute).errmsg.isEmpty
}
override def remove(employee: Employee): Boolean = {
val fRemove = collection.remove(BSONDocument("name" -> employee.name))
Await.result(fRemove, 1 minute).errmsg.isEmpty
}
}
开发者ID:clemble,项目名称:scala-query-dsl,代码行数:43,代码来源:MongoBSONQueryFactorySpecification.scala
示例17: CurriDocument
//设置package包名称以及导入依赖的类
package curri.docs.domain
import com.fasterxml.jackson.annotation.JsonProperty
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
case class CurriDocument(
@JsonProperty("title") title: String,
@JsonProperty("kind") kind: String,
@JsonProperty("body") body: String,
@JsonProperty("ownerUser") ownerUser: Option[String],
@JsonProperty("ownerGroup") ownerGroup: Option[String]) {
def withBody(newBody: String) = CurriDocument(title, kind, newBody, ownerUser, ownerGroup)
}
object CurriDocumentWriter extends BSONDocumentWriter[CurriDocument] {
def write(curriDoc: CurriDocument): BSONDocument = BSONDocument(
"title" -> curriDoc.title,
"kind" -> curriDoc.kind,
"body" -> curriDoc.body,
"ownerUser" -> curriDoc.ownerUser,
"ownerGroup" -> curriDoc.ownerGroup)
}
object CurriDocumentReader extends BSONDocumentReader[CurriDocument] {
def read(doc: BSONDocument): CurriDocument = {
CurriDocument(
doc.getAs[String]("title").get,
doc.getAs[String]("kind").get,
doc.getAs[String]("body").get,
doc.getAs[String]("ownerUser"),
doc.getAs[String]("ownerGroup"))
}
}
开发者ID:kolov,项目名称:curri-docs-service,代码行数:38,代码来源:CurriDocument.scala
示例18: EmailDTO
//设置package包名称以及导入依赖的类
package model.infractructure
import java.util.Date
import model.domain.mailbox.EmailAdded
import model.domain.{Email, EmailId}
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
package object mongo {
final case class EmailDTO(id: EmailId, sender: String, sentTime: Date, receivedTime: Date, content: String, label: String) {
def toDomain: Email = Email(id, sender, sentTime, receivedTime, content, label)
}
object EmailDTO {
def apply(emailAdded: EmailAdded): EmailDTO = new EmailDTO(
emailAdded.id,
emailAdded.emailMetadata.sender,
emailAdded.emailMetadata.sentTime,
emailAdded.emailMetadata.receivedTime,
emailAdded.content,
emailAdded.label
)
}
final case class EmailUpdate(id: EmailId, content: String, label: String)
implicit object EmailReaderWriter extends BSONDocumentReader[EmailDTO] with BSONDocumentWriter[EmailDTO] {
override def read(bson: BSONDocument): EmailDTO = EmailDTO(
EmailId(bson.getAs[String]("folderId").get, bson.getAs[String]("messageId").get),
bson.getAs[String]("sender").get,
bson.getAs[Date]("sentTime").get,
bson.getAs[Date]("receivedTime").get,
bson.getAs[String]("content").get,
bson.getAs[String]("label").get
)
override def write(t: EmailDTO): BSONDocument = BSONDocument(
"messageId" -> t.id.messageId,
"folderId" -> t.id.folderId,
"sender" -> t.sender,
"sentTime" -> t.sentTime,
"receivedTime" -> t.receivedTime,
"content" -> t.content,
"label" -> t.label
)
}
}
开发者ID:bartosz822,项目名称:BITspam,代码行数:56,代码来源:mongo.scala
示例19: Spots
//设置package包名称以及导入依赖的类
package model
import reactivemongo.bson._
import reactivemongo.bson.{ BSONDocument, BSONDocumentReader }
case class Spots(id: String, name: String, lat: Double, lon: Double, created: Long, total_valorations: Int, quiet: Int,
quiet_perc: Double, good_coffee: Int, good_coffee_perc: Double, good_beer: Int, good_beer_perc: Double, pintxo_friendly: Int,
pintxo_friendly_perc: Double, hipster: Int, hipster_perc: Double)
object Spots {
implicit object SpotsReader extends BSONDocumentReader[Spots] {
def read(doc: BSONDocument): Spots = {
val id = doc.getAs[String]("_id").get
val name = doc.getAs[String]("name").get
val lat = doc.getAs[Double]("lat").get
val lon = doc.getAs[Double]("lon").get
val created = doc.getAs[Long]("created").get
val total_valorations = doc.getAs[Int]("total_valorations").get
val quiet = doc.getAs[Int]("quiet").get
val quiet_perc = doc.getAs[Double]("quiet_perc").get
val good_coffee = doc.getAs[Int]("good_coffee").get
val good_coffee_perc = doc.getAs[Double]("good_coffee_perc").get
val good_beer = doc.getAs[Int]("good_beer").get
val good_beer_perc = doc.getAs[Double]("good_beer_perc").get
val pintxo_friendly = doc.getAs[Int]("pintxo_friendly").get
val pintxo_friendly_perc = doc.getAs[Double]("pintxo_friendly_perc").get
val hipster = doc.getAs[Int]("hipster").get
val hipster_perc = doc.getAs[Double]("hipster_perc").get
Spots(id, name, lat, lon, created, total_valorations, quiet, quiet_perc, good_coffee, good_coffee_perc,
good_beer, good_beer_perc, pintxo_friendly, pintxo_friendly_perc, hipster, hipster_perc)
}
}
}
开发者ID:ElComite,项目名称:placesmapper_back,代码行数:36,代码来源:Spots.scala
示例20: User
//设置package包名称以及导入依赖的类
package model
import reactivemongo.bson.{BSONDocumentWriter, BSONDocument, BSONDocumentReader}
case class User(
id: String = java.util.UUID.randomUUID.toString,
isGoogleUser: Boolean = false,
userName: String,
passwordHash: String = ""
) extends WithId
case class CreateUserRequest(userName: String, password: String)
//case class CreateGoogleUserRequest(accessToken: Option[String], idToken: Option[String])
case class UserInfo(id: String, userName: String)
object UserInfo {
def apply(user: User) = new UserInfo(id = user.id, userName = user.userName)
}
object User {
implicit object ReceiptEntityBSONReader extends BSONDocumentReader[User] {
def read(doc: BSONDocument): User =
Serialization.deserialize(
doc,
User(
id = doc.getAs[String]("_id").get,
isGoogleUser = doc.getAs[Boolean]("isGoogleUser").getOrElse(false),
userName = doc.getAs[String]("userName").get,
passwordHash = doc.getAs[String]("passwordHash").get
)
)
}
implicit object ReceiptEntityBSONWriter extends BSONDocumentWriter[User] {
def write(user: User): BSONDocument = {
BSONDocument(
"_id" -> user.id,
"userName" -> user.userName,
"isGoogleUser" -> user.isGoogleUser,
"passwordHash" -> user.passwordHash
)
}
}
}
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:51,代码来源:User.scala
注:本文中的reactivemongo.bson.BSONDocumentReader类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论