本文整理汇总了Scala中play.api.mvc.BodyParsers类的典型用法代码示例。如果您正苦于以下问题:Scala BodyParsers类的具体用法?Scala BodyParsers怎么用?Scala BodyParsers使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BodyParsers类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: 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
示例2: KakeiboApiController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import dao.KakeiboJsonDataDao
import models.KakeiboJsonData
import play.api.libs.json.{JsError, Json}
import play.api.mvc.{Action, BodyParsers, Controller}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
class KakeiboApiController @Inject() (kakeiboJsonDataDao: KakeiboJsonDataDao) extends Controller{
import models.KakeiboJsonConvertImplicits._;
def saveItems = Action(BodyParsers.parse.json) { request =>
val result = request.body.validate[KakeiboJsonData]
result.fold(
errors => {
BadRequest(Json.obj("status" ->"KO", "message" -> JsError.toJson(errors)))
},
data => {
kakeiboJsonDataDao.insert(data)
Ok(Json.obj("status" ->"OK", "message" -> (" kakeibo json data is saved.") ))
}
)
}
def items = Action.async { request =>
kakeiboJsonDataDao.all.map(items => {
val json = Json.toJson(items)
Ok(json)
})
}
}
开发者ID:dikky1218,项目名称:kakeiboApi,代码行数:39,代码来源:KakeiboApiController.scala
示例3: MesaController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import models.Mesa
import play.api.libs.functional.syntax._
import play.api.libs.json._
import play.api.mvc.{Action, BodyParsers, Controller}
import services.MesaService
@Singleton
class MesaController @Inject()(mesaService: MesaService) extends Controller {
implicit val mesaWrites: Writes[Mesa] = (
(JsPath \ "numero").write[Int] and
(JsPath \ "nit").write[String] and
(JsPath \ "capacidad").write[Int]
) (unlift(Mesa.unapply))
implicit val mesaReads: Reads[Mesa] = (
(JsPath \ "numero").read[Int] and
(JsPath \ "nit").read[String] and
(JsPath \ "capacidad").read[Int]
) (Mesa.apply _)
def consultarMesasPorNit(nit: String) = Action {
val mesas = mesaService.consultarPorNit(nit)
val json = Json.toJson(mesas)
Ok(json)
}
def consultarMesa(numero: Int, nit: String) = Action {
val mesa = mesaService.alguno(numero, nit)
if (mesa != null)
Ok(Json.toJson(mesa))
else
NotFound(Json.obj("status" -> "NotFound", "message" -> ("No se encontro la mesa " + nit + "(" + numero + ")")))
}
def guardar = Action(BodyParsers.parse.json) { request =>
val placeResult = request.body.validate[Mesa]
placeResult.fold(
errors => {
BadRequest(Json.obj("status" -> "OK", "message" -> JsError.toJson(errors)))
},
mesa => {
mesaService.guardar(mesa)
Ok(Json.obj("status" -> "OK", "message" -> ("Mesa " + mesa.nit + "(" + mesa.numero + ") guardado.")))
}
)
}
}
开发者ID:dimerick,项目名称:startup-reserves,代码行数:53,代码来源:MesaController.scala
示例4: OwnersEndpoint
//设置package包名称以及导入依赖的类
package com.github.mszarlinski.playframework.petclinic.owners.port.adapters.rest
import javax.inject.{Inject, Singleton}
import com.github.mszarlinski.playframework.petclinic.owners.domain.{Owner, OwnerRepository}
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json._
import play.api.mvc.{Action, BodyParsers, Controller}
@Singleton
class OwnersEndpoint @Inject()(ownerRepository: OwnerRepository)(implicit ownerFormatter: OwnerFormatter) extends Controller {
def getOwners = Action {
val owners = ownerRepository.findAll()
Ok(toJson(owners))
}
def saveOwner = Action(BodyParsers.parse.json) { req =>
req.body.validate[Owner] match {// TODO: fold
case owner: JsSuccess[Owner] =>
val saved = ownerRepository.save(owner.get)
Ok(toJson(saved))
case _ => BadRequest
}
}
}
开发者ID:mszarlinski,项目名称:play-clinic,代码行数:28,代码来源:OwnersEndpoint.scala
示例5: WechatApplication
//设置package包名称以及导入依赖的类
package com.ddn.wechat.controller
import javax.inject.{Inject, Singleton}
import com.ddn.wechat.model.BaseWechatResponse
import com.ddn.wechat.service.{WechatMessageParser, WechatClient, WechatServer}
import play.api.mvc.{BodyParsers, Action, Controller}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
@Singleton
class WechatApplication @Inject()(wechatServer: WechatServer, wechatClient: WechatClient) extends Controller {
def validateWechatApp = Action {
implicit request =>
val signature = request.getQueryString("signature").getOrElse("")
val timestamp = request.getQueryString("timestamp").getOrElse("")
val nonce = request.getQueryString("nonce").getOrElse("")
val echoStr = request.getQueryString("echostr").getOrElse("")
Ok(if (wechatServer.validate(signature, timestamp, nonce)) echoStr else "")
}
def accessToken = Action {
Ok(wechatClient.getAccessToken)
}
def ipList = Action {
val ips = wechatClient.getIpList
println(ips)
Ok(ips.toString())
}
def handleMessage = Action.async(BodyParsers.parse.xml) {
implicit request => {
val message = WechatMessageParser.parse(request.body)
val future = wechatServer.handleMessage(message)
future.mapTo[BaseWechatResponse].map(response => Ok(response.toXml))
}
}
}
开发者ID:ivyy,项目名称:ddn-wechat,代码行数:40,代码来源:WechatApplication.scala
示例6: Auth
//设置package包名称以及导入依赖的类
package utils.auth.deadbolt
import javax.inject.{Inject, Singleton}
import be.objectify.deadbolt.scala.DeadboltActions
import com.mohiva.play.silhouette.api.Silhouette
import models.Roles
import play.api.mvc.{BodyParser, BodyParsers, Result, Results}
import utils.auth.DefaultEnv
import scala.concurrent.Future
@Singleton
class Auth @Inject()(deadboltActions: DeadboltActions, silhouette: Silhouette[DefaultEnv])
extends Results with BodyParsers {
def SubjectPresent[B](parser: BodyParser[B] = parse.anyContent)(block: SecureRequest[B] => Future[Result]) =
silhouette.SecuredAction.async(parser) { implicit req =>
deadboltActions.SubjectPresent()(parser)(block.compose(_ => new SecureRequest(req)))(req)
}
def Restrict[B](parser: BodyParser[B] = parse.anyContent)(role: Roles.Role)(block: SecureRequest[B] => Future[Result]) =
silhouette.SecuredAction.async(parser) { implicit request =>
deadboltActions.Restrict(role.group)(parser)(block.compose(_ => new SecureRequest(request)))(request)
}
}
开发者ID:dexmo007,项目名称:play-sil-seed-exp,代码行数:29,代码来源:Auth.scala
示例7: JsonFormats
//设置package包名称以及导入依赖的类
package utils.json
import java.sql.Timestamp
import java.util.UUID
import models.{ Prediction, TaggingImage }
import play.api.libs.json._
import play.api.mvc.{ BodyParser, BodyParsers }
object JsonFormats {
implicit object timestampFormat extends Format1653283475 {
def reads(json: JsValue) = {
JsSuccess(new Timestamp(json.as[Long]))
}
def writes(ts: Timestamp) = {
JsNumber(ts.getTime)
}
}
implicit val taggingImageFormat = Json.format[TaggingImage]
implicit object PredictionFormat extends Writes[Prediction] {
override def writes(o: Prediction): JsValue = Json.format[Prediction].writes(o) - ("imageId")
}
def writeImageswithPredicitions(images: Seq[TaggingImage], predicitions: Seq[Prediction]): JsValue = {
val predictionMap = scala.collection.mutable.HashMap.empty[UUID, scala.collection.mutable.MutableList[Prediction]]
predicitions.foreach(prediction => {
predictionMap.get(prediction.imageId) match {
case Some(list: scala.collection.mutable.MutableList[Prediction]) => list.+=(prediction)
case _ => predictionMap += ((prediction.imageId, scala.collection.mutable.MutableList(prediction)))
}
})
val imagesJson = images.map(image => {
val jImage = Json.toJson(image).as[JsObject]
predictionMap.get(image.imageId) match {
case Some(preds) => jImage.+(("predictions", Json.toJson(preds)))
case _ => jImage
}
}).seq
Json.toJson(imagesJson)
}
def writeImageswithPredictions(image: TaggingImage, predictions: Seq[Prediction]): JsValue = {
val jImage = Json.toJson(image).as[JsObject]
predictions.length match {
case l if l > 0 => jImage.+(("predictions", Json.toJson(predictions)))
case _ => jImage
}
}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
def validateJson[A: Reads]: BodyParser[A] = BodyParsers.parse.json.validate(
_.validate[A].asEither.left.map(e => play.api.mvc.Results.BadRequest(JsError.toJson(e)))
)
}
开发者ID:SwaggerTagger,项目名称:octo-tagger-backend,代码行数:57,代码来源:JsonFormats.scala
示例8: BrackenController
//设置package包名称以及导入依赖的类
package controllers.bracken
import javax.inject.Inject
import controllers.Actions
import models.store.StepAction
import models.{Message, UserMessage}
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import play.api.mvc.{BodyParsers, Controller}
import service.store.UserStepService
import utils.Slick
class BrackenController @Inject() (ws: WSClient) extends Controller with Actions with Slick{
def getInitKeyboard = StepAction.getFirstSteps.getKeyboard
def message = userAction(BodyParsers.parse.json) { implicit request =>
val (message,keyboard) = request.body.validate[UserMessage].fold(
errors => {
(Message("??? ?????"), getInitKeyboard)
},
userMessage => {
UserStepService.processStep(request.userStep, userMessage.content)
}
)
Ok(Json.obj("message" -> Json.toJson(message), "keyboard" -> Json.toJson(keyboard)))
}
def keyboard = LoggingAction {
Ok(Json.toJson(getInitKeyboard))
}
}
开发者ID:suya55,项目名称:kakaoYellowIdBot,代码行数:35,代码来源:brackenController.scala
示例9: 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
示例10: UrlInfoController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import io.swagger.annotations._
import models.{Resource, ResourceScore, Score}
import play.api.mvc.{Action, AnyContent, BodyParsers, Controller}
import play.api.cache.CacheApi
import play.api.libs.json._
@Singleton
@Api(value = "/urlinfo/1")
class UrlInfoController @Inject()(cacheApi: CacheApi) extends Controller {
import UrlInfoController._
private def urlDecode(url: String) = java.net.URLDecoder.decode(url, "UTF-8")
@ApiOperation(value = "Store a score for the URL.", response = classOf[ResourceScore])
@ApiResponses(Array(new ApiResponse(code = 400, message = "Bad Request")))
@ApiImplicitParams(Array(new ApiImplicitParam(name = "body", value = "the score to assign URL", required = true, dataType = "models.Score", paramType = "body",
examples = new Example(value = Array(new ExampleProperty(mediaType = "application/json", value = """{"score":0.9}"""))))))
def post(
@ApiParam(value = "host:port of URL to score") hostAndPort: String,
@ApiParam(value = "path of URL to score") originalPath: String
): Action[JsValue] = Action(BodyParsers.parse.json) { implicit request =>
val scoreResult = request.body.validate[Score]
scoreResult.fold(
errors => {
BadRequest(Json.obj("status" -> "error", "message" -> JsError.toJson(errors)))
},
score => {
val resource = Resource(hostAndPort, Option(urlDecode(originalPath)))
cacheApi.set(resource.toString, score.score)
Ok(Json.toJson(ResourceScore(resource, score.score)))
}
)
}
}
object UrlInfoController {
implicit val scoreFormats: OFormat[Score] = Json.format[Score]
implicit val resourceWrites: OWrites[Resource] = Json.writes[Resource]
implicit val resourceScoreWrites: OWrites[ResourceScore] = Json.writes[ResourceScore]
}
开发者ID:SkySchulz,项目名称:url-score,代码行数:46,代码来源:UrlInfoController.scala
示例11: Credentials
//设置package包名称以及导入依赖的类
package v1.session
import play.api.libs.json.{JsError, Json}
import play.api.mvc.{Action, BodyParsers, Controller}
import scala.util.Random
case class Credentials(username: String, password: String)
class SessionController extends Controller {
implicit val credentialsReads = Json.reads[Credentials]
def get(token: String) = Action { request =>
if (token.length() == 50) {
Ok(Json.obj("status" -> "OK"))
} else {
NotFound(Json.obj("errors" -> "Invalid token."))
}
}
def create = Action(BodyParsers.parse.json) { request =>
val credentialsResult = request.body.validate[Credentials]
credentialsResult.fold(
errors => {
BadRequest(Json.obj("errors" -> JsError.toJson(errors)))
},
credentials => {
if (credentials.username == "admin" && credentials.password == "password") {
Ok(Json.obj("token" -> Random.alphanumeric.take(50).mkString))
} else {
Unauthorized(Json.obj("errors" -> "Invalid username or password."))
}
}
)
}
}
开发者ID:yellow-bat,项目名称:assess-me-server,代码行数:38,代码来源:SessionController.scala
示例12: RoutesCtrl
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import models.Route
import play.api.libs.json.Json
import play.api.mvc.{Action, BodyParsers, Controller}
import repositories.RouteRepository
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class RoutesCtrl @Inject() (routeRepository: RouteRepository)
(implicit val ec: ExecutionContext) extends Controller {
def findAll = Action.async {
this.routeRepository.findAll() map (routes => Ok( Json.toJson(routes) ))
}
def save = Action.async(BodyParsers.parse.json) { request =>
request.body.validate[Route].fold(
_ => Future.successful(BadRequest( Json.obj("error" -> "invalid request") )),
route => this.routeRepository.save(route) map (route => Ok( Json.toJson(route) ))
)
}
def find(id: Long) = Action.async {
this.routeRepository.findById(id) map {
case Some(route) => Ok( Json.toJson(route) )
case _ => NotFound
}
}
def update(id: Long) = Action.async(BodyParsers.parse.json) { request =>
request.body.validate[Route].fold(
_ => Future.successful(BadRequest( Json.obj("error" -> "invalid request") )),
route => this.routeRepository.update(route) map (route => Ok( Json.toJson(route) ))
)
}
def remove(id: Long) = Action.async {
this.routeRepository.remove(id) map (if (_) Ok else NotFound)
}
}
开发者ID:viajobien,项目名称:busy-example,代码行数:47,代码来源:RoutesCtrl.scala
注:本文中的play.api.mvc.BodyParsers类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论