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

Scala JsError类代码示例

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

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



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

示例1: ApiController

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

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

import models.RestResource
import play.api.libs.json.{JsError, JsValue, Json}
import play.api.mvc._

import scala.concurrent.Future

@Singleton
class ApiController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index: Action[AnyContent] = {
    val resources = Seq(RestResource(UUID.randomUUID(), "name 1", "link 2"),
                        RestResource(UUID.randomUUID(), "name 2", "link 2"))
    Action.async {
      val json = Json.toJson(resources)
      Future.successful(Ok(json))
    }
  }

  def show(id: UUID): Action[AnyContent] = {
    Action.async {
      implicit request =>
        val json = Json.toJson(RestResource(id, "name x", "link x"))
        Future.successful(Ok(json))
    }
  }

  def process: Action[JsValue] = Action(parse.json) { implicit request =>
    request.body.validate[RestResource]
      .fold(
        errors =>
          BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors))),
        restResource => {
          println(restResource)
          Ok(Json.toJson(restResource))
        }
      )
  }

  def delete(id: String) = ???

  def update(id: String) = ???

} 
开发者ID:kamilduda,项目名称:play-hateoas,代码行数:49,代码来源:ApiController.scala


示例2: PermissionsViaHttpAuthorizer

//设置package包名称以及导入依赖的类
package auth.http.service.impl.authorization.impl

import auth.core.model.core.{Permission, PermissionToUser, User}
import auth.core.service.authorization.{PermissionAuthorization, PermissionsAuthorizer}
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import play.api.Configuration
import play.api.libs.json.{JsError, JsSuccess}
import play.api.libs.ws.WSClient
import play.api.mvc.Request

import scala.concurrent.{ExecutionContext, Future}
import play.api.Logger


class PermissionsViaHttpAuthorizer(configuration: Configuration, ws: WSClient)(
    implicit ec: ExecutionContext)
    extends PermissionsAuthorizer {
  import auth.core.formatting.core.Rest._

  private val logger   = Logger(this.getClass)
  private val endpoint = configuration.underlying.getString("auth.http.user-service.url")
  private def uri(uuid: String): String = s"$endpoint/users/$uuid/permissions"

  override def require(required: Permission): PermissionAuthorization[JWTAuthenticator] =
    new PermissionAuthorization[JWTAuthenticator] {
      override def isAuthorized[B](identity: User, authenticator: JWTAuthenticator)(
          implicit request: Request[B]): Future[Boolean] = {
        val endpoint = uri(identity.uuid.toString)

        val f = ws.url(endpoint).get().map { resp ?
          val permissions = resp.json.validate[Seq[PermissionToUser]]
          permissions match {
            case JsSuccess(ps, _) ?
              ps.map(_.permission).contains(required)
            case JsError(e) ?
              logger.error(e.mkString("\n"))
              false
          }
        }
        logError(f, endpoint)
        f
      }
    }

  @inline private def logError[A](f: Future[_], endpoint: String): Unit =
    f.onFailure {
      case e: Throwable ?
        logger.error(s"Error during request to $endpoint", e)
    }
} 
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:51,代码来源:PermissionsViaHttpAuthorizer.scala


示例3: PreprocessedFromStringUnmarshaller

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl

import akka.http.scaladsl.marshallers.playjson.PlayJsonSupport.PlayJsonError
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.server.{RejectionError, ValidationRejection}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, FromStringUnmarshaller, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json.{JsError, JsValue, Json, Reads}

class PreprocessedFromStringUnmarshaller[T](sanitize: Preprocess[String], _fsu: FromStringUnmarshaller[T]) {
  implicit val fsu: FromStringUnmarshaller[T] = Unmarshaller withMaterializer {
    implicit ec =>
      implicit mat =>
        string =>
          _fsu(sanitize(string))
  }
}

object PreprocessedFromStringUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[String] = Preprocess.identity, fsu: FromStringUnmarshaller[T]): PreprocessedFromStringUnmarshaller[T] = {
    new PreprocessedFromStringUnmarshaller(sanitize, fsu)
  }
}

