• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Cursor类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: HomeController

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

import javax.inject._

import org.slf4j.LoggerFactory
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.Cursor

import scala.concurrent.Future

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

  val logger = LoggerFactory.getLogger(this.getClass)

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

  def index = Action {
    Ok(views.html.index(""))
  }

  def query = Action.async { request =>
    val body = request.body
    val query = body.asFormUrlEncoded.get("query")

    val querySet = query.toSet[String]

    val keywords = querySet.flatMap({ string: String =>
      string.split(" ")
    })

    val searchQuery = Json.obj("keywords" -> Json.obj("$in" -> Json.toJson(keywords)))
    logger.info(s"Internal query from client: $searchQuery")
    val cursor: Cursor[JsObject] = collection.find(searchQuery).cursor[JsObject]

    val result: Future[List[JsObject]] = cursor.collect[List]()

    val resultJson: Future[JsValue] =
      result.map { persons => Json.toJson(persons) }

    resultJson.map { results =>
      val title = results \\ "title"
      val url = results \\ "url"
      val description = results \\ "body"
      val queryData: Seq[((JsValue, JsValue), JsValue)] = title.zip(url).zip(description)
      Ok(views.html.result(queryData))
    }
  }
} 
开发者ID:slideon,项目名称:Scrawler-frontend,代码行数:56,代码来源:HomeController.scala


示例2: ReactiveMongoExtensions

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

import reactivemongo.api.Cursor
import play.api.libs.json._
import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.BSONObjectID

object ReactiveMongoExtensions {

  implicit class ListExtensions[T](val futureList: Future[List[T]]) extends AnyVal {
    def toJsArray(implicit ec: ExecutionContext, writes: Writes[T]): Future[JsArray] = {
      futureList.map { futureList =>
        futureList.foldLeft(JsArray(List()))( (obj, item) => obj ++ Json.arr(item))
      }
    }
  }

  implicit class CursorExtensions[T](val cursor: Cursor[T]) extends AnyVal {
    def toJsArray(implicit ec: ExecutionContext, writes: Writes[T]): Future[JsArray] = {
      cursor.toList.toJsArray
    }
  }

  implicit class BSONObjectIdExtensions(val string: String) extends AnyVal {
    def toObjectID: BSONObjectID = BSONObjectID(string)
  }

} 
开发者ID:digiPlant,项目名称:play-imagemagick,代码行数:29,代码来源:ReactiveMongoExtensions.scala


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


示例4: nearPoint

//设置package包名称以及导入依赖的类
package io.soheila.commons.geospatials

import grizzled.slf4j.Logger
import io.soheila.commons.crud.MongoCRUDDAO
import io.soheila.commons.entities.{ Locatable, Page }
import io.soheila.commons.exceptions.{ ErrorCode, MongoDAOException, MongoExceptionBuilder }
import play.api.libs.json.{ Json, Reads }
import play.modules.reactivemongo.json._
import reactivemongo.api.indexes.Index
import reactivemongo.api.indexes.IndexType.Geo2DSpherical
import reactivemongo.api.{ Cursor, ReadPreference }

import scala.concurrent.{ ExecutionContext, Future }

trait Geospatial[T <: Locatable, ID] {
  self: MongoCRUDDAO[T, ID] =>

  private val logger = Logger[this.type]

  lazy val LocationField = "coordinate"

  lazy val geo2DSphericalIndex = Index(Seq((LocationField, Geo2DSpherical)), Some("geo2DSphericalIdx"))

  
  def nearPoint(lon: Double, lat: Double, minDistance: Double = 1, maxDistance: Double = 10000, page: Int = 0, limit: Int = 100, readPreference: ReadPreference = ReadPreference.primaryPreferred)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Either[MongoDAOException, Page[T]]] = {
    val offset = page * limit

    val totalCount = collection.flatMap(_.count())

    val searchResult = collection.flatMap(_.find(
      Json.obj(
        LocationField -> Json.toJson(Json.obj(
          "$geoNear" -> Json.toJson(Json.obj(
            "$geometry" -> Json.toJson(Json.obj(
              "type" -> "Point",
              "coordinates" -> Json.arr(lon, lat)
            )),
            "$maxDistance" -> Json.toJson(maxDistance),
            "$minDistance" -> Json.toJson(minDistance)
          ))
        ))
      )
    ).cursor[T](readPreference).collect[Seq](limit, Cursor.FailOnError((seq: Seq[T], err) => logger.error("Error finding locations.", err))))

    totalCount.zip(searchResult).map {
      case (total, entities) =>
        Right(Page(entities, page, offset, total))
    }.recover {
      case e => Left(MongoExceptionBuilder.buildException(e))
    }
  }

} 
开发者ID:esfand-r,项目名称:play-reactivemongo-commons,代码行数:54,代码来源:Geospatial.scala


