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

Scala current类代码示例

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

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



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

示例1: ContactUsController

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

import javax.inject.Inject

import model.ContactFormTemplate
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.Play.current
import play.api.data.validation._
import play.api.i18n.Messages.Implicits._
import services._

import scala.concurrent.Future

class ContactUsController @Inject()(validator: Validation) extends Controller  {

  val contactUsForm: Form[ContactFormTemplate] = Form(
    mapping(
      "name" -> nonEmptyText(maxLength = 20),
      "email" -> nonEmptyText(maxLength = 30).verifying(validator.emailCheckConstraint),
      "description" -> nonEmptyText(maxLength = 50)
    )(ContactFormTemplate.apply)(ContactFormTemplate.unapply)
  )

  def entry = Action {
    Ok(views.html.contact(contactUsForm))
  }

  def postForm = Action.async { implicit request =>
    println(request.body)
    contactUsForm.bindFromRequest.fold(
      formWithErrors => {
        Future.successful(BadRequest(views.html.contact(formWithErrors)))
      },
      UserData => {
        Future.successful(Redirect(routes.ContactUsController.success(UserData.name, UserData.email, UserData.description)))
      }
    )
  }

  def success(name: String, email: String, description: String) = Action {
    Ok(views.html.contactFormConfirmation(name, email, description))
  }
} 
开发者ID:ZDevelop94,项目名称:ZolvedIT,代码行数:46,代码来源:ContactUsController.scala


示例2: insert

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

import play.api.Play.current
import play.api.db.DB
import play.api.libs.concurrent.Execution.Implicits._
import slick.driver.PostgresDriver.api._

import scala.concurrent.Future

trait DAOComponent {

