play.api.libs.json.JsError Scala Examples

The following examples show how to use play.api.libs.json.JsError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SttpPlayJsonApi.scala    From sttp   with Apache License 2.0 5 votes vote down vote up
package sttp.client.playJson

import sttp.client._
import sttp.model._
import sttp.client.internal.Utf8
import play.api.libs.json.{JsError, Json, Reads, Writes}
import sttp.client.{IsOption, JsonInput, ResponseAs, ResponseError}
import sttp.model.MediaType

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

trait SttpPlayJsonApi {
  implicit def playJsonBodySerializer[B: Writes]: BodySerializer[B] =
    b => StringBody(Json.stringify(Json.toJson(b)), Utf8, Some(MediaType.ApplicationJson))

  
  def asJsonAlwaysUnsafe[B: Reads: IsOption]: ResponseAs[B, Nothing] =
    asStringAlways.map(ResponseAs.deserializeOrThrow(deserializeJson))

  // Note: None of the play-json utilities attempt to catch invalid
  // json, so Json.parse needs to be wrapped in Try
  def deserializeJson[B: Reads: IsOption]: String => Either[JsError, B] =
    JsonInput.sanitize[B].andThen { s =>
      Try(Json.parse(s)) match {
        case Failure(e: Exception) => Left(JsError(e.getMessage))
        case Failure(t: Throwable) => throw t
        case Success(json) =>
          Json.fromJson(json).asEither match {
            case Left(failures) => Left(JsError(failures))
            case Right(success) => Right(success)
          }
      }
    }
} 
Example 2
Source File: NonBlankStringSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.binders

import org.scalatest.{Matchers, WordSpecLike}
import play.api.libs.json.{JsError, JsString, JsSuccess, Json}

class NonBlankStringSpec extends WordSpecLike with Matchers {

  "Creating a NonBlankString" should {
    "throw an exception for a blank string" in {
      an[IllegalArgumentException] should be thrownBy NonBlankString("")
    }

    "give an error for a null string" in {
      an[IllegalArgumentException] should be thrownBy NonBlankString(null)
    }

    "give a success for a non-blank string" in {
      NonBlankString("x")
    }
  }

  "Reading a NonBlankString" should {
    "give an error for a blank string" in {
      validating("") shouldBe a[JsError]
    }

    "give an error for a null string" in {
      validating(null) shouldBe a[JsError]
    }

    "give a success for a non-blank string" in {
      validating("x") should be(JsSuccess(NonBlankString("x")))
    }

    def validating(s: String) = JsString(s).validate[NonBlankString]
  }

  "Writing a NonBlankString" should {
    "just include the value" in {
      Json.toJson(NonBlankString("x")) should be(JsString("x"))
    }
  }

  "Binding from a query string" should {
    "give an error for a blank string" in {
      binding("") shouldBe Some(Left("String was blank"))
    }

    "give an error for a null string" in {
      binding(null) shouldBe Some(Left("String was blank"))
    }

    "give a success for a non-blank string" in {
      binding("x") shouldBe Some(Right(NonBlankString("x")))
    }
    def binding(s: String) = NonBlankString.stringToNonBlankString.bind("v", Map("v" -> Seq(s)))
  }

  "Unbinding to a query string" should {
    "extract the value" in {
      unbinding(NonBlankString("something")) shouldBe "something"
    }
    def unbinding(n: NonBlankString) = NonBlankString.stringToNonBlankString.unbind("v", n)
  }

} 
Example 3
Source File: MillinerHatSignup.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.resourceManagement

import org.hatdex.hat.resourceManagement.models.HatSignup
import play.api.cache.AsyncCacheApi
import play.api.http.Status._
import play.api.libs.json.{ JsError, JsSuccess }
import play.api.libs.ws.{ WSClient, WSRequest, WSResponse }
import play.api.{ Configuration, Logger }

import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future }

trait MillinerHatSignup {
  val logger: Logger
  val ws: WSClient
  val configuration: Configuration
  val schema: String = configuration.get[String]("resourceManagement.millinerAddress") match {
    case address if address.startsWith("https") => "https://"
    case address if address.startsWith("http")  => "http://"
    case _                                      => "https://"
  }

  val millinerAddress: String = configuration.get[String]("resourceManagement.millinerAddress")
    .stripPrefix("http://")
    .stripPrefix("https://")
  val hatSharedSecret: String = configuration.get[String]("resourceManagement.hatSharedSecret")

  val cache: AsyncCacheApi

  def getHatSignup(hatAddress: String)(implicit ec: ExecutionContext): Future[HatSignup] = {
    // Cache the signup information for subsequent calls (For private/public key and database details)
    cache.getOrElseUpdate[HatSignup](s"configuration:$hatAddress") {
      val request: WSRequest = ws.url(s"$schema$millinerAddress/api/manage/configuration/$hatAddress")
        .withVirtualHost(millinerAddress)
        .withHttpHeaders("Accept" -> "application/json", "X-Auth-Token" -> hatSharedSecret)

      val futureResponse: Future[WSResponse] = request.get()
      futureResponse.map { response =>
        response.status match {
          case OK =>
            response.json.validate[HatSignup] match {
              case signup: JsSuccess[HatSignup] =>
                logger.debug(s"Got back configuration: ${signup.value}")
                cache.set(s"configuration:$hatAddress", signup.value, 1.minute)
                signup.value
              case e: JsError =>
                logger.error(s"Parsing HAT configuration failed: $e")
                throw new HatServerDiscoveryException("Fetching HAT configuration failed")
            }
          case _ =>
            logger.error(s"Fetching HAT configuration failed: ${response.body}")
            throw new HatServerDiscoveryException("Fetching HAT configuration failed")
        }
      }
    }
  }

} 
Example 4
Source File: UberMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, FilterOperator, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemLocation, DataFeedItemTitle, LocationGeo }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsSuccess, JsValue, Json }

import scala.util.Try

class UberRidesMapper extends DataEndpointMapper {
  override protected val dataDeduplicationField: Option[String] = Some("request_id")

  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    val unixDateFilter = fromDate.flatMap { _ =>
      Some(FilterOperator.Between(Json.toJson(fromDate.map(t => t.getMillis / 1000)), Json.toJson(untilDate.map(t => t.getMillis / 1000))))
    }

