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


Scala ObjectId类代码示例

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


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

示例1: Address

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

import java.util.UUID

import collections.UserStatus.UserStatus
import com.google.inject.{Inject, Singleton}
import mongo.{BaseMongoCollection, MongoDAO, MongoDBObjectId}
import org.bson.types.ObjectId
import org.joda.time.DateTime
import org.json4s.Formats
import org.json4s.ext.EnumNameSerializer



case class Address(address: String, country: String = "HK")

object UserStatus extends Enumeration {
  type UserStatus = Value
  val Active, Disabled = Value
}

case class TestUser(
                     _id: Option[ObjectId] = None, // mongodb will auto-generate the _id by default
                     name: String, // required
                     nickName: Option[String] = None, // if application-wise is optional => should use option Type and default value = None
                     address: Address = Address(address = "address"), // can nested object
                     friends: List[TestUser] = List(),
                     uuid: UUID = UUID.randomUUID(),
                     jodaDateTime: DateTime = new DateTime(),
                     status: UserStatus = UserStatus.Active
               ) extends MongoDBObjectId

@Singleton
class TestCollection @Inject() (mongoDAO: MongoDAO)
  extends BaseMongoCollection[TestUser](collectionName = "test", mongoDAO) {
  // add enum serializer
  override protected implicit val formats: Formats = standardMongoSerializer ++ jodaTimeSerializers + new EnumNameSerializer(UserStatus)
} 
开发者ID:gaplo917,项目名称:play-scala-casbah-json4s-seed,代码行数:39,代码来源:TestCollection.scala

示例2: Model

//设置package包名称以及导入依赖的类
package com.zhranklin.homepage.imhere

import com.zhranklin.homepage._
import org.bson.types.ObjectId


object Model {

  import Util._idRename

  case class Place(id: String, name: String) extends _idRename
  case class ItemWithOwner(title: String, `type`: String, content: String,
                           place: String, owner: String, id: Option[ObjectId] = None) extends _idRename {
    def withId(id: ObjectId) = ItemWithOwner(title, `type`, content, place, owner, Some(id))
    def asItem = Item(title, `type`, content, place, id)
  }
  case class Item(title: String, `type`: String, content: String,
                  place: String, id: Option[ObjectId] = None) extends _idRename {
    def withId(id: ObjectId) = Item(title, `type`, content, place, Some(id))
    def withOwner(owner: String) = ItemWithOwner(title, `type`, content, place, owner, id)
  }
  case class User(username: String, name: String)
  case class UserPass(username: String, name: String, password: String) {
    def asUser = User(username, name)
  }
  object Item1 {
    val is = List(
      ItemWithOwner("title0", "text", "kkk", "001", "public"),
      ItemWithOwner("title1", "html", "<h1>head</h1><p>ttext</p>", "001", "public"),
      ItemWithOwner("title2", "html", "<h2>head2</h2><p>text</p>", "002", "public"),
      ItemWithOwner("title3", "url", "http://www.baidu.com", "002", "public"),
      ItemWithOwner("title4", "text", "kkk4", "001", "public"),
      ItemWithOwner("title5", "text", "kkk5", "002", "public"),
      ItemWithOwner("title6", "text", "kkk6", "001", "public"),
      ItemWithOwner("title7", "text", "kkk7", "002", "public"),
      ItemWithOwner("title8", "text", "kkk8", "001", "public"),
      ItemWithOwner("title9", "text", "kkk9", "002", "public"))
  }
} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:40,代码来源:Model.scala

示例3: FilesRepository

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

import java.io.FileInputStream
import java.net.URLConnection

import com.mongodb.casbah.gridfs.{GridFS, GridFSDBFile}
import conf.connection.HashDB
import domain.storage.FileMeta
import org.bson.types.ObjectId


object FilesRepository {
  val gridfs = GridFS(HashDB.getConnection())

  def getFileType(name: String): String = {
    URLConnection.guessContentTypeFromName(name)
  }

  def save(file: FileInputStream,meta:FileMeta):ObjectId = {
    val fileId = gridfs(file) { f =>
      f.filename = meta.fileName
      f.contentType = meta.contentType
    }

    fileId.get.asInstanceOf[ObjectId]
  }

  def getFileById(id: String): Option[GridFSDBFile] = {
    gridfs.findOne(new ObjectId(id))
  }

