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


Scala ReactiveMongoComponents类代码示例

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


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

示例1: MyApplicationLoader

//设置package包名称以及导入依赖的类
import dao.CroissantDAO
import jobs.GmailJob
import play.api._
import play.api.ApplicationLoader.Context
import router.Routes
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.libs.mailer._
import play.api.i18n.I18nComponents
import play.modules.reactivemongo.{ReactiveMongoApiFromContext, ReactiveMongoComponents}
import services.OauthProvider
import utils.{Mailer, Settings}


class MyApplicationLoader extends ApplicationLoader {
  def load(context: Context) = {
    LoggerConfigurator(context.environment.classLoader).foreach(_.configure(context.environment))
    new MyComponents(context).application
  }
}

class MyComponents(context: Context) extends ReactiveMongoApiFromContext(context)
  with I18nComponents
  with AhcWSComponents
  with MailerComponents
  with ReactiveMongoComponents {

  implicit val ec = actorSystem.dispatcher

  val settings = new Settings(configuration)
  val mailer = new Mailer(settings, mailerClient)

  val croissantDAO = new CroissantDAO(settings, mailer, reactiveMongoApi)
  val oauthProvider = new OauthProvider(settings, wsClient)
  //val gmailJob = new GmailJob(wsClient, actorSystem, settings, mailer, croissantDAO)

  lazy val router = new Routes(
    httpErrorHandler,
    new controllers.CroissantController(settings, messagesApi, mailer, croissantDAO),
    new controllers.AdminCroissantController(settings, messagesApi, mailer, croissantDAO),
    new controllers.OauthController(oauthProvider),
    new controllers.Assets(httpErrorHandler)
  )
} 
开发者ID:denis-mludek,项目名称:zencroissants,代码行数:44,代码来源:MyApplicationLoader.scala

示例2: Users

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

import javax.inject.Inject

import org.joda.time.DateTime
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Action, BodyParsers, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import repos.UserRepoImpl



class Users @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents{

  import models.UserFields._

  def userRepo = new UserRepoImpl(reactiveMongoApi)

  def create = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim Anlegen
    implicit request =>
      val name = (request.body \ Name).as[String]
      val password = (request.body \ Password).as[String]
      val email = (request.body \ EMail).as[String]
      userRepo.save(BSONDocument(
        Name -> name,
        Password -> password,
        EMail -> email,
        CreatedAt -> DateTime.now.toString
      )).map(result => Created("Created"))
  }

  def read(id: String) = Action.async{ implicit request =>
    userRepo.select(BSONDocument(Id -> BSONObjectID(id))).map(exercise => Ok(Json.toJson(exercise)))
  }


  def update(id: String) = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim updaten
    implicit request =>
      val name = (request.body \ Name).asOpt[String]
      val password = (request.body \ Password).asOpt[String]
      val email = (request.body \ EMail).asOpt[String]
      userRepo.update(BSONDocument( Id -> BSONObjectID(id)),
        BSONDocument("$set" -> BSONDocument(
          Name -> name,
          Password -> password,
          EMail -> EMail
      ))).map(result => Accepted)
  }

  def delete(id: String) = Action.async{
    userRepo.remove(BSONDocument(Id -> BSONObjectID(id))).map(result => Accepted("Deleted: "+ id ))
  }

} 
开发者ID:NorbertEbenhoeh,项目名称:projectX,代码行数:58,代码来源:Users.scala

示例3: Application

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

import javax.inject.{Inject, Singleton}

import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{Count, CountResult}
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._
import reactivemongo.bson.BSONDocument

import scala.concurrent.Future

@Singleton
class Application @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents {

  def index = Action {
    Logger.info("Application startup...")

    val posts = List(
      Json.obj(
        "name" -> "Widget One",
        "description" -> "My first widget",
        "author" -> "Justin"
      ),
      Json.obj(
        "name" -> "Widget Two: The Return",
        "description" -> "My second widget",
        "author" -> "Justin"
      ))

    val query = BSONDocument("name" -> BSONDocument("$exists" -> true))
    val command = Count(query)
    val result: Future[CountResult] = bsonCollection.runCommand(command)

    result.map { res =>
      val numberOfDocs: Int = res.value
      if (numberOfDocs < 1) {
        jsonCollection.bulkInsert(posts.toStream, ordered = true).foreach(i => Logger.info("Record added."))
      }
    }

    Ok("Your database is ready.")
  }

  def jsonCollection = reactiveMongoApi.db.collection[JSONCollection]("widgets")

  def bsonCollection = reactiveMongoApi.db.collection[BSONCollection]("widgets")