    Seq(PropertyQuery(
      List(EndpointQuery("uber/rides", None,
        unixDateFilter.map(f ⇒ Seq(EndpointQueryFilter("start_time", None, f))), None)), Some("start_time"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    logger.debug(s"uber content: $content")
    for {
      distance <- Try((content \ "distance").asOpt[Double].getOrElse(0.doubleValue()).toString)
      startDate <- Try(new DateTime((content \ "start_time").as[Long] * 1000.longValue()))
      durationSeconds ← Try((content \ "end_time").asOpt[Int].getOrElse(0) - (content \ "start_time").asOpt[Int].getOrElse(0))
      duration <- Try {
        val m = (durationSeconds / 60) % 60
        val h = (durationSeconds / 60 / 60) % 24
        "%02d h %02d min".format(h, m)
      }
      title ← Try(DataFeedItemTitle(s"Your trip on ${startDate.toString("dd/MM/YYYY")}", None, None))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "start_city" \ "display_name").asOpt[String].getOrElse("Unknown City")},
             |${BigDecimal.decimal(distance.toFloat).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble} miles,
             |${duration}""".stripMargin),
        None,
        None,
        None))
      latitude <- Try((content \ "start_city" \ "latitude").asOpt[Double].getOrElse(0.doubleValue()))
      longitude <- Try((content \ "start_city" \ "longitude").asOpt[Double].getOrElse(0.doubleValue()))
      location <- Try(DataFeedItemLocation(Some(LocationGeo(longitude, latitude)), None, None))
    } yield DataFeedItem("uber", startDate, Seq(), Some(title), Some(itemContent), Some(location))
  }
}

class UberProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("uber/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[Map[String, JsValue]]
    eventualData match {
      case JsSuccess(value, _) =>
        val lastPartOfEndpointString = endpoint.split("/").last

        Seq(StaticDataValues(lastPartOfEndpointString, value))
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }
} 
Example 5
Source File: SpotifyMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemMedia, DataFeedItemTitle }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsNumber, JsObject, JsResult, JsSuccess, JsValue, __ }

import scala.util.Try

class SpotifyFeedMapper extends DataEndpointMapper {
  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(EndpointQuery("spotify/feed", None,
        dateFilter(fromDate, untilDate).map(f ⇒ Seq(EndpointQueryFilter("played_at", None, f))), None)), Some("played_at"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      durationSeconds ← Try((content \ "track" \ "duration_ms").as[Int] / 1000)
      title ← Try(
        DataFeedItemTitle("You listened", None, Some(s"${"%02d".format(durationSeconds / 60)}:${"%02d".format(durationSeconds % 60)}")))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "track" \ "name").as[String]},
             |${(content \ "track" \ "artists").as[Seq[JsObject]].map(a ⇒ (a \ "name").as[String]).mkString(", ")},
             |${(content \ "track" \ "album" \ "name").as[String]}""".stripMargin),
        None,
        Some(
          Seq(DataFeedItemMedia((content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String], (content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String]))),
        None))
      date ← Try((content \ "played_at").as[DateTime])
    } yield DataFeedItem("spotify", date, Seq(), Some(title), Some(itemContent), None)
  }
}

class SpotifyProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("spotify/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[JsObject]
    eventualData match {
      case JsSuccess(value, _) =>

        val lastPartOfEndpointString = endpoint.split("/").last
        val maybeTransformedData = transformData(value).flatMap(item => item.validate[Map[String, JsValue]])
        maybeTransformedData match {
          case JsSuccess(data, _) =>

            Seq(StaticDataValues(lastPartOfEndpointString, (data - "images" - "external_urls")))
          case e: JsError =>

            logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
            Seq()
        }
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }

  private def transformData(rawData: JsObject): JsResult[JsValue] = {
    val transformation = __.json.update(
      __.read[JsObject].map(profile => {
        val followers = (profile \ "followers" \ "total").asOpt[JsNumber].getOrElse(JsNumber(0))

        profile ++ JsObject(Map(
          "followers" -> followers))
      }))

    rawData.transform(transformation)
  }
} 
Example 6
Source File: HatBodyParsers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.utils

import javax.inject.Inject

import play.api.http.{ HttpErrorHandler, Status }
import play.api.libs.json.{ JsError, Reads }
import play.api.mvc.{ BodyParser, PlayBodyParsers }

import scala.concurrent.{ ExecutionContext, Future }

class HatBodyParsers @Inject() (errorHandler: HttpErrorHandler, playBodyParsers: PlayBodyParsers)(
    implicit
    val ec: ExecutionContext) {
  def json[A](implicit reader: Reads[A]): BodyParser[A] =
    BodyParser("json reader") { request =>
      playBodyParsers.json(request) mapFuture {
        case Left(simpleResult) =>
          Future.successful(Left(simpleResult))
        case Right(jsValue) =>
          jsValue.validate(reader) map { a =>
            Future.successful(Right(a))
          } recoverTotal { jsError =>
            val msg = JsError.toJson(jsError).toString()
            errorHandler.onClientError(request, Status.BAD_REQUEST, msg) map Left.apply
          }
      }
    }
} 
Example 7
Source File: LoginDetails.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.phata.models

import me.gosimple.nbvcxz._
import play.api.libs.functional.syntax._
import play.api.libs.json.{ JsError, _ }

import scala.collection.JavaConverters._

case class ApiPasswordChange(
    newPassword: String,
    password: Option[String])

object ApiPasswordChange {

  private val nbvcxzDictionaryList = resources.ConfigurationBuilder.getDefaultDictionaries

  private val nbvcxzConfiguration = new resources.ConfigurationBuilder()
    .setMinimumEntropy(40d)
    .setDictionaries(nbvcxzDictionaryList)
    .createConfiguration()

  private val nbvcxz = new Nbvcxz(nbvcxzConfiguration)

  private def passwordGuessesToScore(guesses: BigDecimal) = {
    val DELTA = 5
    if (guesses < 1e3 + DELTA) {
      0
    }
    else if (guesses < 1e6 + DELTA) {
      1
    }
    else if (guesses < 1e8 + DELTA) {
      2
    }
    else if (guesses < 1e10 + DELTA) {
      3
    }
    else {
      4
    }
  }

  def passwordStrength(implicit reads: Reads[String]): Reads[String] =
    Reads[String] { js =>
      reads.reads(js)
        .flatMap { a =>
          val estimate = nbvcxz.estimate(a)
          if (passwordGuessesToScore(estimate.getGuesses) >= 2) {
            JsSuccess(a)
          }
          else {
            JsError(JsonValidationError(
              "Minimum password requirement strength not met",
              estimate.getFeedback.getSuggestion.asScala.toList: _*))
          }
        }
    }

  implicit val passwordChangeApiReads: Reads[ApiPasswordChange] = (
    (JsPath \ "newPassword").read[String](passwordStrength) and
    (JsPath \ "password").readNullable[String])(ApiPasswordChange.apply _)
  implicit val passwordChangeApiWrites: Writes[ApiPasswordChange] = Json.format[ApiPasswordChange]
}

case class ApiPasswordResetRequest(
    email: String)

