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


Scala ValidationError类代码示例

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


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

示例1: PullRequest

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

import play.api.data.validation.ValidationError
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scalaz._
import scalaz.Scalaz._

case class PullRequest(number: Double, owner: String, projectName: String)

object PullRequest {
  def buildFrom(json: JsValue): Seq[(JsPath, Seq[ValidationError])] \/ PullRequest = {
    val prReads: Reads[PullRequest] = (
      (__ \ "issue" \ "number").read[Double] and
        (__ \ "repository" \ "owner" \ "login").read[String] and
        (__ \ "repository" \ "name").read[String]
      ) (PullRequest.apply _)
    json.validate(prReads).asEither.disjunction
  }
} 
开发者ID:MiroslavCsonka,项目名称:u-cant-merge-this,代码行数:22,代码来源:PullRequest.scala

示例2: RichJsError

//设置package包名称以及导入依赖的类
package play.api.libs.json

import play.api.data.validation.ValidationError
import play.api.i18n.Messages

object RichJsError {

  def toI18NJson(e: JsError)(messages: Messages): JsObject = toI18NJson(e.errors)(messages)

  private def toI18NJson(errors: Seq[(JsPath, Seq[ValidationError])])(messages: Messages): JsObject = {
    val argsWrite = Writes.traversableWrites[Any](Writes.anyWrites)
    errors.foldLeft(Json.obj()) { (obj, error) =>
      obj ++ Json.obj(error._1.toJsonString -> error._2.foldLeft(Json.arr()) { (arr, err) =>
        arr :+ JsString( play.api.i18n.Messages(err.messages, err.args)(messages) )
      })
    }
  }

} 
开发者ID:LabCo,项目名称:rpi-zway-play,代码行数:20,代码来源:RichJsError.scala

示例3: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:chriswk,项目名称:gameranker,代码行数:60,代码来源:JsonFormats.scala

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

示例5: CartEntry

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

import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

case class CartEntry(productName: String, count: Int)
case class Cart(user: UUID, cartItems: Seq[CartEntry])
case class Product(name: String, description: String, imageResource: String, price: Double)

object CartEntry {
  implicit val format = Json.format[CartEntry]
}

object Cart {
  def parseUUID(s: String): Option[java.util.UUID] = Try(java.util.UUID.fromString(s)).toOption

  implicit val uuidFormat = new Format[UUID] {
    def reads(json: JsValue): JsResult[UUID] = json match {
      case JsString(s) =>
        parseUUID(s).map(JsSuccess(_)).getOrElse(JsError(Seq(JsPath() -> Seq(ValidationError("Expected UUID string")))))
      case _ =>
        JsError(Seq(JsPath() -> Seq(ValidationError("Expected UUID string"))))
    }
    def writes(uuid: java.util.UUID): JsValue = JsString(uuid.toString)
  }

  implicit val format = Json.format[Cart]
} 
开发者ID:emotecontrol,项目名称:cart_play,代码行数:33,代码来源:Models.scala

示例6: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }

  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))

  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }

  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }

  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:adempiere,项目名称:ADReactiveSystem,代码行数:62,代码来源:JsonFormats.scala

示例7: Errors

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

import play.api.data.validation.ValidationError
import play.api.libs.json._

object Errors {
  case object DuplicateAdmiral         extends Error
  case object AdmiralNotFound          extends Error

  case object DuplicateAnchor          extends Error
  case object AnchorNotFound           extends Error

  case object DuplicateSpotting        extends Error
  case object SpottingNotFound         extends Error
  case object TooShortSpottingInterval extends Error
  case object AnchorAlreadySpotted     extends Error
  case object AnchorAlreadySunk        extends Error

  case object Maintenance              extends Error

  case class JsonParseError(jsError: JsError) extends Error {
    override def toJson: JsObject = super.toJson.deepMerge(jsError.toJson)
  }
  object JsonParseError {
    def apply(errors: Seq[(JsPath, Seq[ValidationError])]): JsonParseError = JsonParseError(JsError(errors))
  }

  sealed trait Error {
    this: Product =>

    def code: String = productPrefix
    def toJson: JsObject = Json.obj("code" -> code)
  }

  private implicit val validationErrorWrites: Writes[ValidationError] = new Writes[ValidationError] {
    override def writes(o: ValidationError): JsValue = Json.obj(
      "messages" -> o.messages,
      "args"     -> o.args.map(_.toString)
    )
  }