  def cleanup = Action {
    jsonCollection.drop().onComplete {
      case _ => Logger.info("Database collection dropped")
    }
    Ok("Your database is clean.")
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:62,代码来源:Application.scala

示例4: Application

//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.mvc.{ Action, Controller }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
import models._
import models.JsonFormats._

class Application @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller with MongoController with ReactiveMongoComponents {

  def getHotels = Action.async {
    db.collection("hotels").find(Json.obj()).cursor[Hotel]()
      .collect[List]().map {hotels => Ok(Json.toJson(hotels))}
  }

  def findByCityName(cityName : String) = Action.async {
    db.collection("hotels").find(Json.obj("city" -> cityName)).cursor[Hotel]()
        .collect[List]().map (hotels => Ok(Json.toJson(hotels)))
  }
} 
开发者ID:EmrysMyrddin,项目名称:WSHotels,代码行数:25,代码来源:Application.scala

示例5: MasterActor

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

import java.util.Date
import javax.inject.Inject

import akka.actor.Actor
import models.HourlyMessage
import play.api.libs.mailer.MailerClient
import play.api.libs.ws.WSClient
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.play.json.collection.JSONCollection
import play.api.libs.json.Json
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection.JSONCollection
import services.Counter

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


class MasterActor @Inject()(mailerClient: MailerClient, val reactiveMongoApi: ReactiveMongoApi, ws: WSClient,counter: Counter) extends Actor  with MongoController with ReactiveMongoComponents {
  override val database = reactiveMongoApi.connection.database("dummy")

  def receive = {

    case HourlyMessage(message) => {

      def patternFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("testdb"))
      val date = new Date()
      val _count = counter.nextCount().toString
      val _date = date.toString
      for{
        pattern <- patternFuture
        lastError <- pattern.insert(Json.obj("count"-> _count,"date" -> _date))
      }yield{
        //Ok("Mongo LastError: %s".format(lastError))
        println("count "+_count)
        var status = 0
        if(lastError.hasErrors){
          status = 0
        } else{
          status = 1
        }
        status
      }
     }

    }
} 
开发者ID:rahulkumar-aws,项目名称:akka-quartz-scheduler-example,代码行数:54,代码来源:MasterActor.scala

示例6: Application

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

import javax.inject.{Inject, Singleton}

import models._
import models.JsonFormats._
import org.slf4j.{Logger, LoggerFactory}
import play.api.libs.json.Json
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.modules.reactivemongo.json._
import reactivemongo.api.Cursor
import reactivemongo.play.json.collection.JSONCollection
import services.{UUIDGenerator,SimpleUUIDGenerator}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


@Singleton
class Application @Inject() (
                              val uuidGenerator: UUIDGenerator,
                              val reactiveMongoApi: ReactiveMongoApi
                            )
  extends Controller
    with MongoController
    with ReactiveMongoComponents
{

  private final val logger: Logger = LoggerFactory.getLogger(classOf[Application])

  def collection: JSONCollection = db.collection[JSONCollection]("greek")

  def index = Action.async {
    logger.info("Serving index page...")

    val cursor: Cursor[Sentence] = collection.
      // find all people with name `name`
      find(Json.obj("_id.scheme" -> "urn", "_id.namespace"->"cts", "_id.domain"->"greekLit", "_id.textgroup"->"tlg0003", "_id.work"->"tlg001", "_id.edition"->"perseus-grc1")).
      // perform the query and get a cursor of JsObject
      cursor[Sentence]

    // gather all the JsObjects in a list
    val futureUsersList: Future[List[Sentence]] = cursor.collect[List]()

    // everything's ok! Let's reply with the array
    futureUsersList.map { persons =>
      Ok(Json.toJson(persons))
    }
  }

  def randomUUID = Action {
    logger.info("calling UUIDGenerator...")
    Ok(uuidGenerator.generate.toString)
  }

} 
开发者ID:fbaumgardt,项目名称:manifold_,代码行数:58,代码来源:Application.scala

示例7: AuthController

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

import javax.inject._

import pdi.jwt.{Jwt, JwtSession}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.MongoAuthService

import scala.concurrent.Future


@Singleton
class AuthController @Inject()(val reactiveMongoApi: ReactiveMongoApi, val authService: MongoAuthService) extends Controller with MongoController with ReactiveMongoComponents {