  def insert(employee: Employee): Future[Int]
  def update(id: Long, employee: Employee): Future[Int]
  def delete(id: Long): Future[Int]
  def list(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Future[Page[Employee]]
  def listActive(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Future[Page[Employee]]
  def listArchived(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Future[Page[Employee]]
  def findById(id: Long): Future[Employee]
  def count: Future[Int]

}

object DAO extends DAOComponent {

  private val employees = TableQuery[Employees]

  private def db: Database = Database.forDataSource(DB.getDataSource())

  
  override def listArchived(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Future[Page[Employee]] = {
    try {
      val offset = pageSize * page
      val query =
        (for {
          employee <- employees if (employee.name.toLowerCase like filter.toLowerCase) && (employee.status like "Archived")
        } yield (employee)).drop(offset).take(pageSize)
      val totalRows = count(filter)
      val result = db.run(query.result)
      result flatMap (employees => totalRows map (rows => Page(employees, page, offset, rows)))
    } finally { db.close() }
  }
} 
开发者ID:Harl0,项目名称:play-reactive-slick,代码行数:43,代码来源:DAO.scala


示例3: show

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

import com.google.inject.Inject
import models._
import play.api.mvc.{Controller, Action}
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import scala.concurrent.duration._
import scala.concurrent.Await


class [email protected]()(userRepo: UserRepo) extends Controller {

  def show = Action {
          val userList = Await.result(userRepo.getAll,2 second)
    //      val awardList =  Await.result(awardsRepo.getAll,2 second)
    //      val assignmentList = Await.result(assignmentRepo.getAll,2 second)
    //      val languageList = Await.result(languageRepo.getAll,2 second)
    //      val programminList = Await.result(programmingRepo.getAll,2 second)

    Ok(views.html.intern(userList))
  }
} 
开发者ID:aarwee,项目名称:PLAY-SLICK-DEEPTI-KUNAL-RISHABH,代码行数:24,代码来源:InternController.scala


示例4: AssignmentController

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

import com.google.inject.Inject
import models.Assignment
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import services.AssignmentServiceApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.Future
import play.api.i18n.Messages.Implicits._
import play.api.Play.current

class AssignmentController @Inject()(service:AssignmentServiceApi) extends Controller {
  val assigForm = Form(
    mapping(
      "id" -> number,
      "name" ->nonEmptyText,
      "marks"->number(),
      "remarks"->nonEmptyText
    )(Assignment.apply)(Assignment.unapply)
  )

  def list = Action.async { implicit request =>
    val list = service.getAssignment

    list.map {
      list => Ok("" + list)
    }
  }

  def listById=Action.async { implicit request =>
    val id=request.session.get("id").get.toInt
    service.getAssignmentById(id).map{ list => Ok(views.html.assignment(list.toList, assigForm))
    }
  }


} 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:40,代码来源:AssignmentController.scala


示例5: ProgLanguageController

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

import com.google.inject.Inject
import models.ProgLanguage
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import services.ProgLanguageApi
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.i18n.Messages.Implicits._
import play.api.Play.current

class ProgLanguageController @Inject()(service:ProgLanguageApi) extends Controller {
  val progLangForm = Form(
    mapping(
      "id" -> number,
      "name" ->nonEmptyText
    )(ProgLanguage.apply)(ProgLanguage.unapply)
  )

  def list = Action.async { implicit request =>
    val list = service.getProg()

    list.map {
      list => Ok("" + list)
    }
  }

  def listById=Action.async { implicit request =>
    val id=request.session.get("id").get.toInt
    service.getProgId(id).map{ list => Ok(views.html.proglanguage(list.toList,progLangForm))
    }
  }

  def add=Action.async{implicit request =>
    progLangForm.bindFromRequest.fold(
      // if any error in submitted data
      errorForm => Future.successful(Ok("success")),
      data => {
        val id:Int=request.session.get("id").get.toInt
        service.insertProg(id,data.name).map { res =>
          Redirect(routes.ProgLanguageController.listById)
        }
      })
  }


  def delete(name:String) = Action.async { implicit request =>
    val id:Int=request.session.get("id").get.toInt
    service.deleteProg(name) map { res =>
      Redirect(routes.ProgLanguageController.listById)
    }
  }



  } 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:59,代码来源:ProgLanguageController.scala


示例6: UserService

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

import java.util.UUID
import javax.inject._

import scala.concurrent.Future

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.services.IdentityService
import com.mohiva.play.silhouette.impl.providers.CommonSocialProfile

import play.api.Play.current
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json.collection.JSONCollection

import daos.UserDao
import models.{User,Profile}

class UserService @Inject() (userDao:UserDao) extends IdentityService[User] {
  def retrieve(loginInfo:LoginInfo):Future[Option[User]] = userDao.find(loginInfo)
  def save(user:User) = userDao.save(user)
  def find(id:UUID) = userDao.find(id)
  def confirm(loginInfo:LoginInfo) = userDao.confirm(loginInfo)
  def link(user:User, socialProfile:CommonSocialProfile) = {
    val profile = toProfile(socialProfile)
    if (user.profiles.exists(_.loginInfo == profile.loginInfo)) Future.successful(user) else userDao.link(user, profile)
  }

  def save(socialProfile:CommonSocialProfile) = {
    val profile = toProfile(socialProfile)
    userDao.find(profile.loginInfo).flatMap {
      case None => userDao.save(User(UUID.randomUUID(), List(profile)))
      case Some(user) => userDao.update(profile)
    }
  }

  private def toProfile(p:CommonSocialProfile) = Profile(
    loginInfo = p.loginInfo,
    confirmed = true,
    email = p.email,
    firstName = p.firstName,
    lastName = p.lastName,
    fullName = p.fullName,
    passwordInfo = None,
    oauth1Info = None,
    avatarUrl = p.avatarURL
  )
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:50,代码来源:UserService.scala


示例7: ExecutionContexts

//设置package包名称以及导入依赖的类
package context
import play.api.libs.concurrent.Akka
import play.api.Play.current



object ExecutionContexts {
  // 0-500 msecs
  implicit val genericOps = Akka.system.dispatchers.lookup("contexts.generic-ops")
  // 0-500 msecs
  implicit val criticalOps = Akka.system.dispatchers.lookup("contexts.critical-ops")

  // 1000 msecs-1 min
  implicit val slowIoOps = Akka.system.dispatchers.lookup("contexts.slow-io-ops")
  // More than 1 min
  implicit val slowCpuOps = Akka.system.dispatchers.lookup("contexts.slow-cpu-ops")
} 
开发者ID:emrekarakis,项目名称:TwitterProject,代码行数:18,代码来源:ExecutionContexts.scala


示例8: Users

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

import javax.inject._

import actors.{WebSockets, UsersArea}
import akka.actor._
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.JsValue
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.Future

@Singleton
class Users @Inject()(val messagesApi: MessagesApi, system: ActorSystem) extends Controller with I18nSupport {
  val User = "user"

  val nickForm = Form(single("nickname" -> nonEmptyText))

  def index = Action { implicit request =>
    request.session.get(User).map { user =>
      Redirect(routes.Users.chat()).flashing("info" -> s"Redirected to chat as $user user")
    }.getOrElse(Ok(views.html.index(nickForm)))
  }

  def name = Action { implicit request =>
    nickForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.index(formWithErrors))
      },
      nickname => {
        Redirect(routes.Users.chat())
          .withSession(request.session + (User -> nickname))
      }
    )
  }

  def leave = Action { implicit request =>
    Redirect(routes.Users.index()).withNewSession.flashing("success" -> "See you soon!")
  }

  def chat = Action { implicit request =>
    request.session.get(User).map { user =>
      Ok(views.html.chat(user))
    }.getOrElse(Redirect(routes.Users.index()))
  }

  def socket = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(User) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(WebSockets.props(uid))
    })
  }
} 
开发者ID:maltiyadav,项目名称:messaging-system-websockets,代码行数:57,代码来源:Users.scala


