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


Scala JsError类代码示例

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


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


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