class PreprocessedFromEntityUnmarshaller[T](sanitize: Preprocess[JsValue], reads: Reads[T]) {
  private val jsonStringUnmarshaller =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset)       => data.decodeString(charset.nioCharset.name)
      }

  implicit val fsu: FromEntityUnmarshaller[T] = jsonStringUnmarshaller map { data =>
    val json = sanitize(Json parse data)

    reads reads json recoverTotal { error =>
      throw RejectionError(ValidationRejection(JsError.toJson(error).toString, Some(PlayJsonError(error))))
    }
  }
}

object PreprocessedFromEntityUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[JsValue] = Preprocess.identity, reads: Reads[T]): PreprocessedFromEntityUnmarshaller[T] = {
    new PreprocessedFromEntityUnmarshaller(sanitize, reads)
  }
}

trait Preprocess[T] {
  def apply(x: T): T
}
object Preprocess {
  def identity[T]: Preprocess[T] = new Preprocess[T] {
    override def apply(x: T): T = x
  }
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:57,代码来源:Preprocess.scala


示例4: AuthenticatedRequest

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

import java.util.UUID
import javax.inject.Inject

import models.Account
import pdi.jwt.{JwtAlgorithm, JwtJson}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc._
import repositories.AccountRepository
import utils.{Conf, Log}

import scala.concurrent.Future
import scala.util.{Failure, Success}

case class AuthenticatedRequest[A](account: Account, request: Request[A]) extends WrappedRequest[A](request)

class AuthenticationActionService @Inject()(conf: Conf, accountRepository: AccountRepository) extends Log {
  val key = conf.cryptoKey

  object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] {
    override def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
      val errorResponse = Json.obj("error" -> "Unauthorized")
      request.headers.get("Authorization")
      .orElse(request.getQueryString("token"))
      .orElse(request.cookies.get("token").map(_.value))
      .orElse(request.session.get("token")) match {
        case Some(token) =>
          logger.debug(s"${request.toString()} Authorization=$token")
          JwtJson.decodeJson(token, key, Seq(JwtAlgorithm.HS256)) match {
            case Success(json) =>
              (json \ "user_id").validate[UUID] match {
                case s: JsSuccess[UUID] =>
                  accountRepository.getByUUID(s.get) match {
                  case Some(user) =>
                    logger.debug(s"${request.toString()} user=$user")
                    block(AuthenticatedRequest(user, request))
                  case None =>
                    logger.error(s"Unauthorized: User not found with id=${s.get}")
                    Future.successful(Results.Unauthorized(errorResponse))
                  }
                case e: JsError =>
                  logger.error(s"Unauthorized: Jwt decode Json error $e")
                  Future.successful(Results.Unauthorized(errorResponse))
              }
            case Failure(e) =>
              logger.error(s"Unauthorized: Jwt decode Json error", e)
              Future.successful(Results.Unauthorized(errorResponse))
          }
        case None =>
          logger.error(s"Unauthorized: Missing token in Authorization header | cookies | session | query string")
          Future.successful(Results.Unauthorized(errorResponse))
      }
    }
  }
} 
开发者ID:Cumulus-Cloud,项目名称:cumulus,代码行数:57,代码来源:AuthenticationActionService.scala


示例5: ReceivedMessageConverters

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

import com.amazonaws.services.sqs.model.Message
import domain.common.{ MessageToken, ProcessableMessage, ReceivedMessage, UnprocessableMessage }
import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }

object ReceivedMessageConverters {

  def toReceivedMessage[T](message: Message)(implicit reads: Reads[T]): ReceivedMessage[T] = {
    val json = Json.parse(message.getBody)
    val result = Json.fromJson(json)
    val token = MessageToken(message.getReceiptHandle)
    result match {
      case JsSuccess(t, _) => ProcessableMessage(t, token)
      case JsError(e) =>
        val errorMessage = s"messageId: ${ message.getMessageId }, reason: ${ Json.stringify(JsError.toJson(e)) }"
        UnprocessableMessage(new IllegalArgumentException(errorMessage), token)
    }
  }
} 
开发者ID:cm-wada-yusuke,项目名称:ecn-news,代码行数:21,代码来源:ReceivedMessageConverters.scala


示例6: OAuth2Success