  def getFilesByName(fileName: String): Option[GridFSDBFile] = {
    gridfs.findOne(fileName)

  }

  def deleteFileById(id: String) = {
    gridfs.remove(new ObjectId(id))
  }

  def deleteFilesByName(fileName: String) = {
    gridfs.remove(fileName)
  }

} 
开发者ID:Thulebona,项目名称:hashpvtapi,代码行数:46,代码来源:FileRepository.scala

示例4: Generators

//设置package包名称以及导入依赖的类
package com.vatbox.epoximise

import java.time.{LocalDate, LocalDateTime}
import java.util.UUID

import org.bson.types.ObjectId
import org.scalacheck.{Arbitrary, Gen}


object Generators {
  def upperLevelGen: Gen[UpperLevel] = for{
    i <- Arbitrary.arbInt.arbitrary
    b <- Arbitrary.arbBool.arbitrary
    s <- Gen.listOfN(10,Gen.alphaNumChar).map(_.mkString)
    o <- Gen.option(Arbitrary.arbBool.arbitrary)
    d <- Arbitrary.arbDouble.arbitrary
    l <- Arbitrary.arbLong.arbitrary
    uuid <- Gen.uuid
    set <- Gen.choose(0,5).flatMap(size => Gen.listOfN(size,embeddedGen)).map(_.toSet)
  } yield UpperLevel(i, b, s, o, d, l, ObjectId.get(), uuid, set)

  def embeddedGen : Gen[Embedded] = for {
    ii <- Arbitrary.arbInt.arbitrary
    bb <- Arbitrary.arbBool.arbitrary
    arr <- Gen.choose(0,10).flatMap(size => Gen.listOfN(size, Arbitrary.arbInt.arbitrary))
    lDateTime <- Gen.choose(10000,100000).map { sec =>
      val time = LocalDateTime.now().minusSeconds(sec)
      val nanos = time.getNano
      time.minusNanos(nanos)
    }
    lclDate <- for {
      month <- Gen.choose(1, 6)
      day <- Gen.choose(1, 28)
    } yield LocalDate.of(2016, month, day)
  } yield Embedded(ii, bb, arr, lDateTime, lclDate)
}

case class UpperLevel(
                       i: Int,
                       b: Boolean,
                       s: String,
                       o: Option[Boolean],
                       d: Double,
                       l: Long,
                       objectId: ObjectId,
                       uuid: UUID,
                       set: Set[Embedded]
                     )

case class Embedded(ii: Int, bb: Boolean, arr: List[Int], lclDate: LocalDateTime, justLclDate: LocalDate) 
开发者ID:VATBox,项目名称:Epoximise,代码行数:51,代码来源:Generators.scala

示例5: GameEdition

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

import java.time.LocalDate

import org.bson.types.ObjectId

class GameEdition(
                   val id: ObjectId,
                   val region: String,
                   val name: String,
                   val platform: Platform,
                   val game: GameEditionGame,
                   val releaseDate: LocalDate
                 ) {
}

class GameEditionGame(val id: ObjectId,
                      val name: String) {
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:20,代码来源:GameEdition.scala

示例6: LocalDateSerializer

//设置package包名称以及导入依赖的类
package com.buysomegames.kernel

import java.time.LocalDate
import java.time.format.DateTimeFormatter

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonSerializer, SerializerProvider}
import com.twitter.finatra.json.modules.FinatraJacksonModule
import org.bson.types.ObjectId

private class LocalDateSerializer extends JsonSerializer[LocalDate] {
  override def serialize(value: LocalDate, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
    gen.writeString(value.format(DateTimeFormatter.ISO_DATE))
  }
}

private class ObjectIdSerializer extends JsonSerializer[ObjectId] {
  override def serialize(value: ObjectId, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
    gen.writeString(value.toHexString)
  }
}

