本文整理汇总了Scala中play.modules.reactivemongo.ReactiveMongoApi类的典型用法代码示例。如果您正苦于以下问题:Scala ReactiveMongoApi类的具体用法?Scala ReactiveMongoApi怎么用?Scala ReactiveMongoApi使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ReactiveMongoApi类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: find
//设置package包名称以及导入依赖的类
package repos
import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.libs.json.{JsObject, Json}
import reactivemongo.api.commands.WriteResult
import play.modules.reactivemongo.ReactiveMongoApi
import javax.inject._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
trait PostRepo {
def find() (implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument) (implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
}
class PostRepoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends PostRepo {
def collection = reactiveMongoApi.db.collection[JSONCollection]("posts");
override def find() (implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj());
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary);
cursor.collect[List]()
}
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector,update)
}
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
开发者ID:Rheriel,项目名称:LightHouse,代码行数:52,代码来源:PostRepo.scala
示例2: PublishedStoryDAOImpl
//设置package包名称以及导入依赖的类
package io.soheila.cms.daos
import javax.inject.Inject
import grizzled.slf4j.Logger
import io.soheila.cms.daos.exceptions.DAOException
import io.soheila.cms.entities.Story
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class PublishedStoryDAOImpl @Inject() (override val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext) extends StoryDAOImpl(reactiveMongoApi) {
private val logger = Logger[this.type]
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("published_stories"))
override def findAndUpdateLatest(story: Story, upsert: Boolean): Future[Either[DAOException, Option[Story]]] = {
findAndUpdateByCriteria(Json.obj("uuid" -> story.uuid.get), story, upsert)
.map {
case Left(err) => Left(DAOException(err.getMessage, err))
case Right(res) => Right(res)
}
}
}
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:27,代码来源:PublishedStoryDAOImpl.scala
示例3: find
//设置package包名称以及导入依赖的类
package repos
import javax.inject.Inject
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait RepoLike {
def find()(implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}
abstract class Repo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends RepoLike {
val collectionName: String
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
collection.find(Json.obj())
.cursor[JsObject](ReadPreference.Primary)
.collect[List](100)
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
def collection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection](collectionName)
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:54,代码来源:Repo.scala
示例4: CounterDao
//设置package包名称以及导入依赖的类
package dao
import javax.inject.Inject
import play.api.libs.concurrent.Execution.Implicits._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson._
import scala.concurrent.Future
class CounterDao @Inject()(reactiveMongoApi: ReactiveMongoApi) {
def countersFuture: Future[BSONCollection] = reactiveMongoApi.database.map(_.collection[BSONCollection]("counters"))
def nextId(collection: String): Future[Long] = {
val query = BSONDocument("collection" -> collection)
val update = BSONDocument("$inc" -> BSONDocument("counter" -> 1))
findAndModify(query, update)
}
def resetId(collection: String) : Future[Long] = {
val query = BSONDocument("collection" -> collection)
val update = BSONDocument("$set" -> BSONDocument("counter" -> 0))
findAndModify(query, update)
}
private def findAndModify(query: BSONDocument, update: BSONDocument): Future[Long] = {
val modify = countersFuture.map(_.BatchCommands.FindAndModifyCommand.Update(
update,
fetchNewObject = true,
upsert = true))
modify.flatMap(modify =>
countersFuture.flatMap(_.findAndModify(query, modify) map { res =>
res.result.get.get("counter") match {
case Some(BSONLong(id)) => id
case Some(BSONDouble(id)) => id.toLong
case Some(BSONInteger(id)) => id.toLong
case _ => 1L
}
})
)
}
}
开发者ID:deusz,项目名称:play-rest-embeded-mongo,代码行数:44,代码来源:CounterDao.scala
示例5: AuthRequestMongo
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.mongo
import javax.inject._
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import uk.gov.bis.levyApiMock.data.{AuthRequest, AuthRequestOps}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random
class AuthRequestMongo @Inject()(val mongodb: ReactiveMongoApi) extends MongoCollection[AuthRequest] with AuthRequestOps {
override val collectionName = "sys_auth_requests"
implicit val authIdF = Json.format[AuthRequest]
override def stash(authRequest: AuthRequest)(implicit ec: ExecutionContext): Future[Long] = {
val id = Random.nextLong().abs
for {
collection <- collectionF
r <- collection.insert(authRequest.copy(id = id))
} yield id
}
override def pop(id: Long)(implicit ec: ExecutionContext): Future[Option[AuthRequest]] = {
findOne("id" -> id).map {
_.map { d => remove("id" -> id); d }
}
}
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:32,代码来源:AuthRequestMongo.scala
示例6: AuthRecordMongo
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.mongo
import javax.inject.Inject
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json._
import uk.gov.bis.levyApiMock.auth.OAuthTrace
import uk.gov.bis.levyApiMock.data.oauth2.{AuthRecord, AuthRecordOps}
import scala.concurrent.{ExecutionContext, Future}
class AuthRecordMongo @Inject()(val mongodb: ReactiveMongoApi) extends MongoCollection[AuthRecord] with AuthRecordOps {
implicit val authRecordF = Json.format[AuthRecord]
override val collectionName = "sys_auth_records"
override def find(accessToken: String)(implicit ec: ExecutionContext) = findOne("accessToken" -> accessToken)
override def forRefreshToken(refreshToken: String)(implicit ec: ExecutionContext) = findOne("refreshToken" -> refreshToken)
override def forAccessToken(accessToken: String)(implicit ec: ExecutionContext) = findOne("accessToken" -> accessToken)
override def find(gatewayID: String, clientId: Option[String])(implicit ec: ExecutionContext) = findOne("gatewayID" -> gatewayID, "clientID" -> clientId)
override def create(auth: AuthRecord)(implicit ec: ExecutionContext): Future[Unit] = {
for {
collection <- collectionF
r <- collection.insert(auth)
} yield ()
}
override def deleteExistingAndCreate(existing: AuthRecord, created: AuthRecord)(implicit ec: ExecutionContext): Future[Unit] = {
OAuthTrace(s"Removing ${existing.accessToken} and creating ${created.accessToken}")
for {
coll <- collectionF
_ <- coll.remove(Json.obj("accessToken" -> existing.accessToken))
_ <- coll.insert(created)
} yield ()
}
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:43,代码来源:AuthRecordMongo.scala
示例7: mongodb
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.mongo
import play.api.libs.json.Json.JsValueWrapper
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait MongoCollection[T] {
def mongodb: ReactiveMongoApi
def collectionName: String
def collectionF(implicit ec: ExecutionContext): Future[JSONCollection] = mongodb.database.map(_.collection[JSONCollection](collectionName))
def findMany(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Seq[T]] = {
val selector = Json.obj(params: _*)
for {
collection <- collectionF
o <- collection.find(selector).cursor[JsObject]().collect[List](100)
} yield o.flatMap {
_.validate[T] match {
case JsSuccess(resp, _) => Some(resp)
case JsError(errs) => None
}
}
}
def findOne(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Option[T]] = {
val selector = Json.obj(params: _*)
val of = for {
collection <- collectionF
o <- collection.find(selector).cursor[JsObject]().collect[List](1).map(_.headOption)
} yield o
of.map {
case Some(o) => o.validate[T] match {
case JsSuccess(resp, _) => Some(resp)
case JsError(errs) => None
}
case _ => None
}
}
def remove(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext): Future[Unit] = {
collectionF.map(coll => coll.remove(Json.obj(params: _*)))
}
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:51,代码来源:MongoCollection.scala
示例8: AuthCodeMongo
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.mongo
import javax.inject.Inject
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json._
import uk.gov.bis.levyApiMock.data.{AuthCodeOps, AuthCodeRow, TimeSource}
import scala.concurrent.{ExecutionContext, Future}
class AuthCodeMongo @Inject()(val mongodb: ReactiveMongoApi, timeSource: TimeSource) extends MongoCollection[AuthCodeRow] with AuthCodeOps {
implicit val fmt = Json.format[AuthCodeRow]
override val collectionName: String = "sys_auth_codes"
override def find(code: String)(implicit ec: ExecutionContext) = findOne("authorizationCode" -> code)
override def delete(code: String)(implicit ec: ExecutionContext): Future[Int] = {
for {
coll <- collectionF
i <- coll.remove(Json.obj("authorizationCode" -> code))
} yield i.n
}
override def create(code: String, gatewayUserId: String, redirectUri: String, clientId: String, scope: String)(implicit ec: ExecutionContext): Future[Int] = {
val row = AuthCodeRow(code, gatewayUserId, redirectUri, timeSource.currentTimeMillis(), Some("read:apprenticeship-levy"), Some(clientId), 3600)
for {
coll <- collectionF
i <- coll.insert(row)
} yield i.n
}
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:34,代码来源:AuthCodeMongo.scala
示例9: authenticate
//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import org.mindrot.jbcrypt.BCrypt
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.BSONObjectID
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait AuthService {
def authenticate(email:String,password:String)(implicit ec: ExecutionContext):Future[Option[String]]
}
class MongoAuthService @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends AuthService {
val collection = "users"
override def authenticate(email: String, password: String)(implicit ec: ExecutionContext): Future[Option[String]] = {
for {
users <- reactiveMongoApi.database.map(_.collection[JSONCollection](collection))
userOpt <- users.find(Json.obj("email"->email)).one[JsObject]
authenticated <- userOpt.map { user =>
Future.successful(BCrypt.checkpw(password,(user \ "password").as[String]))
}.getOrElse(Future.successful(false))
id <- (userOpt,authenticated) match {
case (Some(user),true) =>
val _id:String= (user \ "_id").as[BSONObjectID].stringify
Future.successful(Some(_id))
case (None,_) => Future.successful(None)
case (_,false) => Future.successful(None)
}
} yield id
}
}
开发者ID:sdor,项目名称:labnotes-server,代码行数:42,代码来源:AuthService.scala
示例10: MongoUserActivityDAO
//设置package包名称以及导入依赖的类
package io.soheila.um.daos.activities
import javax.inject.Inject
import io.soheila.commons.crud.MongoCRUDDAO
import io.soheila.commons.entities.Page
import io.soheila.commons.exceptions.MongoDAOException
import io.soheila.um.entities.UserActivity
import io.soheila.um.vos.activities.UserActivityQuery
import play.api.libs.json.{ JsObject, Json }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.indexes.{ Index, IndexType }
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class MongoUserActivityDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext)
extends MongoCRUDDAO[UserActivity, String] with UserActivityDAO {
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("user_activity"))
override def find(userActivityQuery: UserActivityQuery, page: Int, limit: Int, sortFilter: Option[(String, Int)]): Future[Either[MongoDAOException, Page[UserActivity]]] = {
Json.toJson(userActivityQuery)
find(Json.toJson(userActivityQuery).as[JsObject], page, limit, sortFilter)
}
override def indexSet: Set[Index] = Set(
Index(Seq("userUUID" -> IndexType.Ascending)),
Index(Seq("activityType" -> IndexType.Ascending)),
Index(Seq("userIP" -> IndexType.Ascending)),
Index(Seq("userDevice" -> IndexType.Ascending)),
Index(Seq("timestamp" -> IndexType.Ascending))
)
}
开发者ID:esfand-r,项目名称:soheila-um,代码行数:36,代码来源:MongoUserActivityDAO.scala
示例11: MongoUserDAO
//设置package包名称以及导入依赖的类
package io.soheila.um.daos.accounts
import javax.inject.Inject
import com.mohiva.play.silhouette.api.LoginInfo
import io.soheila.um.entities.User
import io.soheila.um.exceptions.UMDAOException
import io.soheila.commons.crud.MongoCRUDDAO
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.indexes.IndexType.Geo2DSpherical
import reactivemongo.api.indexes.{ Index, IndexType }
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class MongoUserDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext)
extends MongoCRUDDAO[User, String] with UserDAO {
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("users"))
def find(loginInfo: LoginInfo): Future[Option[User]] = {
collection.flatMap(_.find(Json.obj("loginInfo" -> loginInfo)).one[User])
}
override def archive(uuid: String): Future[Either[UMDAOException, Boolean]] = {
archive(uuid, archived = true)
}
override def restore(uuid: String): Future[Either[UMDAOException, Boolean]] = {
archive(uuid, archived = false)
}
private def archive(uuid: String, archived: Boolean): Future[Either[UMDAOException, Boolean]] = {
collection.flatMap(col => {
val updateOp = col.updateModifier(Json.obj("$set" -> Json.obj("archived" -> archived)), fetchNewObject = true)
col.findAndModify(Json.obj("uuid" -> uuid), updateOp) map {
entity => Right(true)
}
}).recover {
case err =>
Left(UMDAOException(err.getMessage, err))
}
}
override def indexSet: Set[Index] = Set(
Index(Seq("uuid" -> IndexType.Ascending), unique = true),
Index(Seq("email" -> IndexType.Ascending), unique = true),
Index(Seq("roles" -> IndexType.Ascending)),
Index(List("firstName" -> IndexType.Ascending, "lastName" -> IndexType.Ascending, "fullName" -> IndexType.Text)),
Index(Seq("createdOn" -> IndexType.Descending, "updatedOn" -> IndexType.Descending)),
Index(Seq(("coordinate", Geo2DSpherical)), Some("geo2DSphericalIdx")),
Index(List("attributes.key" -> IndexType.Ascending, "attributes.value" -> IndexType.Ascending))
)
}
开发者ID:esfand-r,项目名称:soheila-um,代码行数:59,代码来源:MongoUserDAO.scala
示例12: ApplicationSpec
//设置package包名称以及导入依赖的类
package test
import play.api.Play.current
import play.api.test._
import play.api.test.Helpers._
import org.scalatest.DoNotDiscover
import org.scalatestplus.play._
import play.modules.reactivemongo.ReactiveMongoApi
@DoNotDiscover
class ApplicationSpec extends PlaySpec with ConfiguredApp {
lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
"Application" must {
"send 404 on a bad request" in {
val nowhere = route(FakeRequest(GET, "/nowhere")).get
status(nowhere) mustBe (NOT_FOUND)
}
"render the hello page" in {
val hello = route(FakeRequest(GET, "/hello")).get
status(hello) mustBe (OK)
contentType(hello) mustBe Some("application/json")
contentAsString(hello) must include ("Hello there!")
}
"connect to test DB" in {
reactiveMongoApi.db mustNot be (null)
}
}
}
开发者ID:paulporu,项目名称:Play-User-Queue,代码行数:37,代码来源:ApplicationSpec.scala
示例13: TranslatorRepositoryImpl
//设置package包名称以及导入依赖的类
package Repositories.implements
import Repositories.TranslatorRepository
import com.google.inject.Inject
import models.Translator
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{QueryOpts, ReadPreference}
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.collection.JSONCollection
import utils.Pagination
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}
class TranslatorRepositoryImpl @Inject()(reactiveMongoApi: ReactiveMongoApi) extends TranslatorRepository{
def collection(implicit ec: ExecutionContext) = reactiveMongoApi.database.map(_.collection[JSONCollection]("translators"))
override def getAllTranslators(pagination: Pagination, sortField: String)(implicit ec: ExecutionContext): Future[List[JsObject]] = {
var sort : Int = 1; var getField: String = sortField
if(sortField.startsWith("-")){
sort = -1; getField = sortField.drop(1)
}
val genericQueryBuilder = collection.map(_.find(Json.obj()).sort(Json.obj(getField -> sort)).options(QueryOpts(pagination.Offset)))
val cursor = genericQueryBuilder.map(_.cursor[JsObject](ReadPreference.Primary))
cursor.flatMap(_.collect[List](pagination.Limit))
}
override def insertTranslator(translator: Translator)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.flatMap(_.insert(translator))
}
override def count()(implicit ec: ExecutionContext): Future[Int] = {
val count = collection.flatMap(_.count()); count
}
}
开发者ID:sopheakreth,项目名称:rest-api-play-scala-mongodb,代码行数:37,代码来源:TranslatorRepositoryImpl.scala
示例14: LetsEncryptService
//设置package包名称以及导入依赖的类
package com.themillhousegroup.play2letsencrypt
import javax.inject.{ Inject, Singleton }
import com.themillhousegroup.mondrian.TypedMongoService
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import com.themillhousegroup.play2letsencrypt.LetsEncryptChallengeResponsePairJson._
import play.api.Configuration
import scala.concurrent.Future
@Singleton
class LetsEncryptService @Inject() (
val reactiveMongoApi: ReactiveMongoApi,
val configuration: Configuration)
extends TypedMongoService[LetsEncryptChallengeResponsePair](configuration.getString("letsencrypt.mongo.collection.name").getOrElse("letsEncryptPairs")) {
def findByChallenge(challenge: String): Future[Option[LetsEncryptChallengeResponsePair]] = {
findOne(Json.obj("challenge" -> challenge))
}
def findResponseFor(challenge: String): Future[Option[String]] = {
findByChallenge(challenge).map { maybePair =>
maybePair.map(_.response)
}
}
def savePair(challenge: String, responseText: String): Future[Option[LetsEncryptChallengeResponsePair]] = {
findByChallenge(challenge).flatMap { maybeExistingPairWithThisChallenge =>
val whatToSave = maybeExistingPairWithThisChallenge.fold {
// Brand new:
new LetsEncryptChallengeResponsePair(None, challenge, responseText)
} { existingPair =>
existingPair.copy(response = responseText)
}
saveAndPopulate(whatToSave)
}
}
}
开发者ID:themillhousegroup,项目名称:play2-lets-encrypt,代码行数:44,代码来源:LetsEncryptService.scala
示例15: UserModule
//设置package包名称以及导入依赖的类
package com.clemble.loveit.user
import com.clemble.loveit.user.service._
import com.clemble.loveit.user.service.repository._
import com.clemble.loveit.user.service.repository.mongo.{MongoInvitationRepository, MongoUserRepository}
import javax.inject.{Named, Singleton}
import com.clemble.loveit.common.mongo.JSONCollectionFactory
import com.google.inject.Provides
import net.codingwell.scalaguice.ScalaModule
import org.joda.time.DateTimeZone
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment, Mode}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.ExecutionContext
class UserModule(env: Environment, conf: Configuration) extends ScalaModule {
override def configure(): Unit = {
DateTimeZone.setDefault(DateTimeZone.UTC)
bind(classOf[UserService]).to(classOf[SimpleUserService])
bind(classOf[UserRepository]).to(classOf[MongoUserRepository])
bind(classOf[InvitationRepository]).to(classOf[MongoInvitationRepository])
bind(classOf[InvitationService]).to(classOf[SimpleInvitationService])
}
@Provides
@Named("user")
@Singleton
def userMongoCollection(mongoApi: ReactiveMongoApi, ec: ExecutionContext): JSONCollection = {
JSONCollectionFactory.create("user", mongoApi, ec, env)
}
@Provides
@Named("invitation")
@Singleton
def inviteMongoCollection(mongoApi: ReactiveMongoApi, ec: ExecutionContext): JSONCollection = {
JSONCollectionFactory.create("invitation", mongoApi, ec, env)
}
@Provides
@Singleton
def subscriptionManager(ws: WSClient, ec: ExecutionContext): SubscriptionManager = {
if (env.mode == Mode.Test) {
TestSubscriptionManager
} else {
val apiKey = conf.getString("email.mailgun.api.key").get
MailgunSubscriptionManager(apiKey, ws, ec)
}
}
}
开发者ID:thankyo,项目名称:thank,代码行数:61,代码来源:UserModule.scala
示例16: JSONCollectionFactory
//设置package包名称以及导入依赖的类
package com.clemble.loveit.common.mongo
import com.mohiva.play.silhouette.api.Logger
import play.api.{Environment, Mode}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.FailoverStrategy
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
object JSONCollectionFactory extends Logger {
private def doCreate(collectionName: String, mongoApi: ReactiveMongoApi)(implicit ec: ExecutionContext): JSONCollection = {
val fCollection: Future[JSONCollection] = mongoApi.
database.
map(_.collection[JSONCollection](collectionName, FailoverStrategy.default))
fCollection.onFailure({ case err =>
logger.error(s"Failed to create ${collectionName}", err);
Thread.sleep(60000)
System.exit(1)
})
Await.result(fCollection, 1 minute)
}
def create(collectionName: String, mongoApi: ReactiveMongoApi, ec: ExecutionContext, env: Environment): JSONCollection = {
val collection = doCreate(collectionName, mongoApi)(ec)
if (env.mode == Mode.Test) Await.result(collection.drop(false)(ec), 1 minute)
collection
}
}
开发者ID:thankyo,项目名称:thank,代码行数:34,代码来源:JSONCollectionFactory.scala
示例17: BalanceInfoController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import models.BalanceInfo
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.{Cursor, ReadPreference}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class BalanceInfoController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext)
extends Controller with MongoController with ReactiveMongoComponents {
val balances: JSONCollection = db.collection[JSONCollection]("balance_info")
def get(name: String) = Action.async {
val balanceCursor: Cursor[BalanceInfo] =
balances.find(Json.obj("name" -> name)).cursor[BalanceInfo](ReadPreference.primary)
val balanceFuture: Future[List[BalanceInfo]] = balanceCursor.collect[List]()
balanceFuture.map { data => Ok(Json.toJson(data)) }
}
}
开发者ID:qza,项目名称:balance-service-play,代码行数:30,代码来源:BalanceInfoController.scala
示例18: MongoBillingDetailsRepository
//设置package包名称以及导入依赖的类
package com.lej.customer.infrastructure.persistence
import javax.inject.Inject
import com.lej.customer.domain.model.BillingDetailsRepository
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
class MongoBillingDetailsRepository @Inject()(reactiveMongoApi: ReactiveMongoApi) extends BillingDetailsRepository {
def collection = reactiveMongoApi.db.collection[JSONCollection]("billing_details")
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj())
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary)
cursor.collect[List]()
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
开发者ID:torstenheinrich,项目名称:lej-order-scala,代码行数:41,代码来源:MongoBillingDetailsRepository.scala
示例19: MemoController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import model.Memo
import org.joda.time.LocalDateTime
import play.api.libs.json.Json
import play.api.mvc.{BodyParsers, Action, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.BSONObjectID
import scala.concurrent.{Future, ExecutionContext}
@Singleton
class MemoController @Inject()(val reactiveMongoApi: ReactiveMongoApi)
(implicit ec: ExecutionContext)
extends Controller with MongoController with ReactiveMongoComponents {
def memoRepo = new backend.MemoMongoRepo(reactiveMongoApi)
//import reactivemongo.play.json._
import util.ReactiveMongoFormats._
implicit val memoFormat = Json.format[Memo]
def list = Action.async {
val memos: Future[List[Memo]] = memoRepo.find()
memos.map(list => Ok(Json.toJson(list)))
}
def post = Action.async(BodyParsers.parse.json) { implicit request =>
val memo: Memo = Memo(Some(BSONObjectID.generate()),
(request.body \ "text").as[String],
new LocalDateTime((request.body \ "date").as[Long]))
memoRepo.save(memo).map(_ => Created(memo._id.get.stringify))
}
}
开发者ID:dturbay,项目名称:memo-rest,代码行数:37,代码来源:MemoController.scala
示例20:
//设置package包名称以及导入依赖的类
package com.themillhousegroup.mondrian.test
import org.specs2.mock.mockito.{MockitoStubs, MocksCreation}
import org.specs2.specification.Scope
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.commands._
import reactivemongo.api.{DefaultDB, MongoConnection, MongoConnectionOptions}
trait ScopedMockedReactiveApi extends Scope with MocksCreation with MockitoStubs with MockedConnection {
val mockDB = mock[DefaultDB]
val mockReactiveApi = mock[ReactiveMongoApi]
mockReactiveApi.db returns mockDB
mockDB.connection returns mockConnection
}
trait MockedConnection extends MocksCreation with MockitoStubs {
val mockConnection = mock[MongoConnection]
val mockConnectionOptions = mock[MongoConnectionOptions]
mockConnection.options returns mockConnectionOptions
mockConnectionOptions.writeConcern returns WriteConcern.Default
}
开发者ID:themillhousegroup,项目名称:mondrian,代码行数:24,代码来源:MockedReactiveApi.scala
注:本文中的play.modules.reactivemongo.ReactiveMongoApi类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论