//设置package包名称以及导入依赖的类
package org.zalando.hutmann.authentication

import play.api.Logger
import play.api.libs.json.{ JsError, JsSuccess, JsValue }

trait OAuth2Response

final case class OAuth2Success[T <: OAuth2User](user: T) extends OAuth2Response
final case class OAuth2Failure[T <: OAuth2Error](failure: T) extends OAuth2Response

object OAuth2Response {
  implicit val userFormat = User.app2AppUserReader
  implicit val errorFormat = AuthError.format

  def fromJson(json: JsValue): OAuth2Response = {
    json.validate[User] match {
      case JsSuccess(user, _) => OAuth2Success(user)
      case JsError(error) =>
        json.validate[AuthError] match {
          case JsSuccess(failure, _) => OAuth2Failure(failure)
          case JsError(fail) =>
            Logger.warn("Failed to parse oauth response from auth server")
            OAuth2Failure(AuthError("Parser failed", "Failed to parse response from OAuth server."))
        }
    }
  }
} 
开发者ID:zalando-incubator,项目名称:hutmann,代码行数:28,代码来源:OAuth2Response.scala


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


示例8: DockerEnvironment

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

import java.nio.file.{Files, Paths}

import codacy.dockerApi.api.CodacyConfiguration
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, Json}

import scala.util.{Failure, Success, Try}

object DockerEnvironment {

  def config: Try[CodacyConfiguration] = Try(Files.readAllBytes(configFilePath)).transform(
    raw => Try(Json.parse(raw)).flatMap(
      _.validate[CodacyConfiguration].fold(
        asFailure,
        conf => Success(conf)
      )),
    error => Failure(error)
  )

  private[this] def asFailure(error: Seq[(JsPath, Seq[ValidationError])]) =
    Failure(new Throwable(Json.stringify(JsError.toFlatJson(error.toList))))

  private[this] lazy val configFilePath = sourcePath.resolve(".codacyrc")

  lazy val sourcePath = Paths.get("/src")
} 
开发者ID:codacy,项目名称:codacy-duplication-scala-seed,代码行数:29,代码来源:DockerEnvironment.scala


示例9: SprayHttpResponse

//设置package包名称以及导入依赖的类
package mesosphere.marathon.integration.setup

import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }
import spray.http.HttpResponse

import scala.reflect.ClassTag

object SprayHttpResponse {
  def read[T](implicit reads: Reads[T], classTag: ClassTag[T]): HttpResponse => RestResult[T] = responseResult.andThen { result =>
    result.map(_ => Json.fromJson(result.entityJson)).map {
      case JsSuccess(value, _) => value
      case JsError(errors) =>
        throw new IllegalArgumentException(
          s"could not parse as $classTag:\n${Json.prettyPrint(result.entityJson)}\nErrors:\n${errors.mkString("\n")}")
    }
  }
  def responseResult: HttpResponse => RestResult[HttpResponse] = response => RestResult(response)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:19,代码来源:SprayHttpResponse.scala


示例10: index

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

import javax.inject._

import dao.UserDAO
import models.{Bad, User}
import play.api.mvc._
import play.api.libs.json.{JsError, JsSuccess, Json, _}
import play.api.Mode
import system.MyExecutionContext

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



  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
implicit val userformat = Json.format[User]


  def create = Action.async(parse.json) { implicit request =>
    val validationResult: JsResult[User] = request.body.validate[User]
      validationResult match {
        case r: JsSuccess[User] =>
          val user:User=r.get
         val futureLong : Future[Long] =  userDAO.insert(user)
          futureLong.map{
            result => Ok("success")
          }
        case r: JsError =>
          scala.concurrent.Future {
            val errors = JsError.toJson(r)
            Ok(Json.toJson(Bad(Some(430), "bad.request", data = errors)))
          }
      }
  }


  def getAll = Action.async { implicit rs =>
    val users : Future[Seq[User]] =  userDAO.all()
    users.map(u => Ok(Json.toJson(u)))
  }



  def deleteUser(id:Long) = Action.async {  implicit request =>
      userDAO.delete(id).map(num => Ok(Json.toJson(num)))
  }