示例9: Bot

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

import scala.concurrent.duration._
import scala.concurrent.Await
import scala.util.{Failure, Success}

import play.api.Play.current
import play.api.libs.ws.WS


object Bot {

  def duck(qry: String): String = {
    val res = Await.ready(
      WS.url(s"http://api.duckduckgo.com/?format=json&q=$qry").get,
      5 seconds).value.get
    res match {
      case Success(wsResponse) => (wsResponse.json \\ "Text").head.toString.replace("\"", "")
      case Failure(ex) => ex.toString
    }
  }

  def parseInputGetOutput(input: String): String = {
    val words = "\\w+".r.findAllIn(input).toList
    words.head match {
      case "duck" => duck(words.tail.mkString("%20"))
      case x => duck(words.mkString("%20"))
    }
  }

} 
开发者ID:delqn,项目名称:botslandia,代码行数:32,代码来源:Bot.scala


示例10: ErrorHandler

//设置package包名称以及导入依赖的类
import play.api.{Logger, mvc}
import play.api.http.HttpErrorHandler
import play.api.mvc._
import play.api.mvc.Results._

import scala.concurrent._
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    val fullMessage = "An error occurred: " + statusCode + (if (message.nonEmpty) ", " + message else "")
    Logger.logger.error(fullMessage)
    Future.successful(
      Status(statusCode)(views.html.error(fullMessage))
    )
  }

  def onServerError(request: RequestHeader, exception: Throwable) = {
    Logger.logger.error("A server error occurred: " + exception.getMessage, exception)
    Future.successful(
      InternalServerError(views.html.error("A server error occurred: " + exception.getMessage))
    )
  }
} 
开发者ID:intracer,项目名称:wlxjury,代码行数:26,代码来源:ErrorHandler.scala


示例11: Chat

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

import javax.inject._

import actors.{UserSocket, ChatRoom}
import akka.actor._
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.JsValue
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.Future

@Singleton
class Chat @Inject()(val messagesApi: MessagesApi, system: ActorSystem) extends Controller with I18nSupport {
  val User = "user"

  val chatRoom = system.actorOf(Props[ChatRoom], "chat-room")

  val nickForm = Form(single("nickname" -> nonEmptyText))

  def index = Action { implicit request =>
    request.session.get(User).map { user =>
      Redirect(routes.Chat.chat()).flashing("info" -> s"Redirected to chat as $user user")
    }.getOrElse(Ok(views.html.index(nickForm)))
  }

  def nickname = Action { implicit request =>
    nickForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.index(formWithErrors))
      },
      nickname => {
        Redirect(routes.Chat.chat())
          .withSession(request.session + (User -> nickname))
      }
    )
  }

  def leave = Action { implicit request =>
    Redirect(routes.Chat.index()).withNewSession.flashing("success" -> "See you soon!")
  }

  def chat = Action { implicit request =>
    request.session.get(User).map { user =>
      Ok(views.html.chat(user))
    }.getOrElse(Redirect(routes.Chat.index()))
  }

  def socket = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(User) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(UserSocket.props(uid))
    })
  }
} 
开发者ID:onegrx,项目名称:playakkachat,代码行数:59,代码来源:Chat.scala