object BuysomegamesJacksonModule extends FinatraJacksonModule {
  override val additionalJacksonModules = Seq(
    new SimpleModule {
      addSerializer(classOf[LocalDate], new LocalDateSerializer)
    },
    new SimpleModule {
      addSerializer(classOf[ObjectId], new ObjectIdSerializer)
    }
  )
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:34,代码来源:BuysomegamesJacksonModule.scala

示例7: BuysomegamesJacksonModuleTest

//设置package包名称以及导入依赖的类
package com.buysomegames.kernel

import java.time.LocalDate

import com.fasterxml.jackson.databind.ObjectMapper
import com.twitter.inject.app.TestInjector
import org.bson.types.ObjectId
import org.scalatest.{Matchers, WordSpec}

class BuysomegamesJacksonModuleTest extends WordSpec with Matchers {
  "BuysomegamesJacksonModule" when {
    def injector = TestInjector(modules = BuysomegamesJacksonModule)
    val objectMapper: ObjectMapper = injector.instance[ObjectMapper]
    "LocalDate is used" should {
      "serialize it using ISO8601 format" in {
        val date = LocalDate.parse("2007-12-03")
        val result = objectMapper.writeValueAsString(date)
        result shouldBe "\"2007-12-03\""
      }
    }
    "ObjectId is used" should {
      "serialize it as hex string" in {
        val objectId: ObjectId = new ObjectId("5894944f5591d01832058cda")
        val result = objectMapper.writeValueAsString(objectId)
        result shouldBe "\"5894944f5591d01832058cda\""
      }
    }
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:30,代码来源:BuysomegamesJacksonModuleTest.scala

示例8: GameEditionRepositoryIntegrationTest

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

import java.time.LocalDate
import java.util.concurrent.TimeUnit

import com.buysomegames.kernel.MongoConnectionModule
import com.buysomegames.model.GameEdition
import com.buysomegames.test.FreshDatabase
import com.twitter.inject.app.TestInjector
import com.twitter.inject.{Injector, IntegrationTest}
import org.bson.types.ObjectId

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

class GameEditionRepositoryIntegrationTest extends IntegrationTest with FreshDatabase {
  override protected def injector: Injector = TestInjector(modules = Seq(MongoConnectionModule))

  "GameEditionsRepository.findAllGameEditions method" should {
    "return all available game editions" in {
      val gameEditions = getAllGameEditions
      gameEditions should have size 3
    }
    "map GameEdition.name" in {
      val uncharted = getAllGameEditionsAndExtractUncharted
      uncharted.name should be("Uncharted: Drake's Fortune")
    }
    "map GameEdition.game with ID and name from the database" in {
      val uncharted = getAllGameEditionsAndExtractUncharted
      uncharted.game.id should be(new ObjectId("57c28e830868729b8638fe5c"))
      uncharted.game.name should be("Uncharted: Drake’s Fortune")
    }
    "map GameEdition.name as test entity" in {
      val uncharted = getAllGameEditionsAndExtractUncharted
      uncharted.platform.id should be("PS3")
      uncharted.platform.name should be("changeit")
    }
    "map GameEdition.region from the database" in {
      val uncharted = getAllGameEditionsAndExtractUncharted
      uncharted.region should be("US")
    }
    "map GameEdition.releaseDate from the database" in {
      val uncharted = getAllGameEditionsAndExtractUncharted
      uncharted.releaseDate should be(LocalDate.parse("2007-11-16"))
    }
  }

  private def getAllGameEditionsAndExtractUncharted: GameEdition = {
    val gameEditions: Iterable[GameEdition] = getAllGameEditions
    val uncharted: GameEdition = gameEditions.find(_.id == new ObjectId("5894944f5591d01832058cda")).get
    uncharted
  }

  private def getAllGameEditions: Iterable[GameEdition] = {
    val gameEditionsFuture: Future[Iterable[GameEdition]] = injector.instance[GameEditionRepository].findAllGameEditions
    val gameEditions: Iterable[GameEdition] = Await.result(gameEditionsFuture, Duration(10, TimeUnit.SECONDS))
    gameEditions
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:60,代码来源:GameEditionRepositoryIntegrationTest.scala

示例9: GameEditionServiceTest

//设置package包名称以及导入依赖的类
package com.buysomegames.service

import java.time.LocalDate
import java.util.concurrent.TimeUnit

import com.buysomegames.controller.response.GameEditionsResponse
import com.buysomegames.model.{GameEdition, GameEditionGame, Platform}
import com.buysomegames.repository.GameEditionRepository
import org.bson.types.ObjectId
import org.mockito.Mockito.when
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpec}

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

class GameEditionServiceTest extends WordSpec with MockitoSugar with Matchers with BeforeAndAfterEach {
  var gameEditionService: GameEditionService = _
  var mockGameEditionRepository: GameEditionRepository = _

  override protected def beforeEach(): Unit = {
    mockGameEditionRepository = mock[GameEditionRepository]
    gameEditionService = new GameEditionService(gameEditionRepository = mockGameEditionRepository)
  }

  "GameService.handleFindAllGames" should {
    "create GamesResponse from result of GameRepository.findAllGames" in {
      val gameEdition = new GameEdition(
        id = new ObjectId(),
        name = "Uncharted",
        region = "US",
        platform = new Platform(id = "PS3", name = "Playstation 3"),
        game = new GameEditionGame(id = new ObjectId(), name = "Uncharted"),
        releaseDate = LocalDate.parse("2007-11-16")
      )
      when(mockGameEditionRepository.findAllGameEditions).thenReturn(Future.successful(Seq(gameEdition)))
      val responseFuture: Future[GameEditionsResponse] = gameEditionService.handleFindAllGameEditions
      val response = Await.result(responseFuture, Duration.create(10, TimeUnit.SECONDS))
      response.gameEditions should contain only gameEdition
    }
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:43,代码来源:GameEditionServiceTest.scala

示例10: PersistedCatalogueProduct

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

import com.mongodb.casbah.commons.Imports.{ObjectId => Oid}
import org.bson.types.ObjectId

import org.joda.time.DateTime

case class PersistedCatalogueProduct(_id: Oid,
                                     name: String,
                                     version: Int = 0,
                                     title: String,
                                     description: String,
                                     attributes: Map[String, CatalogueAttribute] = Map.empty,
                                     serviceAddOns: List[ServiceAddOn] = Nil,
                                     tags: List[String] = Nil,
                                     created: DateTime = DateTime.now(),
                                     lastModified: DateTime = DateTime.now(),
                                     productBlockList: List[ProductBlockList] = Nil)

case class NewCatalogueProduct(name: String,
                               title: String,
                               description: String,
                               attributes: Map[String, CatalogueAttribute] = Map.empty,
                               serviceAddOns: List[ServiceAddOn] = Nil,
                               tags: List[String] = Nil,
                               created: DateTime,
                               lastModified: DateTime,
                               productBlockList: List[ProductBlockList] = Nil) {

  def toPersistedCatalogueProduct(version: Int = 0, id: ObjectId = ObjectId.get()) =
    PersistedCatalogueProduct(
      _id = id,
      name = name,
      version = version,
      title = title,
      description = description,
      attributes = attributes,
      serviceAddOns = serviceAddOns,
      tags = tags,
      created = created,
      lastModified = lastModified,
      productBlockList = productBlockList
    )
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:45,代码来源:CatalogueProduct.scala

示例11: SalatRepository

//设置package包名称以及导入依赖的类
package cjp.catalogue.mongo

import com.mongodb.WriteConcern
import com.mongodb.casbah.commons.MongoDBObject
import com.mongodb.casbah.{MongoCollection, MongoDB}
import com.novus.salat._
import com.novus.salat.dao.SalatDAO
import org.bson.types.ObjectId

abstract class SalatRepository[T <: CaseClass](val collectionName: String, getDb: () => MongoDB, mc: Option[MongoCollection] = None)(implicit manifest: Manifest[T], ctx: Context)
  extends SalatDAO[T, ObjectId](collection = mc.getOrElse(getDb()(collectionName))) {

  def findAll: List[T] = {
    find(MongoDBObject.empty).toList
  }

  def removeAll = {
    collection.remove(MongoDBObject.empty)
  }

  def drop() {
    collection.drop()
  }

  def save(bulk: List[T], wc: WriteConcern = WriteConcern.SAFE) {
    bulk.foreach {
      super.save(_, wc)
    }
  }

  def findById(id: String): Option[T] = {
    findOneById(new ObjectId(id))
  }

} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:36,代码来源:SalatRepository.scala

示例12: CataloguePublishedProductBuilder

//设置package包名称以及导入依赖的类
package cjp.catalogue.test.builder

import cjp.catalogue.model.{ServiceAddOn, CatalogueAttribute, CataloguePublishedProduct}
import org.bson.types.ObjectId
import org.joda.time.DateTime

object CataloguePublishedProductBuilder {

  def apply(name: String = "a-title",
            title: String = "a title",
            description: String = "a description",
            attributes: Map[String, CatalogueAttribute] = Map.empty,
            serviceAddOns: List[ServiceAddOn] = Nil,
            version: Int = 1,
            updateId: Option[ObjectId] = None,
            effectiveFrom: DateTime = DateTime.now) =
    CataloguePublishedProduct(
      name = name,
      title = title,
      description = description,
      attributes = attributes,
      serviceAddOns = serviceAddOns,
      version = version,
      updateId = updateId,
      effectiveFrom = effectiveFrom
    )
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:28,代码来源:CataloguePublishedProductBuilder.scala

示例13: CatalogueProductBuilder

//设置package包名称以及导入依赖的类
package cjp.catalogue.test.builder

import cjp.catalogue.model._
import org.bson.types.ObjectId
import org.joda.time.DateTime

object CatalogueProductBuilder {

  def apply(_id: ObjectId = ObjectId.get,
            name: String = "a-title",
            title: String = "a title",
            description: String = "a description",
            attributes: Map[String, CatalogueAttribute] = Map.empty,
            serviceAddOns: List[ServiceAddOn] = Nil,
            tags: List[String] = Nil,
            created: DateTime = DateTime.now,
            lastModified: DateTime = DateTime.now,
            version: Int = 0) =

    NewCatalogueProduct(
      name = name,
      title = title,
      description = description,
      attributes = attributes,
      serviceAddOns = serviceAddOns,
      tags = tags,
      created = created,
      lastModified = lastModified
    )

  def newProduct : NewCatalogueProduct = CatalogueProductBuilder()
  def persistedProduct : PersistedCatalogueProduct = CatalogueProductBuilder().toPersistedCatalogueProduct(0)
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:34,代码来源:CatalogueProductBuilder.scala

示例14: generateObjId

//设置package包名称以及导入依赖的类
package org.edu.utn.newspark.utils

import java.util.Date

import org.bson.types.ObjectId
import org.edu.utn.newspark.lemmatizer.NewsMeta
import org.edu.utn.newspark.lsa.Group


trait NewsFixture {

  val now = new Date

  def generateObjId = {
    Thread.sleep(20)
    new ObjectId(new Date)
  }
  def generateNewsMeta(title: String) = NewsMeta(generateObjId, title, "Deportes", "the image url", now)

  // Fixture

  // News
  val newsMessi1 = generateNewsMeta("messi1")
  val newsMessi2 = generateNewsMeta("messi2")
  val newsRonaldo = generateNewsMeta("ronaldo")

  // Term Scores
  val messiTermScore = ("messi", 100D, 1)
  val futbolTermScore = ("futbol", 75D, 3)

  val termScoresMessi1 = List(messiTermScore, futbolTermScore, ("barcelona", 90D, 2))
  val termScoresMessi1B = List(messiTermScore, futbolTermScore, ("evasion", 110D, 2))
  val termScoresMessi2 = List(messiTermScore, futbolTermScore, ("argentina", 85D, 4))
  val termScoresRonaldo = List(("ronaldo", 100D, 5), futbolTermScore, ("real", 55D, 4))

  // Doc scores
  val docMessi1 = (newsMessi1, 40D, 1L)
  val docMessi1B = (newsMessi1, 50D, 2L)
  val docMessi2 = (newsMessi2, 75D, 3L)
  val docRonaldo = (newsRonaldo, 20D, 4L)

  val docScoresMessi1 = List(docMessi1)
  val docScoresMessi1B = List(docMessi1B)
  val docScoresMessi2 = List(docMessi2)
  val docScoresRonaldo = List(docRonaldo)

  // Groups
  val messiGroup1: Group = (termScoresMessi1, docScoresMessi1, newsMessi1.imageUrl, false)
  val messiGroup1B: Group = (termScoresMessi1B, docScoresMessi1B, newsMessi1.imageUrl, false)
  val messiGroup2: Group = (termScoresMessi2, docScoresMessi2, newsMessi2.imageUrl, false)
  val ronaldoGroup: Group = (termScoresRonaldo, docScoresRonaldo, newsRonaldo.imageUrl, false)

  val groups: List[Group] = List(messiGroup1, messiGroup1B, messiGroup2, ronaldoGroup)
} 
开发者ID:Newspark-UTN,项目名称:poc-lsa-model,代码行数:55,代码来源:NewsFixture.scala


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