  def getById(id:Long) =Action.async{  implicit request =>
    userDAO.findById(id).map(num => Ok(Json.toJson(num)))
  }

} 
开发者ID:sarathraj-coder,项目名称:play2_6curd_rest,代码行数:59,代码来源:HomeController.scala


示例11: jsonException

//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.errors

import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, JsValue, Json}

trait JsonError {
  def jsonException(message: String, exception: Exception = new Exception): JsValue = {
    Json.obj(
      "error" -> message,
      "details" -> Json.obj(
        "exception_class" -> exception.getClass.toString,
        "message" -> exception.toString
      )
    )
  }

  def jsonError(message: String): JsValue = Json.obj(
    "error" -> message
  )

  def jsonValidationError(message: String, errors: Seq[(JsPath, Seq[ValidationError])]): JsValue = {
    Json.obj("error" -> message, "details" -> JsError.toJson(errors))
  }
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:25,代码来源:JsonError.scala


示例12: BackPropagationService

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

import javax.inject.Inject

import play.api.libs.json.{JsError, Json}
import play.api.mvc._
import se.andrisak.backprop.algo.BackPropagationAlgo
import se.andrisak.backprop.rest.model.ClassificationRequest.ClassificationInput
import se.andrisak.backprop.rest.model.ClassificationResponse.Classification

import scala.util.Random


class BackPropagationService @Inject()(random: Random) extends Controller {
  def classify = Action(BodyParsers.parse.json) { request =>
    val r = request.body.validate[ClassificationInput]

    r.fold(
      errors => {
        BadRequest(Json.obj("message" -> JsError.toJson(errors)))
      },
      classification => {
        val iterations = classification.valuesToClassify.iterations
        val trainingData = classification.trainingData
        val bp = new BackPropagationAlgo(random)
        val firstInput = classification.valuesToClassify.firstInput
        val secondInput = classification.valuesToClassify.secondInput
        val output = bp.classify(iterations, trainingData, List(firstInput, secondInput))

        Ok(Json.toJson(Classification(firstInput, secondInput, output)))
      })
  }
} 
开发者ID:andrisak,项目名称:backprop,代码行数:34,代码来源:BackPropagationService.scala


示例13: getUserInfo

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

import com.google.inject.{ImplementedBy, Inject, Singleton}
import org.apache.http.HttpStatus
import play.api.Logger
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.libs.ws.WSClient
import services.endpoints.GOAuthEndpoints
import services.exceptions.ParseException
import services.models.UserInfo
import services.status.{AuthFailure, LoginStatus, LoginSuccess}

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

@ImplementedBy(classOf[GOAuthServicesImpl])
trait OAuthServices {
  def getUserInfo(accessToken: String): Future[LoginStatus[UserInfo]]
}

@Singleton
class GOAuthServicesImpl @Inject()(gOAuthEndpoints: GOAuthEndpoints, wsClient: WSClient) extends OAuthServices {
  override def getUserInfo(accessToken: String): Future[LoginStatus[UserInfo]] = {
    wsClient.url(gOAuthEndpoints.userInfoURL(accessToken)).get().flatMap { wsResponse =>
      val status = wsResponse.status
      if (status == HttpStatus.SC_OK) {
        Logger.info(s"""response body as string: ${wsResponse.body}""")
        val payload = Json.parse(wsResponse.body)
        payload.validate[UserInfo] match {
          case JsSuccess(userInfo, _) => Future.successful(LoginSuccess(userInfo))
          case [email protected](errors) => Future.failed(ParseException(s"Errors while parsing the json payload into user info object: ${errors.mkString(" ")}"))
        }
      } else if (status == HttpStatus.SC_UNAUTHORIZED) {
        Future.successful(AuthFailure)
      } else {
        Future.failed(new Exception("Unknown http status: " + status))
      }
    }
  }
} 
开发者ID:pamu,项目名称:blog,代码行数:41,代码来源:OAuthServices.scala


示例14: isAjax

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

import play.api.http.{Writeable, ContentTypes, ContentTypeOf}
import play.api.libs.json.JsError
import play.api.mvc.{Request, Codec}
import scala.concurrent.ExecutionContext.Implicits.global

object `package` {