示例12: Global

//设置package包名称以及导入依赖的类
import scala.concurrent.ExecutionContext
import play.api._
import play.api.libs.json._
import play.modules.reactivemongo._
import play.modules.reactivemongo.json.collection.JSONCollection
import models._
import play.api.Play.current
import se.digiplant.imagemagick.plugin.IMPluginResAssets

object Global extends GlobalSettings with InitModels {

  override def onStart(app: Application) {
    initDB()
  }
}

trait InitModels {

  import ExecutionContext.Implicits.global

  def initDB() {
    val beachesFuture = Beach.collection.find(Json.obj()).cursor[JsObject].headOption
    beachesFuture.map { beach =>
      if (!beach.isDefined) {
        insertModels()
      }
    }
  }

  def insertModels() {
    // Create three beaches
    (1 to 3).map { i =>
      println(s"Saving beach $i")

      Beach.collection.insert(Beach(
        name = s"Beach $i",
        image = Image.fromPath(s"mockimages/beach$i.jpg", "default")
      ))
    }
  }
} 
开发者ID:digiPlant,项目名称:play-imagemagick,代码行数:42,代码来源:Global.scala


示例13: Global

//设置package包名称以及导入依赖的类
import play.api._
import models._
import akka.actor._
import play.api.libs.iteratee._
import play.api.libs.concurrent.Akka
import play.api.Play.current

object Global extends GlobalSettings {
  override def onStart(app: Application) {
    class Listener extends Actor {
      var out: Option[Concurrent.Channel[String]] = None
      def receive = {
        case Start(out)       => this.out = Some(out)
        case UserRegistration => this.out.map(_.push("user"))
        case NewMessage       => this.out.map(_.push("message"))
      }
    }
    val listener = Akka.system.actorOf(Props[Listener], "listener")
  }
} 
开发者ID:clrvynt,项目名称:sse,代码行数:21,代码来源:Global.scala


示例14: ControllerConfiguration

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fubenos3

import com.typesafe.config.Config
import play.api.{Application, Configuration, Play}
import uk.gov.hmrc.play.audit.filters.AuditFilter
import uk.gov.hmrc.play.auth.controllers.AuthParamsControllerConfig
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.http.logging.filters.LoggingFilter
import uk.gov.hmrc.play.microservice.bootstrap.DefaultMicroserviceGlobal
import uk.gov.hmrc.play.auth.microservice.filters.AuthorisationFilter
import net.ceedubs.ficus.Ficus._
import uk.gov.hmrc.play.filters.MicroserviceFilterSupport
import play.api.i18n.Messages.Implicits._
import play.api.Play.current


object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object AuthParamsControllerConfiguration extends AuthParamsControllerConfig {
  lazy val controllerConfigs = ControllerConfiguration.controllerConfigs
}

object MicroserviceAuditFilter extends AuditFilter with AppName with MicroserviceFilterSupport {
  override val auditConnector = MicroserviceAuditConnector
  override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}

object MicroserviceLoggingFilter extends LoggingFilter with MicroserviceFilterSupport {
  override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object MicroserviceAuthFilter extends AuthorisationFilter with MicroserviceFilterSupport {
  override lazy val authParamsConfig = AuthParamsControllerConfiguration
  override lazy val authConnector = MicroserviceAuthConnector
  override def controllerNeedsAuth(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuth
}

object MicroserviceGlobal extends DefaultMicroserviceGlobal with RunMode with MicroserviceFilterSupport {
  override val auditConnector = MicroserviceAuditConnector

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")

  override val loggingFilter = MicroserviceLoggingFilter

  override val microserviceAuditFilter = MicroserviceAuditFilter

  override val authFilter = Some(MicroserviceAuthFilter)
} 
开发者ID:hmrc,项目名称:fu-be-nos3,代码行数:51,代码来源:microserviceGlobal.scala


示例15: Application

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

import scala.Left
import scala.Right
import scala.concurrent.Future
import actors.UserActor
import play.api.Logger
import play.api.Play.current
import play.api.libs.json.JsValue
import play.api.mvc.Action
import play.api.mvc.Controller
import play.api.mvc.WebSocket

object Application extends Controller {
  val UID = "uid"
  var counter = 0;

  def index = Action { implicit request =>
    {
      val uid = request.session.get(UID).getOrElse {
        counter += 1
        counter.toString
      }
      Ok(views.html.index(uid)).withSession {
        Logger.debug("creation uid " + uid)
        request.session + (UID -> uid)
      }
    }
  }

  
  def ws = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(UID) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(UserActor.props(uid))
    })
  }

} 
开发者ID:OCervantes,项目名称:websocket-play,代码行数:40,代码来源:Application.scala