object ApiPasswordResetRequest {
  implicit val passwordResetApiReads: Reads[ApiPasswordResetRequest] =
    (__ \ 'email).read[String](Reads.email).map { email => ApiPasswordResetRequest(email) }
  implicit val passwordResetApiWrites: Writes[ApiPasswordResetRequest] = Json.format[ApiPasswordResetRequest]
} 
Example 8
Source File: Converters.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.singleserver

import cool.graph.messagebus.Conversions.Converter
import cool.graph.subscriptions.protocol.SubscriptionRequest
import cool.graph.webhook.Webhook
import cool.graph.websockets.protocol.Request
import cool.graph.worker.payloads.{LogItem, Webhook => WorkerWebhook}
import play.api.libs.json.{JsError, JsSuccess, Json}


object Converters {

  import cool.graph.worker.payloads.JsonConversions.logItemFormat

  val apiWebhook2WorkerWebhook: Converter[Webhook, WorkerWebhook] = { wh: Webhook =>
    WorkerWebhook(wh.projectId, wh.functionId, wh.requestId, wh.url, wh.payload, wh.id, wh.headers)
  }

  val string2LogItem = { str: String =>
    Json.parse(str).validate[LogItem] match {
      case JsSuccess(logItem, _) => logItem
      case JsError(e)            => sys.error(s"Invalid log item $str, ignoring message.")
    }
  }

  val websocketRequest2SubscriptionRequest = { req: Request =>
    SubscriptionRequest(req.sessionId, req.projectId, req.body)
  }
} 
Example 9
Source File: SubscriptionsMain.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.subscriptions

import akka.actor.{ActorSystem, Props}
import akka.stream.ActorMaterializer
import cool.graph.akkautil.http.{Routes, Server, ServerExecutor}
import cool.graph.messagebus.pubsub.Only
import cool.graph.subscriptions.protocol.SubscriptionProtocolV05.Requests.SubscriptionSessionRequestV05
import cool.graph.subscriptions.protocol.SubscriptionProtocolV07.Requests.SubscriptionSessionRequest
import cool.graph.subscriptions.protocol.SubscriptionProtocolV07.Responses.GqlError
import cool.graph.subscriptions.protocol.SubscriptionSessionManager.Requests.{EnrichedSubscriptionRequest, EnrichedSubscriptionRequestV05, StopSession}
import cool.graph.subscriptions.protocol.{StringOrInt, SubscriptionRequest, SubscriptionSessionManager}
import cool.graph.subscriptions.resolving.SubscriptionsManager
import cool.graph.subscriptions.util.PlayJson
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport
import play.api.libs.json.{JsError, JsSuccess}

import scala.concurrent.Future

object SubscriptionsMain extends App {
  implicit val system       = ActorSystem("graphql-subscriptions")
  implicit val materializer = ActorMaterializer()
  implicit val injector     = new SimpleSubscriptionInjectorImpl()

  ServerExecutor(port = 8086, SimpleSubscriptionsServer()).startBlocking()
}

case class SimpleSubscriptionsServer(prefix: String = "")(
    implicit subscriptionInjector: SimpleSubscriptionInjector,
    system: ActorSystem,
    materializer: ActorMaterializer
) extends Server
    with PlayJsonSupport {
  import system.dispatcher

  implicit val bugSnag             = subscriptionInjector.bugsnagger
  implicit val response05Publisher = subscriptionInjector.responsePubSubPublisherV05
  implicit val response07Publisher = subscriptionInjector.responsePubSubPublisherV07

  val innerRoutes          = Routes.emptyRoute
  val subscriptionsManager = system.actorOf(Props(new SubscriptionsManager(bugSnag)), "subscriptions-manager")
  val requestsConsumer     = subscriptionInjector.requestsQueueConsumer

  val consumerRef = requestsConsumer.withConsumer { req: SubscriptionRequest =>
    Future(if (req.body == "STOP") subscriptionSessionManager ! StopSession(req.sessionId) else handleProtocolMessage(req.projectId, req.sessionId, req.body))
  }

  val subscriptionSessionManager = system.actorOf(
    Props(new SubscriptionSessionManager(subscriptionsManager, bugSnag)),
    "subscriptions-sessions-manager"
  )

  def handleProtocolMessage(projectId: String, sessionId: String, messageBody: String) = {
    import cool.graph.subscriptions.protocol.ProtocolV05.SubscriptionRequestReaders._
    import cool.graph.subscriptions.protocol.ProtocolV07.SubscriptionRequestReaders._

    val currentProtocol  = PlayJson.parse(messageBody).flatMap(_.validate[SubscriptionSessionRequest])
    lazy val oldProtocol = PlayJson.parse(messageBody).flatMap(_.validate[SubscriptionSessionRequestV05])

    currentProtocol match {
      case JsSuccess(request, _) =>
        subscriptionSessionManager ! EnrichedSubscriptionRequest(sessionId = sessionId, projectId = projectId, request)

      case JsError(newError) =>
        oldProtocol match {
          case JsSuccess(request, _) =>
            subscriptionSessionManager ! EnrichedSubscriptionRequestV05(sessionId = sessionId, projectId = projectId, request)

          case JsError(oldError) =>
            response07Publisher.publish(Only(sessionId), GqlError(StringOrInt(string = Some(""), int = None), "The message can't be parsed"))
        }
    }
  }

  override def onStop = Future {
    consumerRef.stop

//    subscriptionInjector.projectSchemaInvalidationSubscriber.shutdown
  }
} 
Example 10
package commons.controllers

import commons.exceptions.ValidationException
import commons.models.ValidationResultWrapper
import play.api.libs.json.{JsError, Json, Reads}
import play.api.mvc.{AbstractController, BodyParser, ControllerComponents, Result}

import scala.concurrent.ExecutionContext

abstract class RealWorldAbstractController(controllerComponents: ControllerComponents)
  extends AbstractController(controllerComponents) {

  implicit protected val executionContext: ExecutionContext = defaultExecutionContext

  protected def validateJson[A: Reads]: BodyParser[A] = parse.json.validate(
    _.validate[A].asEither.left.map(e => BadRequest(JsError.toJson(e)))
  )

  protected def handleFailedValidation: PartialFunction[Throwable, Result] = {
    case e: ValidationException =>
      val errors = e.violations
        .groupBy(_.property)
        .view
        .mapValues(_.map(propertyViolation => propertyViolation.violation.message))
        .toMap

      val wrapper: ValidationResultWrapper = ValidationResultWrapper(errors)
      UnprocessableEntity(Json.toJson(wrapper))
  }

} 
Example 11
Source File: BytesToWatchEventSource.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.api.watch

import akka.stream.scaladsl.{JsonFraming, Source}
import akka.util.ByteString
import play.api.libs.json.{Format, JsError, JsSuccess, Json}
import skuber.ObjectResource
import skuber.api.client.{K8SException, Status, WatchEvent}

import scala.concurrent.ExecutionContext


private[api] object BytesToWatchEventSource {
  def apply[O <: ObjectResource](bytesSource: Source[ByteString, _], bufSize: Int)(implicit ec: ExecutionContext, format: Format[O]): Source[WatchEvent[O], _] = {
    import skuber.json.format.apiobj.watchEventFormat
    bytesSource.via(
      JsonFraming.objectScanner(bufSize)
    ).map { singleEventBytes =>
      Json.parse(singleEventBytes.utf8String).validate(watchEventFormat[O]) match {
        case JsSuccess(value, _) => value
        case JsError(e) => throw new K8SException(Status(message = Some("Error parsing watched object"), details = Some(e.toString)))
      }
    }
  }
} 
Example 12
Source File: PlayJsonSupport.scala    From kafka-serde-scala   with Apache License 2.0 5 votes vote down vote up
package io.github.azhur.kafkaserdeplayjson

import java.nio.charset.StandardCharsets.UTF_8
import java.util

import io.github.azhur.kafkaserdeplayjson.PlayJsonSupport.PlayJsonError
import org.apache.kafka.common.errors.SerializationException
import org.apache.kafka.common.serialization.{ Deserializer, Serde, Serializer }
import play.api.libs.json.{ JsError, JsValue, Json, Reads, Writes }

import scala.language.implicitConversions
import scala.util.control.NonFatal

trait PlayJsonSupport {
  implicit def toSerializer[T <: AnyRef](
      implicit writes: Writes[T],
      printer: JsValue => String = Json.stringify
  ): Serializer[T] =
    new Serializer[T] {
      override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {}
      override def close(): Unit                                                 = {}
      override def serialize(topic: String, data: T): Array[Byte] =
        if (data == null) null
        else
          try printer(writes.writes(data)).getBytes(UTF_8)
          catch {
            case NonFatal(e) => throw new SerializationException(e)
          }
    }