  def isAjax[A](implicit request : Request[A]) = request.headers.get("X-Requested-With").contains("XMLHttpRequest")

  implicit def contentTypeOf_Throwable(implicit codec: Codec): ContentTypeOf[Throwable] =
    ContentTypeOf[Throwable](Some(ContentTypes.TEXT))

  implicit def writeableOf_Throwable(implicit codec: Codec): Writeable[Throwable] = {
    Writeable(e => e.getMessage.getBytes("utf-8"))
  }

  implicit def contentTypeOf_JsError(implicit codec: Codec): ContentTypeOf[JsError] =
    ContentTypeOf[JsError](Some(ContentTypes.JSON))

  implicit def writeableOf_JsError(implicit codec: Codec): Writeable[JsError] = {
    Writeable(e => JsError.toJson(e).toString.getBytes("utf-8"))
  }
} 
开发者ID:gurghet,项目名称:rota-scalajs,代码行数:26,代码来源:package.scala


示例15: TagController

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

import dao.TagDao
import models.Tag
import play.api.libs.json.{Json, JsError}
import play.api.mvc.{Action, Controller}

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

class TagController(tagDao: TagDao, auth: SecuredAuthenticator) extends Controller {

  def index = Action.async { request =>
    tagDao.findAll().map { tags =>
      Ok(Json.toJson(tags))
    }
  }

  def create = auth.JWTAuthentication.async(parse.json) { request =>
    val tagResult = request.body.validate[Tag]
    tagResult.fold(
      valid = { t =>
        val tag = tagDao.add(t)
        tag.map(t => Created(Json.toJson(t))).recoverWith {
          case _ => Future { InternalServerError}
        }
      },
      invalid = { errors =>
        Future.successful(
          BadRequest(JsError.toJson(errors))
        )
      }
    )
  }

  def destroy(id: Long) = auth.JWTAuthentication.async { request =>
    tagDao.remove(id).map(tag => Ok(s"Tag with id: ${id} removed")).recoverWith {
      case _ => Future { NotFound }
    }
  }
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:42,代码来源:TagController.scala


示例16: WordController

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

import com.google.inject.Inject
import model.dto.RawWordRestIn
import play.api.Logger
import play.api.libs.json.JsError
import play.api.mvc._
import service.{RawWordRequestService, WordService}


class WordController @Inject()(requestService: RawWordRequestService, wordService: WordService) extends Controller {

  def add = Action(BodyParsers.parse.json) { implicit request =>
    Logger.debug("{ADD} save request")
    requestService.save(request.body)

    Logger.debug("{ADD} validate and parse body from request")
    request.body.validate[RawWordRestIn].fold(
      errors =>
        BadRequest(JsError.toJson(errors)),
      word => {
        wordService.add(word.word)
        Created
      }
    )
  }
} 
开发者ID:proshik,项目名称:scala-play-app-demo,代码行数:28,代码来源:WordController.scala


示例17: RawWordController

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

import javax.inject.Inject

import model.RawWord
import model.ywordmodel.YTranslateWord
import play.api.libs.json.{JsError, Json}
import play.api.mvc._
import services.TranslateService

import scala.concurrent.Future

class RawWordController @Inject()(translateService: TranslateService) extends Controller {

  def add = Action.async(BodyParsers.parse.json) { implicit request =>
    request.body.validate[RawWord].fold(
      errors =>
        Future.successful(BadRequest(JsError.toJson(errors))),
      word =>
        Future.successful(Ok(Json.toJson(translateService.translate(word))))
    )
  }

  def addTranslate() = Action.async(BodyParsers.parse.json) { implicit request =>
    request.body.validate[YTranslateWord].fold(
      errors =>
        Future.successful(BadRequest(JsError.toJson(errors))),
      word =>
        Future.successful(Ok(Json.toJson(word)))
    )
  }

} 
开发者ID:proshik,项目名称:scala-play-slick-demo,代码行数:34,代码来源:RawWordController.scala


示例18: TaskController

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

import akka.actor.Status.Success
import models.{Tasks, Task}
import play.api.Play
import play.api.libs.json.{JsPath, Reads, JsError}
import play.api.libs.functional.syntax._
import play.api.mvc._

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


class TaskController extends Controller {

