当前位置: 首页>>代码示例>>Scala>>正文


Scala BSONDocumentWriter类代码示例

本文整理汇总了Scala中reactivemongo.bson.BSONDocumentWriter的典型用法代码示例。如果您正苦于以下问题:Scala BSONDocumentWriter类的具体用法?Scala BSONDocumentWriter怎么用?Scala BSONDocumentWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了BSONDocumentWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: 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

示例2: 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

示例3: write

//设置package包名称以及导入依赖的类
package com.realizationtime.btdogg.persist

import java.time.{Instant, LocalDate}

import com.realizationtime.btdogg.TKey
import com.realizationtime.btdogg.parsing.ParsingResult.{FileEntry, TorrentDir, TorrentFile}
import com.realizationtime.btdogg.persist.MongoPersist.{Liveness, TorrentDocument}
import com.realizationtime.btdogg.persist.MongoTorrentWriter.localDateToString
import reactivemongo.bson.{BSONDateTime, BSONDocument, BSONDocumentWriter, BSONInteger, BSONString, BSONWriter, Macros}

trait MongoTorrentWriter {

  implicit val tkeyWriter = new BSONWriter[TKey, BSONString] {
    override def write(k: TKey): BSONString = BSONString(k.hash)
  }
  implicit val torrentDataFileWriter: BSONDocumentWriter[TorrentFile] = Macros.writer[TorrentFile]
  implicit val torrentDataDirWriter: BSONDocumentWriter[TorrentDir] = Macros.writer[TorrentDir]
  implicit val torrentDataWriter: BSONDocumentWriter[FileEntry] = Macros.writer[FileEntry]
  implicit val instantWriter = new BSONWriter[Instant, BSONDateTime] {
    override def write(t: Instant): BSONDateTime = BSONDateTime(t.toEpochMilli)
  }

  implicit val torrentWriter: BSONDocumentWriter[TorrentDocument] = Macros.writer[TorrentDocument]

  implicit val livenessWriter: BSONDocumentWriter[Liveness] = Macros.writer[Liveness]

  implicit val localDateWriter = new BSONWriter[LocalDate, BSONString] {
    override def write(t: LocalDate): BSONString = BSONString(localDateToString(t))
  }

  implicit val mapWriter: BSONDocumentWriter[Map[LocalDate, Int]] = new BSONDocumentWriter[Map[LocalDate, Int]] {
    def write(map: Map[LocalDate, Int]): BSONDocument = {
      val elements = map.toStream.map { tuple =>
        localDateToString(tuple._1) -> BSONInteger(tuple._2)
      }
      BSONDocument(elements)
    }
  }

}

object MongoTorrentWriter {

  def localDateToString(date: LocalDate): String = date.toString

} 
开发者ID:bwrega,项目名称:btdogg,代码行数:47,代码来源:MongoTorrentWriter.scala

示例4: 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

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: 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

示例10: PendingFile

//设置package包名称以及导入依赖的类
package model

import model.PendingFile.PendingFileId
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}

case class PendingFile(id: PendingFileId, userId: String, receiptId: String) extends WithId

object PendingFile {

  type PendingFileId = String

  implicit object PendingFileBSONReader extends BSONDocumentReader[PendingFile] {

    def read(doc: BSONDocument): PendingFile =
      Serialization.deserialize(doc,
                                PendingFile(
                                  id = doc.getAs[String]("_id").get,
                                  userId = doc.getAs[String]("userId").get,
                                  receiptId = doc.getAs[String]("receiptId").get
                                ))
  }

  implicit object PendingFileBSONWriter extends BSONDocumentWriter[PendingFile] {

    def write(pendingFile: PendingFile): BSONDocument = {
      BSONDocument(
        "_id"       -> pendingFile.id,
        "userId"    -> pendingFile.userId,
        "receiptId" -> pendingFile.receiptId
      )
    }
  }
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:34,代码来源:PendingFile.scala

示例11: ReceiptEntity

//设置package包名称以及导入依赖的类
package model

import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}

case class ReceiptEntity(
    id: String = java.util.UUID.randomUUID.toString,
    userId: String,
    files: List[FileEntity] = List.empty,
    description: String = "",
    total: Option[BigDecimal] = None,
    timestamp: Long = System.currentTimeMillis,
    lastModified: Long = System.currentTimeMillis(),
    transactionTime: Long = System.currentTimeMillis(),
    tags: List[String] = List.empty
) extends WithId