  implicit def toDeserializer[T >: Null <: AnyRef: Manifest](
      implicit reads: Reads[T]
  ): Deserializer[T] =
    new Deserializer[T] {
      override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {}
      override def close(): Unit                                                 = {}
      override def deserialize(topic: String, data: Array[Byte]): T =
        if (data == null) null
        else
          reads
            .reads(Json.parse(new String(data, UTF_8)))
            .recoverTotal { e =>
              throw new SerializationException(PlayJsonError(e))
            }
    }

  implicit def toSerde[T >: Null <: AnyRef: Manifest](
      implicit writes: Writes[T],
      reads: Reads[T],
      printer: JsValue => String = Json.stringify
  ): Serde[T] =
    new Serde[T] {
      override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {}
      override def close(): Unit                                                 = {}
      override def serializer(): Serializer[T]                                   = toSerializer[T]
      override def deserializer(): Deserializer[T]                               = toDeserializer[T]
    }
}

object PlayJsonSupport extends PlayJsonSupport {
  final case class PlayJsonError(error: JsError) extends RuntimeException {
    override def getMessage: String =
      JsError.toJson(error).toString()
  }
} 
Example 13
Source File: RequiringFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import play.api.libs.json.Format
import play.api.libs.json.JsError
import play.api.libs.json.OFormat
import play.api.libs.json.Reads


object RequiringFormats {

  def requiringReads[T](delegate: Reads[T]): Reads[T] = Reads { json =>
    try {
      delegate.reads(json)
    } catch {
      case e: IllegalArgumentException => JsError(e.getMessage)
    }
  }

  def requiringFormat[T](delegate: Format[T]): Format[T] = {
    Format(requiringReads(delegate), delegate)
  }

  def requiringOFormat[T](delegate: OFormat[T]): OFormat[T] = {
    OFormat(requiringReads(delegate), delegate)
  }

} 
Example 14
Source File: OrFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import play.api.libs.json.Format
import play.api.libs.json.JsError
import play.api.libs.json.OFormat
import play.api.libs.json.OWrites
import play.api.libs.json.Reads
import play.api.libs.json.Writes

import scala.reflect.ClassTag
import scala.reflect.classTag

object OrFormats {

  def unimplementedReads[T: ClassTag]: Reads[T] = {
    Reads(_ => JsError(s"Invoked `unimplementedReads` for ${classTag[T]}"))
  }

  def unimplementedWrites[T: ClassTag]: Writes[T] = Writes { _ =>
    throw new UnsupportedOperationException(s"Invoked `unimplementedOWrites for ${classTag[T]}")
  }

  def unimplementedOWrites[T: ClassTag]: OWrites[T] = OWrites { _ =>
    throw new UnsupportedOperationException(s"Invoked `unimplementedOWrites for ${classTag[T]}")
  }

  def unimplementedFormat[T: ClassTag]: Format[T] = Format(unimplementedReads, unimplementedWrites)

  def unimplementedOFormat[T: ClassTag]: OFormat[T] =
    OFormat(unimplementedReads[T], unimplementedOWrites[T])

  implicit class OrReads[A](reads: Reads[A]) {
    def orReads[B <: A: Reads]: Reads[A] = {
      import play.api.libs.functional.syntax._
      reads or implicitly[Reads[B]].map(b => b: A)
    }
  }

  implicit class OrWrites[A](writes: Writes[A]) {
    def orWrites[B <: A: Writes: ClassTag](implicit classTag: ClassTag[A]): Writes[A] = Writes {
      case b: B => implicitly[Writes[B]].writes(b)
      case a: A => writes.writes(a)
    }
  }

  implicit class OrOWrites[A](oWrites: OWrites[A]) {
    def orOWrites[B <: A: OWrites: ClassTag](implicit classTag: ClassTag[A]): OWrites[A] = OWrites {
      case b: B => implicitly[OWrites[B]].writes(b)
      case a: A => oWrites.writes(a)
    }
  }

  implicit class OrFormat[A](format: Format[A]) {
    def orFormat[B <: A: Format: ClassTag](implicit classTag: ClassTag[A]): Format[A] = {
      Format(format.orReads[B], format.orWrites[B])
    }
  }

  implicit class OrOFormat[A](oFormat: OFormat[A]) {
    def orOFormat[B <: A: OFormat: ClassTag](implicit classTag: ClassTag[A]): OFormat[A] = {
      OFormat(oFormat.orReads[B], oFormat.orOWrites[B])
    }
  }

} 
Example 15
Source File: HomeController.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package controllers

import env.{AppConfig, Env}
import play.api.libs.json.{JsError, Json}
import play.api.mvc.{AbstractController, ControllerComponents, Cookie, Cookies}

case class LoginForm(email: String)
object LoginForm {
  implicit val format = Json.format[LoginForm]
}

class HomeController(env: Env, config: AppConfig, val cc: ControllerComponents) extends AbstractController(cc) {

  def index() = Action {
    config.front match {
      case "react" =>
        Ok(views.html.index(env))
      case _ =>
        Ok(views.html.indexangular(env))
    }
  }