示例16: ProviderActor

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

import akka.actor.{Actor, Props}
import akka.pattern.pipe
import org.apache.commons.lang3.StringUtils._
import org.json4s._
import org.json4s.native.JsonMethods._
import play.api.Logger
import play.api.Play.current
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import uk.mm.mpp.actors.ProviderActor.{ProductRequest, ProductResponse}
import uk.mm.mpp.globals._

import scala.concurrent.ExecutionContext.Implicits.global

object ProviderActor {
  def props(uid: String, port: Int) = Props(classOf[ProviderActor], uid, port)

  case class ProductRequest()

  case class ProductResponse(products: JArray)

}

class ProviderActor(uid: String, port: Int) extends Actor {

  private lazy val request: WSRequest = WS.client.url(providerUrl)
    .withFollowRedirects(false)
    .withRequestTimeout(15000)

  val logger = Logger(MPP_WORKER_PREFIX + getClass.getSimpleName + "_" + uid + "_" + port)
  val providerUrl: String = "http://localhost:" + port + "/3rd/products"

  def receive = {
    case ProductRequest =>
      request.get()
        .map(productUpdateFrom)
        .recover(withEmptyJsonArray)
        .pipeTo(sender)
  }

  val withEmptyJsonArray: PartialFunction[Throwable, ProductResponse] = {
    case _ => ProductResponse(JArray(List()))
  }

  def productUpdateFrom(response: WSResponse): ProductResponse = if (response.status == 200) {
    logger.debug(s"from: [$providerUrl]: [${piedPiper(response)}]")
    ProductResponse(parseJsonFrom(response))
  } else {
    logger.warn(s"from: [$providerUrl]: [${response.body}]")
    ProductResponse(JArray(List()))
  }

  def piedPiper(response: WSResponse) = {
    abbreviate(replacePattern(response.body, """\s{2,}""", " "), 30)
  }

  def parseJsonFrom(response: WSResponse) = parse(response.body).asInstanceOf[JArray]
} 
开发者ID:mikemey,项目名称:mpp,代码行数:60,代码来源:ProviderActor.scala


示例17: PasswordInfoDao

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

import scala.concurrent.Future
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.PasswordInfo
import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO
import play.api.Play.current
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import models.User
import User._

class PasswordInfoDao extends DelegableAuthInfoDAO[PasswordInfo] {
  lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  val users = reactiveMongoApi.db.collection[JSONCollection]("users")

  def find(loginInfo:LoginInfo):Future[Option[PasswordInfo]] = for {
    user <- users.find(Json.obj(
      "profiles.loginInfo" -> loginInfo
    )).one[User]
  } yield user.flatMap(_.profiles.find(_.loginInfo == loginInfo)).flatMap(_.passwordInfo)

  def add(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] = {
    implicit val PasswordInfoFormat = Json.format[PasswordInfo]
    users.update(Json.obj(
      "profiles.loginInfo" -> loginInfo
    ), Json.obj(
      "$set" -> Json.obj("profiles.$.passwordInfo" -> authInfo)
    )).map(_ => authInfo)
  }

  def update(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] = 
    add(loginInfo, authInfo)

  def save(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] = 
    add(loginInfo, authInfo)