示例5: MsgDAOImpl

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

import java.util.UUID
import javax.inject.{ Inject, Singleton }

import mikanMessages.InternalMsg
import play.api.Configuration
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{ Cursor, ReadPreference }
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection

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


@Singleton
class MsgDAOImpl @Inject() (playConf: Configuration, val reactiveMongoApi: ReactiveMongoApi) extends MsgDAO {

  private val msgCol: String = playConf.getString("mongo.collection.clientmsg").getOrElse("clientmsg")

  def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection(msgCol))

  def find(userID: UUID): Future[Option[InternalMsg]] =
    collection.flatMap(_.find(Json.obj("userID" -> userID)).one[InternalMsg])

  def save(msg: InternalMsg): Future[InternalMsg] = {
    collection.flatMap(_.insert(msg))
    Future.successful(msg)
  }
  // get all current msg filtered by topicList and userId
  // note: if userId="" all objects will be retrieved, otherwise
  // all msg BUT NOT those with the given userId
  def findAll(topicList: List[String], userID: UUID): Future[List[InternalMsg]] = {
    val qry = Json.obj("userID" -> Json.obj("$ne" -> userID), "topic" -> Json.obj("$in" -> topicList))
    for {
      colection <- collection
      theList <- colection.find(qry).
        cursor[InternalMsg](ReadPreference.nearest).
        collect[List](-1, Cursor.FailOnError[List[InternalMsg]]())
    } yield theList
  }

} 
开发者ID:workingDog,项目名称:golfmikan,代码行数:46,代码来源:MsgDAOImpl.scala


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


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


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


示例9: PlaceDAO

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

import javax.inject.Inject

import com.google.common.io.Files
import models.{Place, PlaceData}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.Files.TemporaryFile
import play.api.libs.json.Json
import play.api.mvc.Controller
import play.api.mvc.MultipartFormData.FilePart
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.{Cursor, ReadPreference}
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}

class PlaceDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)
                         (implicit ec: ExecutionContext)
    extends Controller with MongoController with ReactiveMongoComponents{
  def create(placeData: PlaceData, picture: FilePart[TemporaryFile]): Future[WriteResult] = {
    placesCollection.flatMap(_.insert(Place(placeData.name, placeData.country, placeData.description,
      Files.toByteArray(picture.ref.file))))
  }

  def all(): Future[List[Place]] = placesCollection.flatMap(_.find(Json.obj())
        .cursor[Place](ReadPreference.primaryPreferred).collect[List](Int.MaxValue, Cursor.FailOnError[List[Place]]()))

  def placesCollection: Future[JSONCollection] = database.map(_.collection[JSONCollection]("places"))
}


object PlaceDAO {
  val createPlaceForm = Form(
    mapping(
      "name" -> nonEmptyText,
      "country" -> nonEmptyText,
      "description" -> nonEmptyText
    )(PlaceData.apply)(PlaceData.unapply)
  )
} 
开发者ID:test410,项目名称:picture-gallery,代码行数:45,代码来源:PlaceDAO.scala


示例10: OcrRepository

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

import model.{OcrEntity, OcrTextOnly}
import reactivemongo.api.Cursor
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONRegex}

import scala.concurrent.Future

class OcrRepository extends MongoDao[OcrEntity] {

  lazy val collectionFuture: Future[BSONCollection] = dbFuture.map(db => db[BSONCollection]("ocr"))

  def save(ocrEntity: OcrEntity): Future[OcrEntity] = save(collectionFuture, ocrEntity)

  def deleteById(id: String): Future[WriteResult] = deleteById(collectionFuture, id)

  def findById(id: String): Future[Option[OcrEntity]] = find(collectionFuture, queryById(id))

  def findTextOnlyForUserId(userId: String, query: String): Future[List[OcrTextOnly]] =
    collectionFuture.flatMap(
      _.find(BSONDocument(
               "userId"      -> userId,
               "result.text" -> BSONRegex(query, "i")
             ),
             BSONDocument("result.text" -> 1))
        .cursor[OcrTextOnly]()
        .collect[List](-1, Cursor.FailOnError[List[OcrTextOnly]]()))
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:31,代码来源:OcrRepository.scala


示例11: DatabaseAccessor

//设置package包名称以及导入依赖的类
package me.lsbengine.database

import reactivemongo.api.{Cursor, DefaultDB}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.UpdateWriteResult
import reactivemongo.api.commands.WriteConcern
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}

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

class DatabaseAccessor[T](db: DefaultDB, collectionName: String) {

  def getCollection: BSONCollection = db[BSONCollection](collectionName)

  def getItems(query: BSONDocument = BSONDocument(), sort: BSONDocument = BSONDocument(), maxItems: Int = -1)(implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
    getCollection.find(query).sort(sort).cursor[T]().collect[List](maxDocs = maxItems, Cursor.DoneOnError[List[T]]())
  }