  implicit val locationReads: Reads[Task] = (
    (JsPath \ "id").read[Long] and
      (JsPath \ "title").read[String]
    )(Task.apply _)

  def index = Action.async { implicit request =>
    Tasks.all.map { users =>
      Ok(views.html.tasks(users))
    }
  }

  def create = Action(parse.json) { implicit request =>
    request.body.validate[Task].map {
      case Task(i, t) => {
        Tasks.add(new Task(i, t))
        Redirect(routes.TaskController.index)
      }
    }.recoverTotal {
      e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
    }
  }

  def read = TODO

  def update = TODO

  def delete = TODO

} 
开发者ID:nmoniz,项目名称:fokus-server,代码行数:45,代码来源:TaskController.scala


示例19: Application

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

import com.google.inject.Inject
import dao._
import models.{Cat, Dog}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc._

import scala.concurrent.Future

class Application @Inject() (catDao: CatDAO, dogDao: DogDAO) extends Controller {

  def info = Action { implicit request =>
    ???
  }

  def findAllAnimals = Action.async { implicit request =>
    catDao.all().zip(dogDao.all()).map {
      case (cats, dogs) =>
        val catsJson = Json.toJson(cats)
        val dogsJson = Json.toJson(dogs)
        Ok(Json.obj(
          "cats" -> catsJson,
          "dogs" -> dogsJson
        ))
    }
  }

  def insertCat = Action.async(parse.json) { implicit request =>
    request.body.validate[Cat] match {
      case JsSuccess(cat, path) =>
        catDao.insert(cat).map(_ => Ok(Json.obj("msg" -> "Cat was inserted")))

      case JsError(err) =>
        Future.successful(BadRequest(Json.obj("msg" -> err.mkString("\n"))))
    }
  }

  def insertDog = Action.async(parse.json) { implicit request =>
    request.body.validate[Dog] match {
      case JsSuccess(dog, path) =>
        dogDao.insert(dog).map(_ => Ok(Json.obj("msg" -> "Dog was inserted")))

      case JsError(err) =>
        Future.successful(BadRequest(Json.obj("msg" -> err.mkString("\n"))))
    }
  }

} 
开发者ID:kpmeen,项目名称:play-slick-pgsql,代码行数:51,代码来源:Application.scala


示例20: WDHTServer

//设置package包名称以及导入依赖的类
package com.waltsu.wdht

import java.util.concurrent.Executors

import colossus._
import core._
import service._
import protocols.http._
import UrlParsing._
import HttpMethod._
import com.typesafe.config.ConfigFactory
import com.waltsu.wdht.storage.models.StoredObject
import play.api.libs.json.{JsError, JsSuccess, JsValue, Json}

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.{ExecutionContext, Future}

object WDHTServer {
  private implicit val executionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
}
class WDHTServer(context: ServerContext) extends HttpService(context) {
  import WDHTServer._

  private val RequestTimeout = ConfigFactory.load().getInt("wdht.requestTimeout") seconds

  def handle = {
    case request @ Get on Root / key => Callback.fromFuture(getObject(request, key))
    case request @ Put on Root / key => Callback.fromFuture(putObject(request, key))
    case request => Callback.successful(request.notFound("not found"))
  }

  private def getObject(request: HttpRequest, key: String): Future[HttpResponse] = {
    DistributedHashTable.get(key).map {
      case Some(storedObject) =>
        request.ok(Json.toJson(storedObject).toString)
      case None => request.notFound("")
    }
  }

  private def putObject(request: HttpRequest, key: String): Future[HttpResponse] = {
    (Json.parse(request.body.toString) \ "value").validate[String] match {
      case value: JsSuccess[String] =>
        DistributedHashTable.put(key, value.value).map((storedObject) => {
          request.ok(Json.toJson(storedObject).toString())
        })
      case error: JsError =>
        Future { request.badRequest("Errors: " + JsError.toJson(error).toString()) }
    }
  }
}

class WDHTInitializer(worker: WorkerRef) extends Initializer(worker) {
  def onConnect = context => new WDHTServer(context)
} 
开发者ID:waltsu,项目名称:wdht,代码行数:57,代码来源:WDHTServer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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