object ReceiptEntity {

  implicit object ReceiptEntityBSONReader extends BSONDocumentReader[ReceiptEntity] {

    def read(doc: BSONDocument): ReceiptEntity =
      Serialization.deserialize(
        doc,
        ReceiptEntity(
          id = doc.getAs[String]("_id").get,
          userId = doc.getAs[String]("userId").get,
          files = doc.getAs[List[FileEntity]]("files").get,
          description = doc.getAs[String]("description").get,
          total = doc.getAs[String]("total") match {
            case Some(value) => if (value != "None") Some(BigDecimal(value.replace("Some(", "").replace(")", ""))) else None
            case None        => None
          },
          timestamp = doc.getAs[Long]("timestamp").get,
          lastModified = doc.getAs[Long]("lastModified").get,
          transactionTime = doc.getAs[Long]("transactionTime").get,
          tags = doc.getAs[List[String]]("tags").getOrElse(List.empty)
        )
      )
  }

  implicit object ReceiptEntityBSONWriter extends BSONDocumentWriter[ReceiptEntity] {

    def write(receiptEntity: ReceiptEntity): BSONDocument = {
      BSONDocument(
        "_id"             -> receiptEntity.id,
        "userId"          -> receiptEntity.userId,
        "files"           -> receiptEntity.files,
        "description"     -> receiptEntity.description,
        "total"           -> receiptEntity.total.toString,
        "timestamp"       -> receiptEntity.timestamp,
        "lastModified"    -> receiptEntity.lastModified,
        "transactionTime" -> receiptEntity.transactionTime,
        "tags"            -> receiptEntity.tags
      )
    }
  }

} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:59,代码来源:ReceiptEntity.scala

示例12: OcrEntity

//设置package包名称以及导入依赖的类
package model

import ocr.model.OcrTextAnnotation
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}

case class OcrEntity(
    id: String,
    userId: String,
    result: OcrTextAnnotation
) extends WithId

case class OcrText(text: String)

case class OcrTextOnly(
    id: String,
    result: OcrText
) extends WithId

object OcrTextOnly {
  implicit def ocrTextReader: BSONDocumentReader[OcrText] = Macros.reader[OcrText]
  implicit object OcrTextOnlyBSONReader extends BSONDocumentReader[OcrTextOnly] {

    def read(doc: BSONDocument): OcrTextOnly =
      Serialization.deserialize(doc,
                                OcrTextOnly(
                                  id = doc.getAs[String]("_id").get,
                                  result = doc.getAs[OcrText]("result").get
                                ))
  }
}

object OcrEntity {

  implicit object OcrEntityBSONReader extends BSONDocumentReader[OcrEntity] {

    def read(doc: BSONDocument): OcrEntity =
      Serialization.deserialize(doc,
                                OcrEntity(
                                  id = doc.getAs[String]("_id").get,
                                  userId = doc.getAs[String]("userId").get,
                                  result = doc.getAs[OcrTextAnnotation]("result").get
                                ))
  }

  implicit object OcrEntityBSONWriter extends BSONDocumentWriter[OcrEntity] {

    def write(ocrResult: OcrEntity): BSONDocument = {
      BSONDocument(
        "_id"    -> ocrResult.id,
        "userId" -> ocrResult.userId,
        "result" -> ocrResult.result
      )
    }
  }
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:56,代码来源:OcrEntity.scala

示例13: save

//设置package包名称以及导入依赖的类
package repository

import model.WithId
import reactivemongo.api._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}

import scala.concurrent.Future

trait MongoDao[T <: WithId] extends MongoConnection {

  def save(collectionFuture: Future[BSONCollection], entity: T)(implicit reader: BSONDocumentWriter[T]): Future[T] =
    collectionFuture.flatMap(_.update(queryById(entity.id), entity, upsert = true).map(_ => entity))

  def deleteById(collectionFuture: Future[BSONCollection], id: String) = collectionFuture.flatMap(_.remove(queryById(id)))

  def find(collectionFuture: Future[BSONCollection], query: BSONDocument)(implicit reader: BSONDocumentReader[T]): Future[Option[T]] = {
    collectionFuture.flatMap(
      _.find(query)
        .cursor[T]()
        .collect[List](-1, Cursor.FailOnError[List[T]]())
        .map {
          case x :: xs => Some(x)
          case _       => None
        })
  }