  def remove(loginInfo:LoginInfo):Future[Unit] = 
    users.update(Json.obj(
      "profiles.loginInfo" -> loginInfo
    ), Json.obj(
      "$pull" -> Json.obj(
        "profiles" -> Json.obj("loginInfo" -> loginInfo)
      )
    )).map(_ => ())
} 
开发者ID:k19862217,项目名称:book-shoes-api,代码行数:50,代码来源:PasswordInfoDao.scala


示例18: find

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

import java.util.UUID

import scala.concurrent.Future

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

import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection

import models.UserToken

trait UserTokenDao {
  def find(id:UUID):Future[Option[UserToken]]
  def save(token:UserToken):Future[UserToken]
  def remove(id:UUID):Future[Unit]
}

class MongoUserTokenDao extends UserTokenDao {
  lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  val tokens = reactiveMongoApi.db.collection[JSONCollection]("tokens")

  def find(id:UUID):Future[Option[UserToken]] = 
      tokens.find(Json.obj("id" -> id)).one[UserToken]

  def save(token:UserToken):Future[UserToken] = for {
    _ <- tokens.insert(token)
  } yield token
       
  def remove(id:UUID):Future[Unit] = for {
    _ <- tokens.remove(Json.obj("id" -> id))
  } yield ()
} 
开发者ID:k19862217,项目名称:book-shoes-api,代码行数:38,代码来源:UserTokenDao.scala


示例19: OAuth1InfoDao

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

import scala.concurrent.Future
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.OAuth1Info
import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO
import play.api.Play.current
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import models.User
import User._

class OAuth1InfoDao extends DelegableAuthInfoDAO[OAuth1Info] {
  lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  val users = reactiveMongoApi.db.collection[JSONCollection]("users")

  def find(loginInfo:LoginInfo):Future[Option[OAuth1Info]] = for {
    user <- users.find(Json.obj(
      "profiles.loginInfo" -> loginInfo
    )).one[User]
  } yield user.flatMap(_.profiles.find(_.loginInfo == loginInfo)).flatMap(_.oauth1Info)

  def add(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] = {
    implicit val OAuth1InfoFormat = Json.format[OAuth1Info]
    users.update(Json.obj(
      "profiles.loginInfo" -> loginInfo
    ), Json.obj(
      "$set" -> Json.obj("profiles.$.oauth1Info" -> authInfo)
    )).map(_ => authInfo)
  }

  def update(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] = 
    add(loginInfo, authInfo)

  def save(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] = 
    add(loginInfo, authInfo)

  def remove(loginInfo:LoginInfo):Future[Unit] = 
    users.update(Json.obj(
      "profiles.loginInfo" -> loginInfo
    ), Json.obj(
      "$pull" -> Json.obj(
        "profiles" -> Json.obj("loginInfo" -> loginInfo)
      )
    )).map(_ => ())
} 
开发者ID:k19862217,项目名称:book-shoes-api,代码行数:50,代码来源:OAuth1InfoDao.scala


示例20: Validation

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

import play.api.Play.current
import play.api.data.validation.ValidationError
import play.api.i18n.Messages
import play.api.i18n.Messages.Implicits._
import play.api.libs.json.Json._
import play.api.libs.json.{JsObject, JsPath, Json}
import play.api.mvc._

import scala.concurrent.Future


object Validation extends Controller {

  def validationError(code: Int)(errors: Seq[(JsPath, Seq[ValidationError])]): Future[Result] = {
    def messageFormat: JsObject = {
      errors.foldLeft(Json.obj()) { (obj, error) =>
        obj ++ Json.obj(error._1.toString().replaceFirst(Constants.Global.SLASH, Constants.Global.EMPTY_STRING) -> error._2.foldLeft(Json.arr()) { (arr, err) =>
          arr :+ Json.obj(Constants.Global.MESSAGE -> Messages(err.message, if (err.args.nonEmpty) err.args.head).toString)
        })
      }
    }
    Future.successful(BadRequest(obj(Constants.Global.STATUS -> code, Constants.Global.ERROR_MESSAGE -> messageFormat)))
  }
} 
开发者ID:satriapribadi,项目名称:satriapribadi.com,代码行数:27,代码来源:Validation.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Executors类代码示例发布时间:2022-05-23
下一篇:
Scala Source类代码示例发布时间: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