  def get_token = Action.async(parse.json) { implicit request =>
    val emailOpt = (request.body \ "email").asOpt[String]
    val passwordOpt = (request.body \ "password").asOpt[String]
    (emailOpt, passwordOpt) match {
      case (Some(email), Some(password)) if !email.trim.isEmpty && !password.isEmpty =>
        for {
          idOpt <- authService.authenticate(email, password)
        } yield {
          idOpt.map {
            id =>
              var session = JwtSession()
              val user = Json.obj("user" -> Json.obj("_id" -> id, "email" -> email))
              session = session + user
              val token = session.serialize
              Ok(Json.obj("token" -> token))
          }.getOrElse(Ok(Json.obj()))
        }
      case _ => Future.successful(Ok(Json.obj()))
    }
  }

} 
开发者ID:sdor,项目名称:labnotes-server,代码行数:40,代码来源:AuthController.scala

示例8: PubmedController

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


import javax.inject._

import play.api.libs.json.{JsObject, Json}
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.PubmedService
import models.pubmed.SearchResult
import models.pubmed.schema.PubmedArticleSet

import scala.concurrent.Future

@Singleton
class PubmedController @Inject() (val reactiveMongoApi: ReactiveMongoApi,val pubmedService: PubmedService) extends Controller with MongoController with ReactiveMongoComponents with SecuredApi {

    def create_search_result = IfAuthentic.async(parse.json) { implicit request =>
      for {
        articleSetOpt <- pubmedService.createSearchResult(request.user.get,request.body.as[JsObject])
      } yield {
        Ok(Json.obj("article_set"->articleSetOpt))
      }
    }