  def findList(collectionFuture: Future[BSONCollection], query: BSONDocument)(implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
    collectionFuture.flatMap(
      _.find(query)
        .cursor[T]()
        .collect[List](-1, Cursor.FailOnError[List[T]]()))
  }

  def findList(collectionFuture: Future[BSONCollection], query: BSONDocument, projection: BSONDocument)(
      implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
    collectionFuture.flatMap(
      _.find(query)
        .cursor[T]()
        .collect[List](-1, Cursor.FailOnError[List[T]]()))
  }

  def queryById(id: String) = BSONDocument("_id" -> id)
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:45,代码来源:MongoDao.scala

示例14: Beacon

//设置package包名称以及导入依赖的类
package models

import reactivemongo.bson.BSONArray
import reactivemongo.bson.BSONDocument
import reactivemongo.bson.BSONDocumentReader
import reactivemongo.bson.BSONDocumentWriter

case class Beacon(
  address: String,
  creator: String,
  endTime: Long,
  location: Point,
  notifiedCount: Int,
  notitifiedUsers: List[String],
  placeName: String,
  range: Double,
  startTime: Long,
  tags: List[String],
  title: String
)

object Beacon {
  implicit object BeaconReader extends BSONDocumentReader[Beacon] {
    def read(bson: BSONDocument): Beacon = {
      val opt: Option[Beacon] = for {
        address <- bson.getAs[String]("address")
        creator <- bson.getAs[String]("creator")
        endTime <- bson.getAs[Long]("endTime")
        location <- bson.getAs[Point]("location")
        notifiedCount <- bson.getAs[Int]("notifiedCount")
        notifiedUsers <- bson.getAs[List[String]]("notifiedUsers")
        placeName <- bson.getAs[String]("placeName")
        range <- bson.getAs[Double]("range")
        startTime <- bson.getAs[Long]("startTime")
        tags <- bson.getAs[List[String]]("tags")
        title <- bson.getAs[String]("title")
      } yield Beacon(address, creator, endTime, location, notifiedCount,
                     notifiedUsers, placeName, range, startTime, tags, title)

      opt.getOrElse(null)
    }
  }

  implicit object BeaconWriter extends BSONDocumentWriter[Beacon] {
    def write(beacon: Beacon): BSONDocument = BSONDocument(
      "address" -> beacon.address,
      "creator" -> beacon.creator,
      "endTime" -> beacon.endTime,
      "location" -> beacon.location,
      "notifiedCount" -> beacon.notifiedCount,
      "notifiedUsers" -> BSONArray(beacon.notitifiedUsers),
      "placeName" -> beacon.placeName,
      "range" -> beacon.range,
      "startTime" -> beacon.startTime,
      "tags" -> BSONArray(beacon.tags),
      "title" -> beacon.title
    )
  }
} 
开发者ID:tninesling,项目名称:BeaconServer,代码行数:60,代码来源:Beacon.scala

示例15: Point

//设置package包名称以及导入依赖的类
package models

import reactivemongo.bson.BSONArray
import reactivemongo.bson.BSONDocument
import reactivemongo.bson.BSONDocumentReader
import reactivemongo.bson.BSONDocumentWriter

case class Point(lat: Double, lon: Double) {
  require(lat >= -90.0)
  require(lat <= 90.0)
  require(lon >= -180.0)
  require(lon <= 180.0)
}

object Point {
  implicit object PointReader extends BSONDocumentReader[Point] {
    def read(bson: BSONDocument): Point = {
      val opt: Option[Point] = for {
        coords <- bson.getAs[BSONArray]("coordinates")
        lon <- coords.getAs[Double](0)
        lat <- coords.getAs[Double](1)
      } yield new Point(lat, lon)

      opt.getOrElse(null)
    }
  }

  implicit object PointWriter extends BSONDocumentWriter[Point] {
    def write(point: Point): BSONDocument = BSONDocument(
      "type" -> "Point",
      "coordinates" -> BSONArray(point.lon, point.lat)
    )
  }
} 
开发者ID:tninesling,项目名称:BeaconServer,代码行数:35,代码来源:Point.scala


注:本文中的reactivemongo.bson.BSONDocumentWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。