  def indexOtherRoutes(path: String) = index()

  def login() = Action(parse.json) { req =>
    req.body
      .validate[LoginForm]
      .fold(
        e => BadRequest(JsError.toJson(e)),
        form => Ok(Json.obj()).withCookies(Cookie("clientId", form.email))
      )

  }

} 
Example 16
Source File: zio.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package libs.ziohelper
import cats.data.NonEmptyList
import play.api.libs.json.{JsError, JsPath, JsResult, JsSuccess, JsonValidationError}
import domains.errors.{IzanamiErrors, ValidationError}
import zio._
import libs.logs.ZLogger

object JsResults {

  def handleJsError[C <: ZLogger, T](err: Seq[(JsPath, Seq[JsonValidationError])]): ZIO[C, IzanamiErrors, T] =
    ZLogger.error(s"Error parsing json $err") *>
    IO.fail(NonEmptyList.of(ValidationError.error("error.json.parsing")))

  def jsResultToError[C <: ZLogger, T](jsResult: JsResult[T]): ZIO[C, IzanamiErrors, T] =
    fromJsResult(jsResult) { handleJsError }

  def jsResultToHttpResponse[T](jsResult: JsResult[T]) =
    liftJsResult(jsResult)(err => play.api.mvc.Results.BadRequest(ValidationError.fromJsError(err).toJson))

  def liftJsResult[T, E](jsResult: JsResult[T])(onError: Seq[(JsPath, Seq[JsonValidationError])] => E): IO[E, T] =
    jsResult match {
      case JsSuccess(value, _) => IO.succeed(value)
      case JsError(errors)     => IO.fail(onError(errors.toSeq.map(t => t.copy(_2 = t._2.toSeq))))
    }

  def fromJsResult[C <: ZLogger, T, E](
      jsResult: JsResult[T]
  )(onError: Seq[(JsPath, Seq[JsonValidationError])] => ZIO[C, E, T]): ZIO[C, E, T] =
    jsResult match {
      case JsSuccess(value, _) => ZIO.succeed(value)
      case JsError(errors)     => onError(errors.toSeq.map(t => t.copy(_2 = t._2.toSeq)))
    }

} 
Example 17
Source File: KeyTest.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package domains

import play.api.libs.json.{JsError, JsString, JsSuccess, Json}
import store.{EmptyPattern, StringPattern}
import test.IzanamiSpec


class KeyTest extends IzanamiSpec {

  "Key deserialization" must {

    "should be valid" in {
      val result = JsString("ragnar:lodbrok:730").validate[Key]
      result mustBe an[JsSuccess[_]]
      result.get must be(Key("ragnar:lodbrok:730"))
    }

    "should be invalid" in {
      val result = JsString("björn:ironside").validate[Key]
      result mustBe an[JsError]
    }

  }

  "Key serialization" must {

    "should be valid" in {
      Json.toJson(Key("ragnar:lodbrok:730")) must be(JsString("ragnar:lodbrok:730"))
    }
  }

  "Test patterns" must {

    "match" in {
      Key("test2:ab:scenario:B:8:displayed").matchPattern("test2:ab:scenario:*") must be(true)
    }

    "not match" in {
      Key("test1:ab:scenario:B:8:displayed").matchPattern("test2:ab:scenario:*") must be(false)
    }

    "match all is true" in {
      Key("test2:ab:scenario:B:8:displayed").matchAllPatterns("test2:ab:scenario:*", "test2:ab:*") must be(true)
    }

    "match all is false" in {
      Key("test1:ab:scenario:B:8:displayed").matchAllPatterns("test2:ab:scenario:*", "test1:ab:*") must be(false)
    }

    "match one str is true" in {
      Key("test1:ab:scenario:B:8:displayed").matchOneStrPatterns("test2:ab:scenario:*", "test1:ab:*") must be(true)
    }

    "match one is false" in {
      Key("test1:ab:scenario:B:8:displayed").matchOneStrPatterns("test2:ab:scenario:*", "test2:ab:*") must be(false)
    }

    "match one pattern is true" in {
      Key("test1:ab:scenario:B:8:displayed").matchOnePatterns(StringPattern("test2:ab:scenario:*"),
                                                              StringPattern("test1:ab:*")) must be(true)
    }

    "match one pattern with empty is false" in {
      Key("test1:ab:scenario:B:8:displayed")
        .matchOnePatterns(StringPattern("test2:ab:scenario:*"), EmptyPattern) must be(false)
    }

  }
} 
Example 18
Source File: SelfAssessmentUserType.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models

import play.api.libs.json.{JsDefined, JsError, JsResult, JsString, JsSuccess, JsValue, Json, Reads, Writes}
import uk.gov.hmrc.domain.SaUtr

sealed trait SelfAssessmentUserType

sealed trait SelfAssessmentUser extends SelfAssessmentUserType {
  def saUtr: SaUtr
}

object SelfAssessmentUserType {
  val cacheId = "SelfAssessmentUser"

  val activatedSa = ActivatedOnlineFilerSelfAssessmentUser.toString
  val notActivatedSa = NotYetActivatedOnlineFilerSelfAssessmentUser.toString
  val wrongCredsSa = WrongCredentialsSelfAssessmentUser.toString
  val notEnrolledSa = NotEnrolledSelfAssessmentUser.toString
  val nonFilerSa = NonFilerSelfAssessmentUser.toString