    def find_search_result = IfAuthentic.async(parse.json) { implicit request =>
      val searchResultOpt = Json.fromJson[SearchResult](request.body).asOpt
      searchResultOpt.map {
        searchResult =>
          searchResult match {
            case SearchResult(Some(req),_,_,Some(year),Some(month),Some(day)) if req.isValid =>
              for {
                searchResultOpt <- pubmedService.findSearchResult(request.user.get,req,year,month,day)
              } yield {
                val articleSetOpt: Option[PubmedArticleSet] = searchResultOpt.map {
                  sr =>
                    sr.data.get.data.map {
                      xml =>
                        PubmedArticleSet.fromXML(scala.xml.XML.loadString(xml))
                    }
                }.flatten
                Ok(Json.obj(
                  "resp"->searchResultOpt.map(_.resp),
                  "article_set"->articleSetOpt
                ))
              }
            case _ =>  Future.successful(Ok(Json.obj()))
          }
      }.getOrElse{
        Future.successful(Ok(Json.obj()))
      }
    }
} 
开发者ID:sdor,项目名称:labnotes-server,代码行数:55,代码来源:PubmedController.scala

示例9: TranslatorController

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

import javax.inject.Inject

import Repositories.{TranslatorRepository, UserRepository}
import models.{Translator, User}
import play.api.libs.json.Json
import play.api.mvc.{Action, BodyParsers, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import utils.Pagination

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global


class TranslatorController @Inject()(val translatorService: TranslatorRepository, val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents {

  def getAllTranslators(page:Int, limit:Int, sort: String) = Action.async {implicit request =>

    val totalCount = Await.result(translatorService.count(), Duration.Inf)
    val pagination = new Pagination(page, limit, totalCount)
    translatorService.getAllTranslators(pagination, sort).map(translators => Ok(Json.obj("DATA" -> Json.toJson(translators), "PAGINATION" -> Json.toJson(pagination))))
  }

  def insertTranslator = Action.async(BodyParsers.parse.json) { implicit request =>
    val translatorObj = (request.body).as[Translator]
    translatorService.insertTranslator(translatorObj).map(result => Created)
  }
} 
开发者ID:sopheakreth,项目名称:rest-api-play-scala-mongodb,代码行数:33,代码来源:TranslatorController.scala

示例10: UserController

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

import javax.inject.Inject

import Repositories.UserRepository
import models.User
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import utils.Pagination

import scala.concurrent.Await
import scala.concurrent.duration._



class UserController @Inject()(val userService: UserRepository, val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents {

  def getAllUsers(page:Int, limit:Int, sort: String) = Action.async {implicit request =>

    val totalCount = Await.result(userService.count(), Duration.Inf)
    val pagination = new Pagination(page, limit, totalCount)
    userService.getAllUsers(pagination, sort).map(users => Ok(Json.obj("DATA" -> Json.toJson(users), "PAGINATION" -> Json.toJson(pagination))))
  }

  def getUserId(id: String) = Action.async { implicit request =>
    userService.getUserId(BSONDocument("_id" -> BSONObjectID(id))).map(user => Ok(Json.prettyPrint(Json.toJson(user))))
  }

  def insertUser = Action.async(BodyParsers.parse.json) { implicit request =>
    val userObj = (request.body).as[User]
    userService.insertUser(userObj).map(result => Created)
  }

  def updateUser(id: String) = Action.async(BodyParsers.parse.json) { implicit request =>
    val userObj = (request.body).as[User]
    userService.updateUser(BSONDocument("_id" -> BSONObjectID(id)), userObj).map(result => Accepted)
  }

  def deleteUser(id: String) = Action.async(BodyParsers.parse.json) { implicit request =>
    userService.deleteUser(BSONDocument("_id" -> BSONObjectID(id))).map(result => Accepted)
  }
} 
开发者ID:sopheakreth,项目名称:rest-api-play-scala-mongodb,代码行数:47,代码来源:UserController.scala

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

示例12: TweetController

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

import javax.inject._

import play.api.libs.json.{JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.modules.reactivemongo.json._
import reactivemongo.api.Cursor
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.BSONDocument
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{Count, CountResult}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._

@Singleton
class TweetController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller with MongoController with ReactiveMongoComponents {

  def jsonCollection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection]("tweets")
  def bsonCollection: BSONCollection = reactiveMongoApi.db.collection[BSONCollection]("tweets")

  import models._
  import models.TweetFormats._

  def findAll = Action.async {
    val cursor: Cursor[Tweet] = jsonCollection.find(Json.obj()).cursor[Tweet]()

    val futureTweetsList: Future[List[Tweet]] = cursor.collect[List]()

    val futureTweetsJsonArray: Future[JsValue] = futureTweetsList.map { tweets =>
      Json.toJson(tweets)
    }
    futureTweetsJsonArray.map { tweets =>
      Ok(tweets)
    }
  }

  def count = Action.async {
    val command = Count(BSONDocument.empty)
    val resultF: Future[CountResult] = bsonCollection.runCommand(command)
    resultF.map { res =>
      val numOfDocuments: Int = res.value
      Ok(Json.obj("numOfTweets" -> numOfDocuments))
    }
  }

} 
开发者ID:kkrzys,项目名称:presidential-elections-data-analysis-restapi,代码行数:52,代码来源:TweetController.scala

示例13: UserController

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

import javax.inject._

import play.api.libs.json.{JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.modules.reactivemongo.json._
import reactivemongo.api.Cursor
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.BSONDocument
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{Count, CountResult}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._

@Singleton
class UserController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller with MongoController with ReactiveMongoComponents {

  def jsonCollection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection]("users")
  def bsonCollection: BSONCollection = reactiveMongoApi.db.collection[BSONCollection]("users")

  import models._
  import models.UserFormats._

  def findAll = Action.async {
    val cursor: Cursor[User] = jsonCollection.find(Json.obj()).cursor[User]()

    val futureUsersList: Future[List[User]] = cursor.collect[List]()

    val futureUsersJsonArray: Future[JsValue] = futureUsersList.map { users =>
      Json.toJson(users)
    }
    futureUsersJsonArray.map { users =>
      Ok(users)
    }
  }

  def count = Action.async {
    val command = Count(BSONDocument.empty)
    val resultF: Future[CountResult] = bsonCollection.runCommand(command)
    resultF.map { res =>
      val numOfDocuments: Int = res.value
      Ok(Json.obj("numOfUsers" -> numOfDocuments))
    }
  }

} 
开发者ID:kkrzys,项目名称:presidential-elections-data-analysis-restapi,代码行数:52,代码来源:UserController.scala

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

示例15: Application

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

import javax.inject.{Inject, Singleton}

import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{ Count, CountResult }
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._
import reactivemongo.bson.BSONDocument

import scala.concurrent.Future

@Singleton
class Application @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
    with MongoController with ReactiveMongoComponents {

  def jsonCollection = reactiveMongoApi.db.collection[JSONCollection]("widgets");
  def bsonCollection = reactiveMongoApi.db.collection[BSONCollection]("widgets");

  def index = Action {
    Logger.info("Application startup...")

    val posts = List(
      Json.obj(
        "name" -> "Widget One",
        "description" -> "My first widget",
        "author" -> "Justin"
      ),
      Json.obj(
        "name" -> "Widget Two: The Return",
        "description" -> "My second widget",
        "author" -> "Justin"
      ))

    val query = BSONDocument("name" -> BSONDocument("$exists" -> true))
    val command = Count(query)
    val result: Future[CountResult] = bsonCollection.runCommand(command)

    result.map { res =>
      val numberOfDocs: Int = res.value
      if(numberOfDocs < 1) {
        jsonCollection.bulkInsert(posts.toStream, ordered = true).foreach(i => Logger.info("Record added."))
      }
    }

    Ok("Your database is ready.")
  }

  def cleanup = Action {
    jsonCollection.drop().onComplete {
      case _ => Logger.info("Database collection dropped")
    }
    Ok("Your database is clean.")
  }
} 
开发者ID:jrodenbostel,项目名称:getting-started-play-scala,代码行数:61,代码来源:Application.scala


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