  private implicit class JsErrorOps(val self: JsError) extends AnyVal {
    def toJson: JsObject = {
      Json.obj(
        "errors" -> self.errors.map { case (jsPath, error) =>
          Json.obj(
            "path" -> jsPath.toString,
            "error" -> error.map(Json.toJson(_))
          )
        }
      )
    }
  }

} 
开发者ID:harry0000,项目名称:KancolleAnchor,代码行数:56,代码来源:Errors.scala

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

示例9: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
      .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
        Try(Duration.parse(str)).toOption
      })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:lagom,项目名称:online-auction-scala,代码行数:60,代码来源:JsonFormats.scala

示例10: JsonFormats

//设置package包名称以及导入依赖的类
package org.wex.cmsfs.monitor.api

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:shinhwazx160,项目名称:test,代码行数:57,代码来源:JsonFormats.scala

示例11: Vote

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

import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._

case class Vote(answer_id: Option[Long], user_id: Option[Long], value: Int)

object Vote {
  val userValidate = Reads.IntReads.
    filter(ValidationError("Value must be -1 or 1"))(validValue(_))

  implicit val voteReads: Reads[Vote] = (
    (JsPath \ "answer_id").readNullable[Long] and
    (JsPath \ "user_id").readNullable[Long] and
    (JsPath \ "value").read[Int](userValidate)
  )(Vote.apply _)

  implicit val voteWrites = Json.writes[Vote]

  def validValue(value: Int) = value == -1 || value == 1
}

class VoteTable(tag: SlickTag) extends Table[Vote](tag, "votes") {
  def answer_id = column[Option[Long]]("answer_id")
  def user_id = column[Option[Long]]("user_id")
  def value = column[Int]("vote_value")

  def pk = primaryKey("vote_pk", (answer_id, user_id))

  def * = (answer_id, user_id, value) <> ((Vote.apply _).tupled, Vote.unapply)
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:37,代码来源:Vote.scala

示例12: SortingPaginationWrapper

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

import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class SortingPaginationWrapper(sort_by: String,
  page: Int = 1,
  resultsPerPage: Int = 25, direction: String = "desc")

object SortingPaginationWrapper {

  val sortingParameters = List("date", "votes", "title")
  val directionParameters = List("asc", "desc")

  val sortValidate = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(sortByValidator(_))

  val sortValidateAnswers = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(sortByValidator)

  val directionValidate = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(directionValidator(_))

  implicit val sortingPaginationReads: Reads[SortingPaginationWrapper] = (
    ((JsPath \ "sort_by").read[String](sortValidate) orElse Reads.pure("date")) and
    ((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
    ((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
    ((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
  )(SortingPaginationWrapper.apply _)

  val sortingPaginationAnswerReads: Reads[SortingPaginationWrapper] = (
    ((JsPath \ "sort_by").read[String](sortValidateAnswers) orElse Reads.pure("created_at")) and
    ((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
    ((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
    ((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
  )(SortingPaginationWrapper.apply _)


  def sortByValidator(criteria: String) =
    List("date", "votecount", "title", "answercount", "favouritecount")
      .contains(criteria.toLowerCase)

  def sortByValidatorAnswers(criteria: String) =
    List("created_at", "updated_at", "voteCount").contains(criteria.toLowerCase)

  def directionValidator(param: String) =
    List("asc", "desc").contains(param.toLowerCase)

  def getPage(pageNum: Int, resultsPerPage: Int) =
    resultsPerPage * (pageNum - 1)
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:53,代码来源:SortingPaginationWrapper.scala

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

示例14: ValidationUtils

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

import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError}

object ValidationUtils {

  def inRange[T](minValue: T, maxValue: T)(implicit ordering: scala.math.Ordering[T]): Constraint[T] =
    Constraint[T] { (t: T) =>
      assert(ordering.compare(minValue, maxValue) < 0, "min bound must be less than max bound")
      (ordering.compare(t, minValue).signum, ordering.compare(t, maxValue).signum) match {
        case (1, -1) | (0, _) | (_, 0) => Valid
        case (_, 1) => Invalid(ValidationError("error.range.above", maxValue))
        case (-1, _) => Invalid(ValidationError("error.range.below", minValue))
      }
    }

  def optionallyMatchingPattern(regex: String): Constraint[String] =
    Constraint[String] { s: String =>
      Option(s) match {
        case None | Some("") => Valid
        case _ if s.matches(regex) => Valid
        case _ => Invalid(ValidationError("error.string.pattern", s))
      }
    }

} 
开发者ID:PeterPerhac,项目名称:vehicle-lookup,代码行数:27,代码来源:ValidationUtils.scala

示例15: JsonFormats

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

import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {


  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }
} 
开发者ID:Saneyan,项目名称:lagom-practice,代码行数:35,代码来源:JsonFormats.scala


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