  def getItem(query: BSONDocument)(implicit reader: BSONDocumentReader[T]): Future[Option[T]] = {
    getCollection.find(query).one[T]
  }

  def upsertItem(selector: BSONDocument, item: T)(implicit writer: BSONDocumentWriter[T]): Future[UpdateWriteResult] = {
    getCollection.update(selector, item, WriteConcern.Acknowledged, upsert = true)
  }

  def updateItem(selector: BSONDocument, item: T)(implicit writer: BSONDocumentWriter[T]): Future[UpdateWriteResult] = {
    getCollection.update(selector, item, WriteConcern.Acknowledged, upsert = false)
  }
} 
开发者ID:jrabasco,项目名称:LSBEngine,代码行数:32,代码来源:DatabaseAccessor.scala


示例12: FileDAOImpl

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

import scala.annotation.implicitNotFound
import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.duration.Duration

import FileDAO.JSONReadFile
import javax.inject.Inject
import play.api.libs.json.JsObject
import play.api.libs.json.JsString
import play.api.libs.json.Json
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.modules.reactivemongo.MongoController.readFileReads
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.ReactiveMongoComponents
import reactivemongo.api.Cursor
import reactivemongo.api.gridfs.GridFS
import reactivemongo.play.json._
import play.api.libs.iteratee.Enumerator
import play.modules.reactivemongo.JSONFileToSave
import reactivemongo.api.gridfs.ReadFile
import play.api.Logger
import reactivemongo.api.commands.WriteResult
import models.AmlFiles
import reactivemongo.play.json.collection.JSONCollection


class FileDAOImpl @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) 
  extends FileDAO with ReactiveMongoComponents {
      
  private val asyncGridFS = reactiveMongoApi.asyncGridFS
  
  private def syncGridFS = Await.result(asyncGridFS, Duration("5s"))

  override def remove(uuid: String): Future[Boolean] = 
    asyncGridFS.flatMap(_.remove(JsString(uuid)).map { wr => wr.n == 1 })
        
  override def findByQuery(query: JsObject): Future[Cursor[JSONReadFile]] =
    asyncGridFS.map(_.find[JsObject, JSONReadFile](query))
    
  override def find(uuid: String): Future[Cursor[JSONReadFile]] = 
    asyncGridFS.map(_.find[JsObject, JSONReadFile](Json.obj("_id" -> JsString(uuid))))
    
  override def updateMetadata(fileUuid:String, metadata: JsObject): Future[Boolean] = 
    asyncGridFS.flatMap(_.files.update(Json.obj("_id" -> JsString(fileUuid)), 
        Json.obj("$set" -> Json.obj(AmlFiles.KeyMetadata -> metadata))).map(ur => ur.ok))
               
    
  override def save(enumerator: Enumerator[Array[Byte]], fileToSave: JSONFileToSave): Future[JSONReadFile] = {
    asyncGridFS.flatMap(_.save(enumerator, fileToSave))
  }
    
  override def withAsyncGfs[T](func: (GridFS[JSONSerializationPack.type] => Future[T])): Future[T] = asyncGridFS.flatMap(func(_))
  
  override def withSyncGfs[T](func: (GridFS[JSONSerializationPack.type] => T)): T = func(syncGridFS)
} 
开发者ID:MagnusAk78,项目名称:mogas,代码行数:59,代码来源:FileDAOImpl.scala


示例13: FileServiceImpl

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

import models.daos.FileDAO
import models.daos.FileDAO.JSONReadFile
import javax.inject.Inject
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
import reactivemongo.api.Cursor
import reactivemongo.api.gridfs.GridFS
import play.api.mvc.Result
import reactivemongo.play.json.JSONSerializationPack
import play.modules.reactivemongo.JSONFileToSave
import play.api.libs.json.JsObject
import utils.RemoveResult
import play.api.libs.iteratee._

class FileServiceImpl @Inject() (override val dao: FileDAO)(implicit val ec: ExecutionContext) extends FileService {

  override def remove(uuid: String): Future[RemoveResult] =
    dao.remove(uuid).map(success => if (success) {
      RemoveResult(true, None)
    } else {
      RemoveResult(false, Some("DAO refused to remove file: " + uuid))
    })

  override def findByQuery(query: JsObject): Future[Cursor[JSONReadFile]] = dao.findByQuery(query)

  override def find(uuid: String): Future[Cursor[JSONReadFile]] = dao.find(uuid)

  override def save(enumerator: Enumerator[Array[Byte]], fileToSave: JSONFileToSave): Future[JSONReadFile] = dao.save(enumerator, fileToSave)

  override def updateMetadata(fileUuid: String, metadata: JsObject): Future[Boolean] = dao.updateMetadata(fileUuid, metadata)