  implicit val writes = new Writes[SelfAssessmentUserType] {
    override def writes(o: SelfAssessmentUserType): JsValue = o match {
      case ActivatedOnlineFilerSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(activatedSa), "utr" -> JsString(utr.toString))
      case NotYetActivatedOnlineFilerSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(notActivatedSa), "utr" -> JsString(utr.toString))
      case WrongCredentialsSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(wrongCredsSa), "utr" -> JsString(utr.toString))
      case NotEnrolledSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(notEnrolledSa), "utr" -> JsString(utr.toString))
      case NonFilerSelfAssessmentUser =>
        Json.obj("_type" -> JsString(nonFilerSa))
    }
  }

  implicit val reads = new Reads[SelfAssessmentUserType] {
    override def reads(json: JsValue): JsResult[SelfAssessmentUserType] =
      (json \ "_type", json \ "utr") match {

        case (JsDefined(JsString(`activatedSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(ActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`notActivatedSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(NotYetActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`wrongCredsSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(WrongCredentialsSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`notEnrolledSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(NotEnrolledSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`nonFilerSa`)), _) =>
          JsSuccess(NonFilerSelfAssessmentUser)
        case _ => JsError("Could not read SelfAssessmentUserType")
      }
  }
}

case class ActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class NotYetActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class WrongCredentialsSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class NotEnrolledSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case object NonFilerSelfAssessmentUser extends SelfAssessmentUserType 
Example 19
Source File: BitcoinerLiveFeeRateProvider.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.feeprovider

import akka.actor.ActorSystem
import akka.http.scaladsl.model.Uri
import org.bitcoins.commons.jsonmodels.wallet.BitcoinerLiveResult
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.wallet.fee.SatoshisPerVirtualByte
import play.api.libs.json.{JsError, JsSuccess, Json}

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

case class BitcoinerLiveFeeRateProvider(minutes: Int)(implicit
    override val system: ActorSystem)
    extends CachedHttpFeeRateProvider {

  private val bitcoinerLiveValidMinutes =
    Vector(30, 60, 120, 180, 360, 720, 1440)
  require(
    bitcoinerLiveValidMinutes.contains(minutes),
    s"$minutes is not a valid selection, must be from $bitcoinerLiveValidMinutes")

  override val uri: Uri =
    Uri("https://bitcoiner.live/api/fees/estimates/latest")

  override def converter(str: String): Try[SatoshisPerVirtualByte] = {
    val json = Json.parse(str)
    json.validate[BitcoinerLiveResult] match {
      case JsSuccess(response, _) =>
        Success(response.estimates(minutes).sat_per_vbyte)
      case JsError(error) =>
        Failure(
          new RuntimeException(
            s"Unexpected error when parsing response: $error"))
    }
  }
} 
Example 20
Source File: AttributesProvider.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.router2

import com.typesafe.scalalogging.StrictLogging
import org.coursera.courier.templates.DataTemplates.DataConversion
import org.coursera.naptime.courier.CourierFormats
import org.coursera.naptime.schema.Attribute
import org.coursera.naptime.schema.JsValue
import play.api.libs.json.JsError
import play.api.libs.json.JsObject
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json

import scala.util.control.NonFatal

object AttributesProvider extends StrictLogging {

  val SCALADOC_ATTRIBUTE_NAME = "scaladocs"

  lazy val scaladocs: Map[String, JsObject] = {
    val scaladocPath = "/naptime.scaladoc.json"
    (for {
      stream <- Option(getClass.getResourceAsStream(scaladocPath))
      json <- try {
        Some(Json.parse(stream))
      } catch {
        case NonFatal(exception) =>
          logger.warn(
            s"Could not parse contents of file " +
              s"$scaladocPath as JSON")
          None
      } finally {
        stream.close()
      }
      scaladocCollection <- json.validate[Map[String, JsObject]] match {
        case JsSuccess(deserialized, _) =>
          Some(deserialized)
        case JsError(_) =>
          logger.warn(
            s"Could not deserialize contents of file " +
              s"$scaladocPath as `Map[String, JsObject]`")
          None
      }
    } yield {
      scaladocCollection
    }).getOrElse(Map.empty)
  }

  def getResourceAttributes(className: String): Seq[Attribute] = {
    scaladocs
      .get(className)
      .map(value => Attribute(SCALADOC_ATTRIBUTE_NAME, Some(jsObjToJsValue(value))))
      .toList
  }

  def getMethodAttributes(className: String, methodName: String): Seq[Attribute] = {
    scaladocs
      .get(s"$className.$methodName")
      .map(value => Attribute(SCALADOC_ATTRIBUTE_NAME, Some(jsObjToJsValue(value))))
      .toList
  }

  private[this] def jsObjToJsValue(jsObj: JsObject): JsValue = {
    JsValue.build(CourierFormats.objToDataMap(jsObj), DataConversion.SetReadOnly)
  }
} 
Example 21
Source File: ValidatingReadsSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.play

import de.leanovate.swaggercheck.schema.model.DefaultSchema
import de.leanovate.swaggercheck.schema.play.Implicits._
import de.leanovate.swaggercheck.schema.play.model.ProductModel
import org.scalatest.{MustMatchers, WordSpec}
import play.api.libs.json.{JsError, Json, Reads}

class ValidatingReadsSpec extends WordSpec with MustMatchers {
  val schema: DefaultSchema = Json
    .parse(getClass.getClassLoader.getResourceAsStream("schema/simple1.json"))
    .as[DefaultSchema]

  val atLeastOneTagRead: Reads[Seq[ProductModel]] =
    ValidatingReads.validating[Seq[ProductModel]](schema)

  "ValidatingReads" should {
    "reject invalid json input" in {
      val json = Json.parse("""[
        |    {
        |        "id": 12345678,
        |        "name": "thename",
        |        "price": 1234.67,
        |        "tags": []
        |    }
        |]""".stripMargin)

      val result = json.validate(atLeastOneTagRead)

      result mustBe a[JsError]
    }
  }
} 
Example 22
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.json.{LaboratoryJson, ResultMessage}
import model.{Laboratory, Role}
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, UserService, state}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}


class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    // TODO: Get id from json
    request.body.asJson match {
      case Some(json) => json.validate[Laboratory] match {
        case JsSuccess(laboratory, _) =>
          laboratoryService.update(laboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory updated")))
            case state.NotFound => NotFound(Json.toJson(ResultMessage("Laboratory not found",Seq(("id", laboratory.id.toString)))))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))
          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def add = AuthRequiredAction { implicit request =>
    Logger.debug("Adding laboratory... ")
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    request.body.asJson match {
      case Some(json) => json.validate[LaboratoryJson] match {
        case JsSuccess(laboratory, _) =>
          val newLaboratory = Laboratory(0, laboratory.name, laboratory.location, laboratory.administration)
          laboratoryService.add(newLaboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory added")))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))

          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(id: Long) = AuthRequiredAction { implicit request =>
    laboratoryService.delete(id) map {
      case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory deleted successfully")))
      case state.NotFound => NotFound(Json.toJson(new ResultMessage("Laboratory not found")))
      case _ => BadRequest(Json.toJson(new ResultMessage("A server problem occurred while trying to delete the laboratory")))
    }
  }
} 
Example 23
Source File: RoomController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.Room
import model.json.ResultMessage
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, RoomService, UserService, state}

import scala.concurrent.{ExecutionContext, Future}


class RoomController @Inject()(roomService: RoomService, laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def add = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Adding room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.add(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room added")))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Updating room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.update(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room updated")))
          case state.NotFound => NotFound(Json.toJson( ResultMessage("Room not found", Seq(("id", room.id.toString)))))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not update that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(roomId: Long) = AuthRequiredAction { implicit request =>
    roomService.delete(roomId).map {
      case state.ActionCompleted => Redirect(normalroutes.HomeController.home())
      case state.NotFound => NotFound
      case _ => BadRequest
    }
  }

  def blockUser(roomId: Long) = AuthRequiredAction { implicit request =>
    // TODO: Processing Not Yet Implemented
    val results = for {
      roomResult <- roomService.get(roomId)
    } yield roomResult
    results.map { result: Option[Room] =>
      if (result.isDefined)
        Redirect(normalroutes.LaboratoryController.get(result.get.laboratoryID))
      else
        NotFound
    }
  }
} 
Example 24
Source File: PaymentItemSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.response.payments

import play.api.libs.json.{JsError, JsObject, JsValue, Json}
import support.UnitSpec

class PaymentItemSpec extends UnitSpec {

  val desJson: JsValue = Json.parse(
    """
      |{
      |  "paymentAmount" : 100.2,
      |  "clearingDate" : "2017-01-01"
      |}
    """.stripMargin
  )

  val invalidDesJson: JsValue = Json.parse(
    """
      |{
      |  "paymentAmount" : 100.2,
      |  "clearingDate" : false
      |}
    """.stripMargin
  )

  val mtdJson: JsValue = Json.parse(
    """
      |{
      |  "amount" : 100.2,
      |  "received" : "2017-01-01"
      |}
    """.stripMargin
  )

  val paymentItemModel: PaymentItem =
    PaymentItem(amount = Some(100.2), received = Some("2017-01-01"))

  "PaymentItem" when {
    "read from valid JSON" should {
      "produce the expected PaymentItem object" in {
        desJson.as[PaymentItem] shouldBe paymentItemModel
      }

      "handle missing optional fields" in {
        JsObject.empty.as[PaymentItem] shouldBe PaymentItem.empty
      }

      "error on invalid json" in {
        invalidDesJson.validate[PaymentItem] shouldBe a[JsError]
      }
    }

    "written to JSON" should {
      "produce the expected Js Object" in {
        Json.toJson(paymentItemModel) shouldBe mtdJson
      }

      "not write empty fields" in {

        val emptyPaymentItemModel: PaymentItem =
          PaymentItem(amount = None, received = None)

        Json.toJson(emptyPaymentItemModel) shouldBe JsObject.empty
      }
    }
  }
} 
Example 25
Source File: VatReturnResponse.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.resources.wrappers

import play.api.http.Status
import play.api.libs.json.{JsError, JsSuccess, JsValue}
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.vatapi.httpparsers.NRSData
import uk.gov.hmrc.vatapi.models.des.DesErrorCode._
import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, VatReturn, des}
import uk.gov.hmrc.vatapi.resources.VatResult

case class VatReturnResponse(underlying: HttpResponse) extends Response {

  var nrsData: NRSData = _

  def vatReturnOrError: Either[DesTransformError, VatReturn] = {

    def deserialise(js: JsValue) = js.validate[des.VatReturn] match {
      case JsError(errors) => Left(ParseError(s"Json format from DES doesn't match the VatReturn model: $errors"))
      case JsSuccess(vatReturn, _) => DesTransformValidator[des.VatReturn, VatReturn].from(vatReturn)
    }

    jsonOrError match {
      case Left(e) =>
        logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e")
        Left(ParseError(s"Unable to parse the response from DES as Json: $e"))
      case Right(js) =>
        deserialise(js)
    }
  }

  def vatSubmissionReturnOrError: Either[DesTransformError, JsValue] = {
    jsonOrError match {
      case Left(e) =>
        logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e")
        Left(ParseError(s"Unable to parse the response from DES as Json: $e"))
      case Right(js) => Right(js)
    }
  }

  def withNrsData(data: NRSData): VatReturnResponse = {
    nrsData = data;
    this
  }

  override def errorMappings: PartialFunction[Int, VatResult] = {
    case 400 if errorCodeIsOneOf(INVALID_VRN) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid)
    case 400 if errorCodeIsOneOf(INVALID_ARN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError)
    case 400 if errorCodeIsOneOf(INVALID_ORIGINATOR_ID) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError)
    case 400 if errorCodeIsOneOf(INVALID_PAYLOAD) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidRequest)
    case 400 if errorCodeIsOneOf(INVALID_PERIODKEY) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidPeriodKey)
    case 400 if errorCodeIsOneOf(INVALID_SUBMISSION) =>
      logger.info(s"[VatReturnResponse][errorMappings] Des returned error with status 400 and errorCode INVALID_SUBMISSION")
      VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError)
    case 403 if errorCodeIsOneOf(DATE_RANGE_TOO_LARGE) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DateRangeTooLarge))
    case 403 if errorCodeIsOneOf(VRN_NOT_FOUND, NOT_FOUND_VRN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError)
    case 403 if errorCodeIsOneOf(INVALID_IDENTIFIER) => VatResult.Failure(Status.NOT_FOUND, Errors.InvalidPeriodKey)
    case 403 if errorCodeIsOneOf(INVALID_INPUTDATA) => VatResult.Failure(Status.FORBIDDEN, Errors.InvalidRequest)
    case 403 if errorCodeIsOneOf(TAX_PERIOD_NOT_ENDED) => VatResult.Failure(Status.FORBIDDEN, Errors.TaxPeriodNotEnded)
    case 409 if errorCodeIsOneOf(DUPLICATE_SUBMISSION) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DuplicateVatSubmission))

  }
}

case class ParseError(msg: String) extends DesTransformError 
Example 26
Source File: FinancialDataResponse.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.resources.wrappers

import play.api.http.Status
import play.api.libs.json.{JsError, JsSuccess, JsValue}
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.vatapi.models.des.DesErrorCode._
import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, Liabilities, Payments, des}
import uk.gov.hmrc.vatapi.resources.VatResult

case class FinancialDataResponse(underlying: HttpResponse) extends Response {

  def getLiabilities(vrn: Vrn): Either[DesTransformError, Liabilities] = {

    def deserialise(js: JsValue) = js.validate[des.FinancialData] match {
      case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getLiabilities - deserialise] Json format from DES doesn't match the FinancialData model:  $errors"))
      case JsSuccess(financialData, _) =>
        DesTransformValidator[des.FinancialData, Liabilities].from(financialData)
    }

    jsonOrError match {
      case Right(js) =>
        logger.debug(s"[FinancialDataResponse][getLiabilities - jsonOrError] Json response body from DES : ${js}")
        deserialise(js)
      case Left(e) =>
        logger.error(s"[FinancialDataResponse][getLiabilities - jsonOrError] Non json response from DES : ${e.getMessage}")
        Left(ParseError(s"Unable to parse the response from DES as Json: $e"))
    }
  }

  def getPayments(vrn: Vrn): Either[DesTransformError, Payments] = {
    def deserialise(js: JsValue) = js.validate[des.FinancialData] match {
      case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getPayments - deserialise] Json format from DES doesn't match the FinancialData model: $errors"))
      case JsSuccess(financialData, _) => DesTransformValidator[des.FinancialData, Payments].from(financialData)
    }

    jsonOrError match {
      case Right(js) =>
        logger.debug(s"[FinancialDataResponse][getPayments - jsonOrError] Json response body from DES : ${js}")
        deserialise(js)
      case Left(e) =>
        logger.error(s"[FinancialDataResponse][getPayments - jsonOrError] Non json response from DES : ${e.getMessage}")
        Left(ParseError(s"Unable to parse the response from DES as Json: $e"))
    }
  }

  override def errorMappings: PartialFunction[Int, VatResult] = {
    case 400 if errorCodeIsOneOf(INVALID_IDNUMBER) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid)
    case 400 if errorCodeIsOneOf(INVALID_DATEFROM) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidDateFrom)
    case 400 if errorCodeIsOneOf(INVALID_DATETO) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidDateTo)
    case 400 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND, Errors.NotFound)
    case 400 if errorCodeIsOneOf(INVALID_IDTYPE, INVALID_ONLYOPENITEMS, INVALID_REGIMETYPE,
      INVALID_INCLUDELOCKS, INVALID_CALCULATEACCRUEDINTEREST, INVALID_CUSTOMERPAYMENTINFORMATION
    ) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError)
    case 404 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND,Errors.NotFound)
    case 422 if errorCodeIsOneOf(INVALID_DATA) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidData)
  }

} 
Example 27
Source File: WsParser.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.connectors.httpparsers

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

import scala.util.{Success, Try}

trait WsParser {

  implicit class KnownJsonResponse(response: WSResponse) {

    def validateJson[T](implicit reads: Reads[T]): Option[T] = {
      Try(response.json) match {
        case Success(json: JsValue) => parseResult(json)
        case _ =>
          Logger.warn("[KnownJsonResponse][validateJson - NRS] No JSON was returned")
          None
      }
    }

    def parseResult[T](json: JsValue)(implicit reads: Reads[T]): Option[T] = json.validate[T] match {

      case JsSuccess(value, _) => Some(value)
      case JsError(error) =>
        Logger.warn(s"[KnownJsonResponse][validateJson - NRS] Unable to parse JSON: $error")
        None
    }
  }
} 
Example 28
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 29
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 30
Source File: TestJson.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.repository.voc

import java.io.FileInputStream

import catalog_manager.yaml.KeyValue
import play.api.libs.json.{JsArray, JsValue}

object TestJson extends App {
  import play.api.libs.json.{JsError, JsResult, JsSuccess, Json}

  val stream = new FileInputStream("data/voc/cv_theme-subtheme_bk.json")
  val json = try { (Json.parse(stream) \ "voc").asOpt[JsArray]} finally {stream.close()}
  val dcatapitThemeId = "AGRI"
  val subthemeId = "policy"
  print {
    json match {
      case Some(s) => s.value.map(x => ((x \ "theme_code").as[String],
        (x \ "subthemes").as[List[JsValue]])).map{ x=>

        x._2.map{ y=> //subthemes

          (x._1, (y \ "subthemes_ita").as[List[List[String]]])
        }
      }.flatten
        .filter(x=>x._1.equals(dcatapitThemeId))
        .map{x=>
          println(x)
          x._2.map{y=>
            println(y)
            println(y.length)
            //println(y(0))
            //println(y(1))
            KeyValue(y(0), y(1))
          }
        }.flatMap(x=>x)
      case None =>
        println("VocRepositoryFile - Error occurred with Json")
        Seq()
    }
  }

} 
Example 31
Source File: EitherReads.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import play.api.libs.json.{JsError, JsSuccess, Reads}

object EitherReads {
  implicit def eitherReads[A, B](implicit A: Reads[A], B: Reads[B]): Reads[Either[A, B]] =
    Reads[Either[A, B]] { json =>
      A.reads(json) match {
        case JsSuccess(value, path) => JsSuccess(Left(value), path)
        case JsError(e1) => B.reads(json) match {
          case JsSuccess(value, path) => JsSuccess(Right(value), path)
          case JsError(e2) => JsError(JsError.merge(e1, e2))
        }
      }
    }
} 
Example 32
Source File: SttpBackendOps.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.sttp

import java.util.UUID

import cats.syntax.flatMap._
import com.softwaremill.sttp.playJson.asJson
import com.softwaremill.sttp.{DeserializationError, Id, RequestT, SttpBackend}
import com.wavesplatform.dex.it.fp.{CanWait, FOps, ThrowableMonadError}
import play.api.libs.json.{JsError, Reads}

class SttpBackendOps[F[_]: CanWait: ThrowableMonadError, ErrorT: Reads](implicit httpBackend: SttpBackend[F, Nothing]) {

  private val ops = FOps[F]; import ops._

  def tryParse[ResultT](req: RequestT[Id, Either[DeserializationError[JsError], ResultT], Nothing]): F[Either[ErrorT, ResultT]] =
    httpBackend.send(req.tag("requestId", UUID.randomUUID)).flatMap(parseTryResponseEither[ErrorT, ResultT])

  def tryParseJson[ResultT: Reads](req: RequestT[Id, String, Nothing]): F[Either[ErrorT, ResultT]] =
    httpBackend.send(req.response(asJson[ResultT]).tag("requestId", UUID.randomUUID)).flatMap(parseTryResponseEither[ErrorT, ResultT])

  def tryUnit(req: RequestT[Id, String, Nothing]): F[Either[ErrorT, Unit]] =
    httpBackend.send(req.mapResponse(_ => ()).tag("requestId", UUID.randomUUID)).flatMap(parseTryResponse[ErrorT, Unit])
}

object SttpBackendOps {
  def apply[F[_]: CanWait: ThrowableMonadError, ErrorT: Reads](implicit httpBackend: SttpBackend[F, Nothing]): SttpBackendOps[F, ErrorT] =
    new SttpBackendOps[F, ErrorT]
} 
Example 33
Source File: ResponseParsers.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.sttp

import com.google.common.primitives.Longs
import com.softwaremill.sttp.{DeserializationError, ResponseAs, MonadError => _, _}
import com.typesafe.config.{Config, ConfigFactory}
import play.api.libs.json.JsError

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

object ResponseParsers {

  val asUtf8String: ResponseAs[String, Nothing] = asString("UTF-8")

  def asLong: ResponseAs[Either[DeserializationError[JsError], Long], Nothing] =
    asUtf8String.map { string =>
      val r = Longs.tryParse(string)
      if (r == null) Left(DeserializationError[JsError](string, JsError("Can't parse Long"), "Can't parse Long"))
      else Right(r)
    }

  def asConfig: ResponseAs[Either[DeserializationError[JsError], Config], Nothing] =
    asUtf8String.map { string =>
      Try(ConfigFactory.parseString(string)) match {
        case Success(r) => Right(r)
        case Failure(e) => Left(DeserializationError[JsError](string, JsError("Can't parse Config"), s"Can't parse Config: ${e.getMessage}"))
      }
    }
}