  override def withAsyncGfs[T](func: (GridFS[JSONSerializationPack.type] => Future[T])): Future[T] = dao.withAsyncGfs(func)

  override def withSyncGfs[T](func: (GridFS[JSONSerializationPack.type] => T)): T = dao.withSyncGfs(func)

  override def imageExists(uuid: String): Future[Boolean] = dao.findByQuery(models.Images.getQueryAllImages(uuid)).
    flatMap { cursor => cursor.headOption }.flatMap { opt =>
      opt.map(file => Future.successful(true)).
        getOrElse(Future.successful(false))
    }

  def videoExists(uuid: String): Future[Boolean] = dao.findByQuery(models.Videos.getQueryAllVideos(uuid)).
    flatMap { cursor => cursor.headOption }.flatMap { opt =>
      opt.map(file => Future.successful(true)).
        getOrElse(Future.successful(false))
    }
    
  def amlFiles(uuid: String): Future[List[JSONReadFile]] = {
    dao.findByQuery(models.AmlFiles.getQueryAllAmlFiles(uuid)).flatMap { c => c.toList(100, true) }
  }
} 
开发者ID:MagnusAk78,项目名称:mogas,代码行数:54,代码来源:FileServiceImpl.scala


示例14: Category

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

import com.google.inject.Singleton
import play.api.inject.Injector
import play.modules.reactivemongo.ReactiveMongoComponents
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection.JSONCollection

import scala.util.parsing.json.JSONArray
import scala.util.{Failure, Success, Try}

// Reactive Mongo imports
import javax.inject.Inject

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._

import scala.concurrent.Future

// Reactive Mongo imports
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.Cursor

// BSON-JSON conversions/collection
import reactivemongo.play.json._

class Category @Inject()(implicit val reactiveMongoApi: ReactiveMongoApi) extends MechanicCollection {

  private def collection: Future[JSONCollection] = {
    reactiveMongoApi.database.map(_.collection[JSONCollection]("categories"))
  }

  def getAll: Future[JsArray] = {
    collection flatMap { c: JSONCollection =>
      val cursor: Cursor[JsObject] = c.find(Json.obj()).cursor[JsObject](ReadPreference.primary)
      val list = cursor.collect[List]()
      list map { l => Json.arr(l) }
    }
  }

  
} 
开发者ID:jordancoded1,项目名称:mechanicfm-reactivemongo-api,代码行数:43,代码来源:Category.scala


示例15: Brand

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

import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection.JSONCollection

// Reactive Mongo imports
import javax.inject.Inject

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._

import scala.concurrent.Future

// Reactive Mongo imports
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.Cursor

// BSON-JSON conversions/collection
import reactivemongo.play.json._

class Brand @Inject()(implicit val reactiveMongoApi: ReactiveMongoApi) extends MechanicCollection {

  private def collection: Future[JSONCollection] = {
    reactiveMongoApi.database.map(_.collection[JSONCollection]("brands"))
  }

  def getAll: Future[JsArray] = {
    collection flatMap { c: JSONCollection =>
      val cursor: Cursor[JsObject] = c.find(Json.obj()).cursor[JsObject](ReadPreference.primary)
      val list = cursor.collect[List]()
      list map { l => Json.arr(l) }
    }
  }

} 
开发者ID:jordancoded1,项目名称:mechanicfm-reactivemongo-api,代码行数:36,代码来源:Brand.scala


示例16: DatabaseController

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

import javax.inject.Inject
import models.Employee
import play.api.libs.json.{JsError, JsValue, Json}
import play.api.mvc.{Action, Controller}
import reactivemongo.play.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.Cursor
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.play.json._
import scala.concurrent.Future

/**
  * Created by Orange on 21/06/2016.
  */

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

  def collection: JSONCollection = db[JSONCollection]("employees")

  implicit val modelFormat = Json.format[Employee]

  def addEmployee = Action { implicit request =>
    val jsonBody: Option[JsValue] = request.body.asJson
    jsonBody.map { json =>
      val employee = json.validate[Employee]
      employee.fold(errors => {
        BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))
      },
        employee => {
          collection.insert(employee) map {
            lastError =>
              Created
          }
          Ok(Json.obj("status" -> "OK", "message" -> ("User added into the system")))
        })
    }.getOrElse(BadRequest(Json.obj("status" -> "KO")))
  }

  def getAllEmployees = Action.async {
    val cursor: Cursor[Employee] = collection.find(Json.obj()).cursor[Employee]
    val futureEmployeesList: Future[List[Employee]] = cursor.collect[List]()
    futureEmployeesList.map(response => Ok(Json.toJson(response)))
  }
} 
开发者ID:MaithiliLabhe,项目名称:EmployeeDetailsApp,代码行数:48,代码来源:DatabaseController.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Stop类代码示例发布时间:2022-05-23
下一篇:
Scala Enumerator类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap