play.api.libs.json.Reads Scala Examples

The following examples show how to use play.api.libs.json.Reads. 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: PipelineClass.scala    From daf   with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
package it.gov.daf.ingestion.pipelines.data

import ingestion_manager.yaml.PipelineInfo
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}

object PipelineClass {

  implicit val pipelineInfoReads: Reads[PipelineInfo] = (
    (JsPath \ "name").read[String] and
      (JsPath \ "description").read[String] and
      (JsPath \ "id").read[String] and
      (JsPath \ "default_stream").read[Boolean] and
      (JsPath \ "category").read[String] and
      (JsPath \ "default_batch").read[Boolean]

    )(PipelineInfo.apply _)

} 
Example 2
Source File: GraphQlClient.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.graphql

import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import cool.graph.akkautil.SingleThreadedActorSystem
import play.api.libs.json.{JsPath, JsValue, Json, Reads}

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

trait GraphQlClient {
  def sendQuery(query: String): Future[GraphQlResponse]
}

object GraphQlClient {
  private implicit lazy val actorSystem       = SingleThreadedActorSystem("graphql-client")
  private implicit lazy val actorMaterializer = ActorMaterializer()(actorSystem)
  private implicit lazy val akkaHttp          = Http()(actorSystem)

  def apply(uri: String, headers: Map[String, String] = Map.empty): GraphQlClient = {
    GraphQlClientImpl(uri, headers, akkaHttp)
  }
}

case class GraphQlResponse(status: Int, body: String) {
  def bodyAs[T](path: String)(implicit reads: Reads[T]): Try[T] = {
    def jsPathForElements(pathElements: Seq[String], current: JsPath = JsPath()): JsPath = {
      if (pathElements.isEmpty) {
        current
      } else {
        jsPathForElements(pathElements.tail, current \ pathElements.head)
      }
    }
    val jsPath      = jsPathForElements(path.split('.'))
    val actualReads = jsPath.read(reads)
    jsonBody.map(_.as(actualReads))
  }

  val is2xx: Boolean = status >= 200 && status <= 299
  val is200: Boolean = status == 200
  val is404: Boolean = status == 404

  def isSuccess: Boolean = deserializedBody match {
    case Success(x) => x.errors.isEmpty && is200
    case Failure(e) => false
  }

  def isFailure: Boolean       = !isSuccess
  def firstError: GraphQlError = deserializedBody.get.errors.head

  private lazy val deserializedBody: Try[GraphQlResponseJson] = {
    for {
      body     <- jsonBody
      response <- Try { body.as(JsonReaders.graphqlResponseReads) }
    } yield response
  }

  lazy val jsonBody: Try[JsValue] = Try(Json.parse(body))
}

case class GraphQlResponseJson(data: JsValue, errors: Seq[GraphQlError])
case class GraphQlError(message: String, code: Int)

object JsonReaders {
  import play.api.libs.functional.syntax._
  import play.api.libs.json._

  implicit lazy val graphqlErrorReads = Json.reads[GraphQlError]
  implicit lazy val graphqlResponseReads = (
    (JsPath \ "data").read[JsValue] and
      (JsPath \ "errors").readNullable[Seq[GraphQlError]].map(_.getOrElse(Seq.empty))
  )(GraphQlResponseJson.apply _)
} 
Example 3
Source File: Utilities.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.kernel

import java.nio.charset.Charset

import akka.util.{ByteString, Timeout}
import org.apache.toree.communication.ZMQMessage
import org.apache.toree.kernel.protocol.v5._
import org.apache.toree.utils.LogLike
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsPath, Json, Reads}

import scala.concurrent.duration._

object Utilities extends LogLike {
  //
  // NOTE: This is brought in to remove feature warnings regarding the use of
  //       implicit conversions regarding the following:
  //
  //       1. ByteStringToString
  //       2. ZMQMessageToKernelMessage
  //
  import scala.language.implicitConversions

  
  implicit val timeout = Timeout(21474835.seconds)

  implicit def ByteStringToString(byteString : ByteString) : String = {
    new String(byteString.toArray, Charset.forName("UTF-8"))
  }

  implicit def StringToByteString(string : String) : ByteString = {
    ByteString(string.getBytes)
  }

  implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = {
    val delimiterIndex: Int =
      message.frames.indexOf(ByteString("<IDS|MSG>".getBytes))
    //  TODO Handle the case where there is no delimiter
    val ids: Seq[Array[Byte]] =
      message.frames.take(delimiterIndex).map(
        (byteString : ByteString) =>  { byteString.toArray }
      )
    val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header]
    // TODO: Investigate better solution than setting parentHeader to null for {}
    val parentHeader = parseAndHandle(message.frames(delimiterIndex + 3),
                                  ParentHeader.headerReads,
                                  handler = (valid: ParentHeader) => valid,
                                  errHandler = _ => null
    )
    val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata]

    KMBuilder().withIds(ids.toList)
               .withSignature(message.frame(delimiterIndex + 1))
               .withHeader(header)
               .withParentHeader(parentHeader)
               .withMetadata(metadata)
               .withContentString(message.frame(delimiterIndex + 5)).build(false)
  }

  implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = {
    val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer()
    kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) )
    frames += "<IDS|MSG>"
    frames += kernelMessage.signature
    frames += Json.toJson(kernelMessage.header).toString()
    frames += Json.toJson(kernelMessage.parentHeader).toString()
    frames += Json.toJson(kernelMessage.metadata).toString
    frames += kernelMessage.contentString
    ZMQMessage(frames  : _*)
  }

  def parseAndHandle[T, U](json: String, reads: Reads[T],
                           handler: T => U) : U = {
    parseAndHandle(json, reads, handler,
      (invalid: Seq[(JsPath, Seq[ValidationError])]) => {
        logger.error(s"Could not parse JSON, ${json}")
        throw new Throwable(s"Could not parse JSON, ${json}")
      }
    )
  }

  def parseAndHandle[T, U](json: String, reads: Reads[T],
                           handler: T => U,
                           errHandler: Seq[(JsPath, Seq[ValidationError])] => U) : U = {
    Json.parse(json).validate[T](reads).fold(
      errHandler,
      (content: T) => handler(content)
    )
  }
} 
Example 4
Source File: Utilities.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.client

import java.nio.charset.Charset

import akka.util.{ByteString, Timeout}
import org.apache.toree.communication.ZMQMessage
import org.apache.toree.kernel.protocol.v5._
import org.apache.toree.kernel.protocol.v5.content.ExecuteRequest
import org.apache.toree.utils.LogLike
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsPath, Json, Reads}

import scala.concurrent.duration._

object Utilities extends LogLike {
  //
  // NOTE: This is brought in to remove feature warnings regarding the use of
  //       implicit conversions regarding the following:
  //
  //       1. ByteStringToString
  //       2. ZMQMessageToKernelMessage
  //
  import scala.language.implicitConversions

  private val sessionId: UUID = java.util.UUID.randomUUID().toString

  
  implicit val timeout = Timeout(21474835.seconds) // Maximum delay

  implicit def ByteStringToString(byteString : ByteString) : String = {
    new String(byteString.toArray, Charset.forName("UTF-8"))
  }

  implicit def StringToByteString(string : String) : ByteString = {
    ByteString(string.getBytes)
  }

  implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = {
    val delimiterIndex: Int =
      message.frames.indexOf(ByteString("<IDS|MSG>".getBytes))
    //  TODO Handle the case where there is no delimiter
    val ids: Seq[Array[Byte]] =
      message.frames.take(delimiterIndex).map(
        (byteString : ByteString) =>  { byteString.toArray }
      )
    val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header]
    val parentHeader = Json.parse(message.frames(delimiterIndex + 3)).validate[ParentHeader].fold[ParentHeader](
      // TODO: Investigate better solution than setting parentHeader to null for {}
      (invalid: Seq[(JsPath, Seq[ValidationError])]) => null, //HeaderBuilder.empty,
      (valid: ParentHeader) => valid
    )
    val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata]

    KMBuilder().withIds(ids.toList)
               .withSignature(message.frame(delimiterIndex + 1))
               .withHeader(header)
               .withParentHeader(parentHeader)
               .withMetadata(metadata)
               .withContentString(message.frame(delimiterIndex + 5)).build(false)
  }

  implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = {
    val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer()
    kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) )
    frames += "<IDS|MSG>"
    frames += kernelMessage.signature
    frames += Json.toJson(kernelMessage.header).toString()
    frames += Json.toJson(kernelMessage.parentHeader).toString()
    frames += Json.toJson(kernelMessage.metadata).toString
    frames += kernelMessage.contentString
    ZMQMessage(frames  : _*)
  }

  def parseAndHandle[T](json: String, reads: Reads[T], handler: T => Unit) : Unit = {
    Json.parse(json).validate[T](reads).fold(
      (invalid: Seq[(JsPath, Seq[ValidationError])]) =>
        logger.error(s"Could not parse JSON, ${json}"),
      (content: T) => handler(content)
    )
  }

  def getSessionId = sessionId

  def toKernelMessage(message: ExecuteRequest): KernelMessage = {
    // construct a kernel message whose content is an ExecuteRequest
    val id = java.util.UUID.randomUUID().toString
    val header = Header(
      id, "spark", sessionId, MessageType.Incoming.ExecuteRequest.toString, "5.0")

    KMBuilder().withIds(Seq[Array[Byte]]()).withSignature("").withHeader(header)
      .withParentHeader(HeaderBuilder.empty).withContentString(message).build
  }

} 
Example 5
Source File: IsCompleteRequest.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.content

import org.apache.toree.kernel.protocol.v5.KernelMessageContent
import play.api.libs.json.{Json, Reads, Writes}

case class IsCompleteRequest(
                            code: String
                          ) extends KernelMessageContent {
  override def content : String =
    Json.toJson(this)(IsCompleteRequest.isCompleteRequestWrites).toString
}

object IsCompleteRequest extends TypeString {
  implicit val isCompleteRequestReads: Reads[IsCompleteRequest] = Json.reads[IsCompleteRequest]
  implicit val isCompleteRequestWrites: Writes[IsCompleteRequest] = Json.writes[IsCompleteRequest]

  
  override def toTypeString: String = "is_complete_request"
} 
Example 6
Source File: IsCompleteReply.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.content

import org.apache.toree.kernel.protocol.v5.{KernelMessageContent}
import play.api.libs.json.{Json, Reads, Writes}

case class IsCompleteReply (
                           status: String,
                           indent: String
                         ) extends KernelMessageContent {
  override def content : String =
    Json.toJson(this)(IsCompleteReply.isCompleteReplyWrites).toString
}

object IsCompleteReply extends TypeString {
  implicit val isCompleteReplyReads: Reads[IsCompleteReply] = Json.reads[IsCompleteReply]
  implicit val isCompleteReplyWrites: Writes[IsCompleteReply] = Json.writes[IsCompleteReply]

  
  override def toTypeString: String = "complete_reply"
} 
Example 7
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 8
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 9
Source File: ApiUser.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.api.domain

import gospeak.core.domain.User
import gospeak.core.domain.utils.{BasicCtx, Constants}
import gospeak.libs.scala.domain.{EmailAddress, Secret}
import gospeak.web.api.domain.utils.ApiSocial
import gospeak.web.api.domain.utils.JsonFormats._
import gospeak.web.utils.GsForms
import play.api.libs.json.{Json, Reads, Writes}

object ApiUser {

  // data to display publicly
  final case class Published(slug: String,
                             firstName: String,
                             lastName: String,
                             avatar: String,
                             bio: Option[String],
                             website: Option[String],
                             social: ApiSocial)

  object Published {
    implicit val writes: Writes[Published] = Json.writes[Published]
  }

  def published(user: User.Full)(implicit ctx: BasicCtx): Published =
    new Published(
      slug = user.slug.value,
      firstName = user.firstName,
      lastName = user.lastName,
      avatar = user.avatar.url.value,
      bio = user.bio.map(_.value),
      website = user.website.map(_.value),
      social = ApiSocial.from(user.social))

  // embedded data in other models, should be public
  final case class Embed(slug: String,
                         firstName: String,
                         lastName: String,
                         avatar: String,
                         bio: Option[String],
                         website: Option[String],
                         social: ApiSocial)

  object Embed {
    implicit val writes: Writes[Embed] = Json.writes[Embed]
  }

  def embed(id: User.Id, users: Seq[User])(implicit ctx: BasicCtx): Embed =
    users.find(_.id == id).map(embed).getOrElse(unknown(id))

  def embed(user: User)(implicit ctx: BasicCtx): Embed =
    new Embed(
      slug = user.slug.value,
      firstName = user.firstName,
      lastName = user.lastName,
      avatar = user.avatar.url.value,
      bio = user.bio.map(_.value),
      website = user.website.map(_.value),
      social = ApiSocial.from(user.social))

  def unknown(id: User.Id)(implicit ctx: BasicCtx): Embed =
    new Embed(
      slug = "unknown",
      firstName = "Unknown",
      lastName = "User",
      avatar = Constants.Placeholders.unknownUser,
      bio = None,
      website = None,
      social = ApiSocial(None, None, None, None, None, None, None, None, None, None))

  final case class SignupPayload(firstName: String,
                                 lastName: String,
                                 username: User.Slug,
                                 email: EmailAddress,
                                 password: Secret,
                                 rememberMe: Option[Boolean]) {
    def asData: GsForms.SignupData = GsForms.SignupData(username, firstName, lastName, email, password, rememberMe.getOrElse(false))
  }

  object SignupPayload {
    implicit val reads: Reads[SignupPayload] = Json.reads[SignupPayload]
  }

  final case class LoginPayload(email: EmailAddress,
                                password: Secret,
                                rememberMe: Option[Boolean]) {
    def asData: GsForms.LoginData = GsForms.LoginData(email, password, rememberMe.getOrElse(false))
  }

  object LoginPayload {
    implicit val reads: Reads[LoginPayload] = Json.reads[LoginPayload]
  }

} 
Example 10
Source File: playjson.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s

import java.nio.charset.Charset

import org.apache.pulsar.client.api.Schema
import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType}
import play.api.libs.json.{Json, Reads, Writes}

import scala.annotation.implicitNotFound

package object playjson {

  @implicitNotFound("No Writes or Reads for type ${T} found. Bring an implicit Writes[T] and Reads[T] instance in scope")
  implicit def playSchema[T: Manifest](implicit w: Writes[T], r: Reads[T]): Schema[T] = new Schema[T] {
    override def clone(): Schema[T] = this
    override def encode(t: T): Array[Byte] = Json.stringify(Json.toJson(t)(w)).getBytes(Charset.forName("UTF-8"))
    override def decode(bytes: Array[Byte]): T = Json.parse(bytes).as[T]
    override def getSchemaInfo: SchemaInfo =
      new SchemaInfo()
        .setName(manifest[T].runtimeClass.getCanonicalName)
        .setType(SchemaType.JSON)
        .setSchema("""{"type":"any"}""".getBytes("UTF-8"))
  }
} 
Example 11
Source File: SignedSetAssetScriptRequest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.PublicKey
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.lang.script.Script
import com.wavesplatform.transaction.Asset.IssuedAsset
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.assets.SetAssetScriptTransaction
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}

object SignedSetAssetScriptRequest {
  implicit val signedSetAssetScriptRequestReads: Reads[SignedSetAssetScriptRequest] = (
    (JsPath \ "version").readNullable[Byte] and
      (JsPath \ "senderPublicKey").read[String] and
      (JsPath \ "assetId").read[IssuedAsset] and
      (JsPath \ "script").readNullable[String] and
      (JsPath \ "fee").read[Long] and
      (JsPath \ "timestamp").read[Long] and
      (JsPath \ "proofs").read[Proofs]
  )(SignedSetAssetScriptRequest.apply _)
}

case class SignedSetAssetScriptRequest(
    version: Option[Byte],
    senderPublicKey: String,
    assetId: IssuedAsset,
    script: Option[String],
    fee: Long,
    timestamp: Long,
    proofs: Proofs
) {
  def toTx: Either[ValidationError, SetAssetScriptTransaction] =
    for {
      _sender <- PublicKey.fromBase58String(senderPublicKey)
      _script <- script match {
        case None | Some("") => Right(None)
        case Some(s)         => Script.fromBase64String(s).map(Some(_))
      }
      t <- SetAssetScriptTransaction.create(version.getOrElse(1.toByte), _sender, assetId, _script, fee, timestamp, proofs)
    } yield t
} 
Example 12
Source File: Webhook.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.webhook

import cool.graph.messagebus.Conversions
import play.api.libs.json.{Json, Reads, Writes}

object Webhook {
  implicit val mapStringReads  = Reads.mapReads[String]
  implicit val mapStringWrites = Writes.mapWrites[String]
  implicit val webhooksWrites  = Json.format[Webhook]
  implicit val marshaller      = Conversions.Marshallers.FromJsonBackedType[Webhook]()
  implicit val unmarshaller    = Conversions.Unmarshallers.ToJsonBackedType[Webhook]()
}

case class Webhook(
    projectId: String,
    functionId: String,
    requestId: String,
    url: String,
    payload: String,
    id: String,
    headers: Map[String, String]
) 
Example 13
Source File: HatClaims.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 play.api.libs.json.{ JsPath, Json, Reads, Writes }
import play.api.libs.functional.syntax._

case class ApiClaimHatRequest(applicationId: String, email: String)

object ApiClaimHatRequest {
  implicit val claimHatRequestApiReads: Reads[ApiClaimHatRequest] = (
    (JsPath \ "applicationId").read[String] and (JsPath \ "email").read[String](Reads.email))(ApiClaimHatRequest.apply _)

  implicit val claimHatRequestApiWrites: Writes[ApiClaimHatRequest] = Json.format[ApiClaimHatRequest]

}

case class HatClaimCompleteRequest(
    email: String,
    termsAgreed: Boolean,
    optins: Array[String],
    hatName: String,
    hatCluster: String,
    password: String)

case class HattersClaimPayload(
    email: String,
    termsAgreed: Boolean,
    sandbox: Boolean,
    platform: String,
    newsletterOptin: Option[Boolean],
    hatName: String,
    hatCluster: String)

object HatClaimCompleteRequest {
  implicit val hatClaimRequestReads: Reads[HatClaimCompleteRequest] = Json.reads[HatClaimCompleteRequest]
}

object HattersClaimPayload {
  def apply(claim: HatClaimCompleteRequest): HattersClaimPayload = new HattersClaimPayload(
    claim.email, claim.termsAgreed, claim.hatCluster == "hubat.net", "web", Some(claim.optins.nonEmpty), claim.hatName, claim.hatCluster)
  implicit val HatClaimRequestWrites: Writes[HattersClaimPayload] = Json.format[HattersClaimPayload]
} 
Example 14
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 15
Source File: RPC.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index.client
package rpc

import ch.epfl.scala.index.api.{AutocompletionResponse, SearchRequest}
import org.scalajs.dom.ext.Ajax
import play.api.libs.json.{Json, Reads}

import scala.concurrent.Future
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue

object RPC {
  def autocomplete(
      request: SearchRequest
  ): Future[List[AutocompletionResponse]] = {
    val params = request.toHttpParams
      .map { case (key, value) => s"$key=$value" }
      .mkString("&")

    Ajax
      .get(s"/api/autocomplete?$params")
      .map(_.responseText)
      .map(read[List[AutocompletionResponse]](_))
  }

  private def read[T: Reads](p: String): T = Json.parse(p).as[T]
} 
Example 16
Source File: Github.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.web.oauth2

import com.olegych.scastie.web.PlayJsonSupport

import akka.http.scaladsl._
import akka.http.scaladsl.model._
import HttpMethods.POST
import headers._
import Uri._
import unmarshalling.Unmarshal

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.olegych.scastie.api.User

import scala.concurrent.Future
import com.typesafe.config.ConfigFactory
import play.api.libs.json.{OFormat, Reads}

case class AccessToken(access_token: String)

class Github(implicit system: ActorSystem, materializer: ActorMaterializer) extends PlayJsonSupport {
  import system.dispatcher

  import play.api.libs.json._
  implicit val formatUser: OFormat[User] = Json.format[User]
  implicit val readAccessToken: Reads[AccessToken] = Json.reads[AccessToken]

  private val config =
    ConfigFactory.load().getConfig("com.olegych.scastie.web.oauth2")
  val clientId: String = config.getString("client-id")
  private val clientSecret = config.getString("client-secret")
  private val redirectUri = config.getString("uri") + "/callback"

  def getUserWithToken(token: String): Future[User] = info(token)
  def getUserWithOauth2(code: String): Future[User] = {
    def access = {
      Http()
        .singleRequest(
          HttpRequest(
            method = POST,
            uri = Uri("https://github.com/login/oauth/access_token").withQuery(
              Query(
                "client_id" -> clientId,
                "client_secret" -> clientSecret,
                "code" -> code,
                "redirect_uri" -> redirectUri
              )
            ),
            headers = List(Accept(MediaTypes.`application/json`))
          )
        )
        .flatMap(
          response => Unmarshal(response).to[AccessToken].map(_.access_token)
        )
    }

    access.flatMap(info)
  }

  private def info(token: String): Future[User] = {
    def fetchGithub(path: Path, query: Query = Query.Empty) = {
      HttpRequest(
        uri = Uri(s"https://api.github.com").withPath(path).withQuery(query),
        headers = List(Authorization(GenericHttpCredentials("token", token)))
      )
    }

    Http()
      .singleRequest(fetchGithub(Path.Empty / "user"))
      .flatMap(response => Unmarshal(response).to[User])
  }
} 
Example 17
Source File: Node.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.nomad.models

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}
import shapeless.tag
import shapeless.tag.@@


final case class Node(
    id: String @@ Node.Id,
    name: String @@ Node.Name,
    httpAddress: String @@ Node.HttpAddress
)

object Node {
  sealed trait Id
  sealed trait Name
  sealed trait HttpAddress

  implicit val nodeReads: Reads[Node] = (
    (JsPath \ "ID").read[String].map(tag[Id](_)) and
      (JsPath \ "Name").read[String].map(tag[Name](_)) and
      (JsPath \ "HTTPAddr").read[String].map(tag[HttpAddress](_))
  )(Node.apply _)
} 
Example 18
Source File: Allocation.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.nomad.models

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}
import shapeless.tag
import shapeless.tag.@@


final case class Allocation(
    id: String @@ Allocation.Id,
    jobId: String @@ Job.Id,
    nodeId: String @@ Node.Id,
    clientStatus: ClientStatus,
    taskStates: Map[String @@ Task.Name, TaskStateEvents]
)

object Allocation {
  trait Id

  implicit val allocationReads: Reads[Allocation] =
    ((JsPath \ "ID").read[String].map(tag[Allocation.Id](_)) and
      (JsPath \ "JobID").read[String].map(tag[Job.Id](_)) and
      (JsPath \ "NodeID").read[String].map(tag[Node.Id](_)) and
      (JsPath \ "ClientStatus").read[ClientStatus] and
      (JsPath \ "TaskStates")
        .readNullable[Map[String, TaskStateEvents]]
        // Tag all values as task name. Since Task.Name is a phantom type this is a safe thing to do, albeit it doesn't
        // look like so
        .map(_.getOrElse(Map.empty).asInstanceOf[Map[String @@ Task.Name, TaskStateEvents]]))(Allocation.apply _)
} 
Example 19
Source File: play.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.interop.play

import caliban.introspection.adt.__Type
import caliban.schema.Step.QueryStep
import caliban.schema.Types.makeScalar
import caliban.schema.{ ArgBuilder, PureStep, Schema, Step }
import caliban.{ InputValue, ResponseValue }
import play.api.libs.json.{ JsPath, JsValue, Json, JsonValidationError, Reads, Writes }
import zio.ZIO
import zio.query.ZQuery


private[caliban] trait IsPlayJsonReads[F[_]]
private[caliban] object IsPlayJsonReads {
  implicit val isPlayJsonReads: IsPlayJsonReads[Reads] = null
}

object json {
  implicit val jsonSchema: Schema[Any, JsValue] = new Schema[Any, JsValue] {
    private def parse(value: JsValue) =
      implicitly[Reads[ResponseValue]]
        .reads(value)
        .asEither
        .left
        .map(parsingException)

    override def toType(isInput: Boolean, isSubscription: Boolean): __Type = makeScalar("Json")
    override def resolve(value: JsValue): Step[Any] =
      QueryStep(ZQuery.fromEffect(ZIO.fromEither(parse(value))).map(PureStep))
  }
  implicit val jsonArgBuilder: ArgBuilder[JsValue] = (input: InputValue) => Right(Json.toJson(input))

  private[caliban] def parsingException(
    errs: scala.collection.Seq[(JsPath, scala.collection.Seq[JsonValidationError])]
  ) =
    new Throwable(s"Couldn't decode json: $errs")
} 
Example 20
Source File: ClusterTest.scala    From exhibitor-mesos-framework   with Apache License 2.0 5 votes vote down vote up
package ly.stealth.mesos.exhibitor

import org.junit.Assert._
import org.junit.Test
import play.api.libs.json.{Writes, Reads}

import scala.util.{Failure, Try}

class ClusterTest extends MesosTestCase {
  @Test
  def expandIds() {
    val cluster = Cluster()

    (0 until 5).foreach(i => cluster.addServer(ExhibitorServer("" + i)))

    Try(cluster.expandIds("")) match {
      case Failure(t) if t.isInstanceOf[IllegalArgumentException] =>
      case other => fail(other.toString)
    }

    assertEquals(List("0"), cluster.expandIds("0"))
    assertEquals(List("0", "2", "4"), cluster.expandIds("0,2,4"))

    assertEquals(List("1", "2", "3"), cluster.expandIds("1..3"))
    assertEquals(List("0", "1", "3", "4"), cluster.expandIds("0..1,3..4"))

    assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("*"))

    // duplicates
    assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("0..3,2..4"))

    // sorting
    assertEquals(List("2", "3", "4"), cluster.expandIds("4,3,2"))
  }

  @Test
  def loadSave() {
    val cluster = Cluster()
    cluster.frameworkId = Some("some id")
    cluster.save()

    val loaded = Cluster()
    loaded.load()

    assertEquals(cluster.frameworkId, loaded.frameworkId)
  }
} 
Example 21
Source File: Storage.scala    From exhibitor-mesos-framework   with Apache License 2.0 5 votes vote down vote up
package ly.stealth.mesos.exhibitor

import java.io.{File, FileWriter}

import play.api.libs.json.{Json, Reads, Writes}

import scala.io.Source

trait Storage[T] {
  def save(value: T)(implicit writes: Writes[T])

  def load(implicit reads: Reads[T]): Option[T]
}

case class FileStorage[T](file: String) extends Storage[T] {
  override def save(value: T)(implicit writes: Writes[T]) {
    val writer = new FileWriter(file)
    try {
      writer.write(Json.stringify(Json.toJson(value)))
    } finally {
      writer.close()
    }
  }

  override def load(implicit reads: Reads[T]): Option[T] = {
    if (!new File(file).exists()) None
    else Json.parse(Source.fromFile(file).mkString).asOpt[T]
  }
} 
Example 22
Source File: CopyingFormatsTest.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json
import play.api.libs.json.Reads

class CopyingFormatsTest extends AssertionsForJUnit {

  import CopyingFormatsTest._

  @Test
  def readNew(): Unit = {
    assertResult(JsSuccess(NewType("hi", "", 1))) {
      Json.fromJson[NewType](Json.obj("newField" -> "hi", "oldField" -> "", "unrelated" -> 1))
    }
  }

  @Test
  def readOld(): Unit = {
    assertResult(JsSuccess(NewType("", "", 1))) {
      Json.fromJson[NewType](Json.obj("oldField" -> "", "unrelated" -> 1))
    }
  }

}

object CopyingFormatsTest {

  case class NewType(newField: String, oldField: String, unrelated: Int)
  implicit val copyingReads: Reads[NewType] = CopyingFormats.copyingReads(
    Json.reads[NewType], "oldField" -> "newField")

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

import org.coursera.common.stringkey.StringKeyFormat
import play.api.libs.json.Json
import play.api.libs.json.OFormat
import play.api.libs.json.OWrites
import play.api.libs.json.Reads
import play.api.libs.json.__


object FlatTypedFormats {

  def flatTypedDefinitionFormat[T: StringKeyFormat, D](typeName: T, defaultFormat: OFormat[D]):
    OFormat[D] = {

    OFormat(
      flatTypedDefinitionReads(typeName, defaultFormat),
      flatTypedDefinitionWrites(typeName, defaultFormat))
  }

  def flatTypedDefinitionReads[T: StringKeyFormat, D](typeName: T, defaultReads: Reads[D]):
    Reads[D] = {

    import JsonFormats.Implicits.ReadsPathMethods
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]

    for {
      _ <- (__ \ "typeName").read[T].filter(_ == typeName).withRootPath
      definition <- {
        val typeNameDroppingReads = (__ \ "typeName").json.prune.withRootPath
        defaultReads.compose(typeNameDroppingReads)
      }
    } yield {
      definition
    }
  }

  def flatTypedDefinitionWrites[T: StringKeyFormat, D](typeName: T, defaultWrites: OWrites[D]):
    OWrites[D] = {

    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]
    OWrites { model: D =>
      val modelJson = defaultWrites.writes(model)

      require(!modelJson.keys.contains("typeName"), "Model cannot contain reserved field 'typeName'")
      modelJson + ("typeName" -> Json.toJson(typeName))
    }
  }

} 
Example 24
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 25
Source File: TypedFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.stringkey.StringKeyFormat
import play.api.libs.json.Format
import play.api.libs.json.Json
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 play.api.libs.json.__


object TypedFormats {

  def typedDefinitionFormat[T, D](
      typeName: T,
      defaultFormat: Format[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): OFormat[D] = {
    OFormat(
      typedDefinitionReads(typeName, defaultFormat),
      typedDefinitionWrites(typeName, defaultFormat))
  }

  def typedDefinitionReads[T, D](
      typeName: T,
      defaultReads: Reads[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): Reads[D] = {
    import JsonFormats.Implicits.ReadsPathMethods
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]

    for {
      _ <- (__ \ "typeName").read[T].filter(_ == typeName).withRootPath
      definition <- {
        val definitionExtractingReads = (__ \ "definition").json.pick.withRootPath
        defaultReads.compose(definitionExtractingReads)
      }
    } yield {
      definition
    }
  }

  def typedDefinitionWrites[T, D](
      typeName: T,
      defaultWrites: Writes[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): OWrites[D] = {
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]
    OWrites { model: D =>
      val modelJson = Json.toJson(model)(defaultWrites)
      Json.obj("typeName" -> typeName, "definition" -> modelJson)
    }
  }

} 
Example 26
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 27
Source File: SlackSearch.scala    From slack-client   with MIT License 5 votes vote down vote up
package com.kifi.slack.models

import org.joda.time.LocalDate
import play.api.libs.json.{Json, Reads}
import scala.language.implicitConversions

case class SlackSearchRequest(query: SlackSearchRequest.Query, optional: SlackSearchRequest.Param*)

object SlackSearchRequest {
  sealed abstract class Param(val name: String, val value: Option[String])

  case class Query(query: String) extends Param("query", Some(query))
  object Query {
    val trivial = Query("")
    def apply(queries: Option[Query]*): Query = Query(queries.flatten.map(_.query).mkString(" "))
    def in(channelName: SlackChannelName) = Query(s"in:#${channelName.value.stripPrefix("#").stripPrefix("@")}")
    def from(username: SlackUsername) = Query(s"from:${username.value}")
    def before(date: LocalDate) = Query(s"before:$date")
    def after(date: LocalDate) = Query(s"after:$date")
    val hasLink = Query(s"has:link")

    implicit val reads = Reads.of[String].map(Query(_))
  }

  sealed abstract class Sort(sort: String) extends Param("sort", Some(sort))
  object Sort {
    case object ByScore extends Sort("score")
    case object ByTimestamp extends Sort("timestamp")
  }

  sealed abstract class SortDirection(dir: String) extends Param("sort_dir", Some(dir))
  object SortDirection {
    case object Descending extends SortDirection("desc")
    case object Ascending extends SortDirection("asc")
  }

  object Highlight extends Param("highlight", Some("1"))

  case class Page(page: Int) extends Param("page", Some(page.toString))
  object Page {
    val max = 100
  }

  case class PageSize(count: Int) extends Param("count", Some(count.toString))
  object PageSize {
    val max = 1000
  }
}

case class SlackSearchResponse(query: SlackSearchRequest.Query, messages: SlackSearchResponse.Messages)
object SlackSearchResponse {
  val trivial = SlackSearchResponse(SlackSearchRequest.Query.trivial, SlackSearchResponse.Messages.empty)

  case class Paging(count: Int, total: Int, page: Int, pages: Int)
  object Paging {
    val empty = Paging(0, 0, 0, 0)
    implicit val reads = Json.reads[Paging]
  }
  case class Messages(total: Int, paging: Paging, matches: Seq[SlackMessage])
  object Messages {
    val empty = Messages(0, Paging.empty, Seq.empty)
    implicit val reads = Json.reads[Messages]
  }

  implicit val reads = Json.reads[SlackSearchResponse]
} 
Example 28
Source File: Domain.scala    From play-swagger   with Apache License 2.0 5 votes vote down vote up
package com.iheart.playSwagger

import play.api.libs.json.{ JsObject, JsPath, JsValue, Reads }
import play.twirl.api.TemplateMagic.Default

object Domain {
  type Path = String
  type Method = String

  final case class Definition(
    name:        String,
    properties:  Seq[SwaggerParameter],
    description: Option[String]        = None)

  sealed trait SwaggerParameter {
    def name: String
    def required: Boolean
    def default: Option[JsValue]

    def update(required: Boolean, default: Option[JsValue]): SwaggerParameter
  }

  final case class GenSwaggerParameter(
    name:          String,
    referenceType: Option[String]           = None,
    `type`:        Option[String]           = None,
    format:        Option[String]           = None,
    required:      Boolean                  = true,
    default:       Option[JsValue]          = None,
    example:       Option[JsValue]          = None,
    items:         Option[SwaggerParameter] = None,
    enum:          Option[Seq[String]]      = None) extends SwaggerParameter {
    def update(_required: Boolean, _default: Option[JsValue]) =
      copy(required = _required, default = _default)
  }

  final case class CustomSwaggerParameter(
    name:            String,
    specAsParameter: List[JsObject],
    specAsProperty:  Option[JsObject],
    required:        Boolean          = true,
    default:         Option[JsValue]  = None) extends SwaggerParameter {
    def update(_required: Boolean, _default: Option[JsValue]) =
      copy(required = _required, default = _default)
  }

  type CustomMappings = List[CustomTypeMapping]

  case class CustomTypeMapping(
    `type`:          String,
    specAsParameter: List[JsObject]   = Nil,
    specAsProperty:  Option[JsObject] = None,
    required:        Boolean          = true)

  object CustomTypeMapping {
    import play.api.libs.functional.syntax._
    implicit val csmFormat: Reads[CustomTypeMapping] = (
      (JsPath \ 'type).read[String] and
      (JsPath \ 'specAsParameter).read[List[JsObject]] and
      (JsPath \ 'specAsProperty).readNullable[JsObject] and
      ((JsPath \ 'required).read[Boolean] orElse Reads.pure(true)))(CustomTypeMapping.apply _)
  }
} 
Example 29
Source File: Storage.scala    From zipkin-mesos-framework   with Apache License 2.0 5 votes vote down vote up
package net.elodina.mesos.zipkin.storage

import java.io.{File, FileWriter}

import org.I0Itec.zkclient.ZkClient
import org.I0Itec.zkclient.exception.ZkNodeExistsException
import org.I0Itec.zkclient.serialize.ZkSerializer
import play.api.libs.json.{Json, Reads, Writes}

import scala.io.Source

trait Storage[T] {
  def save(value: T)(implicit writes: Writes[T])

  def load(implicit reads: Reads[T]): Option[T]
}

case class FileStorage[T](file: String) extends Storage[T] {
  override def save(value: T)(implicit writes: Writes[T]) {
    val writer = new FileWriter(file)
    try {
      writer.write(Json.stringify(Json.toJson(value)))
    } finally {
      writer.close()
    }
  }

  override def load(implicit reads: Reads[T]): Option[T] = {
    if (!new File(file).exists()) None
    else Json.parse(Source.fromFile(file).mkString).asOpt[T]
  }
}

case class ZkStorage[T](zk: String) extends Storage[T] {
  val (zkConnect, path) = zk.span(_ != '/')
  createChrootIfRequired()

  private def createChrootIfRequired() {
    if (path != "") {
      val client = zkClient
      try {
        client.createPersistent(path, true)
      }
      finally {
        client.close()
      }
    }
  }

  private def zkClient: ZkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer)

  override def save(value: T)(implicit writes: Writes[T]) {
    val client = zkClient
    val json = Json.stringify(Json.toJson(value))
    try {
      client.createPersistent(path, json)
    }
    catch {
      case e: ZkNodeExistsException => client.writeData(path, json)
    }
    finally {
      client.close()
    }
  }

  override def load(implicit reads: Reads[T]): Option[T] = {
    val client = zkClient
    try {
      Option(client.readData(path, true).asInstanceOf[String]).flatMap(Json.parse(_).asOpt[T])
    }
    finally {
      client.close()
    }
  }
}

private object ZKStringSerializer extends ZkSerializer {
  def serialize(data: Object): Array[Byte] = data.asInstanceOf[String].getBytes("UTF-8")

  def deserialize(bytes: Array[Byte]): Object = {
    if (bytes == null) null
    else new String(bytes, "UTF-8")
  }
} 
Example 30
Source File: SignedExchangeRequestV2.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import cats.implicits._
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order}
import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, JsPath, Reads}

object SignedExchangeRequestV2 {
  implicit val orderFormat: Format[Order] = com.wavesplatform.transaction.assets.exchange.OrderJson.orderFormat

  implicit val signedExchangeRequestReads: Reads[SignedExchangeRequestV2] = (
    (JsPath \ "senderPublicKey").read[String] and
      (JsPath \ "order1").read[Order] and
      (JsPath \ "order2").read[Order] and
      (JsPath \ "price").read[Long] and
      (JsPath \ "amount").read[Long] and
      (JsPath \ "fee").read[Long] and
      (JsPath \ "buyMatcherFee").read[Long] and
      (JsPath \ "sellMatcherFee").read[Long] and
      (JsPath \ "timestamp").read[Long] and
      (JsPath \ "version").read[Byte] and
      (JsPath \ "proofs").read[List[ProofStr]]
  )(SignedExchangeRequestV2.apply _)
}

case class SignedExchangeRequestV2(
    senderPublicKey: String,
    order1: Order,
    order2: Order,
    price: Long,
    amount: Long,
    fee: Long,
    buyMatcherFee: Long,
    sellMatcherFee: Long,
    timestamp: Long,
    version: Byte,
    proofs: List[String]
) {
  def toTx: Either[ValidationError, ExchangeTransaction] =
    for {
      _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize))
      _proofs     <- Proofs.create(_proofBytes)
      _t          <- ExchangeTransaction.create(2.toByte, order1, order2, amount, price, buyMatcherFee, sellMatcherFee, fee, timestamp, _proofs)
    } yield _t
} 
Example 31
Source File: LeaseCancelV1Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import play.api.libs.json.{Json, Reads, Writes}

case class LeaseCancelV1Request(sender: String, txId: String, fee: Long, timestamp: Option[Long] = None)

object LeaseCancelV1Request {
  implicit val leaseCancelRequestReads: Reads[LeaseCancelV1Request] = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json._

    ((JsPath \ "sender").read[String] ~
      ((JsPath \ "txId").read[String] | (JsPath \ "leaseId").read[String]) ~
      (JsPath \ "fee").read[Long] ~
      (JsPath \ "timestamp").readNullable[Long])(LeaseCancelV1Request.apply _)
  }

  implicit val leaseCancelRequestWrites: Writes[LeaseCancelV1Request] = Json.writes[LeaseCancelV1Request]
} 
Example 32
Source File: SignedReissueV2Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import cats.implicits._
import com.wavesplatform.account.{AddressScheme, PublicKey}
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.assets.ReissueTransaction
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}

case class SignedReissueV2Request(
    senderPublicKey: String,
    assetId: String,
    quantity: Long,
    reissuable: Boolean,
    fee: Long,
    timestamp: Long,
    proofs: List[String]
) {
  def toTx: Either[ValidationError, ReissueTransaction] =
    for {
      _sender <- PublicKey.fromBase58String(senderPublicKey)
      chainId = AddressScheme.current.chainId
      _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize))
      _proofs     <- Proofs.create(_proofBytes)
      _assetId    <- parseBase58ToIssuedAsset(assetId)
      _t          <- ReissueTransaction.create(2.toByte, _sender, _assetId, quantity, reissuable, fee, timestamp, _proofs)
    } yield _t
}

object SignedReissueV2Request {
  implicit val assetReissueRequestReads: Reads[SignedReissueV2Request] = (
    (JsPath \ "senderPublicKey").read[String] and
      (JsPath \ "assetId").read[String] and
      (JsPath \ "quantity").read[Long] and
      (JsPath \ "reissuable").read[Boolean] and
      (JsPath \ "fee").read[Long] and
      (JsPath \ "timestamp").read[Long] and
      (JsPath \ "proofs").read[List[ProofStr]]
  )(SignedReissueV2Request.apply _)
} 
Example 33
Source File: BurnV1Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import play.api.libs.json.{Json, Reads, Writes}

case class BurnV1Request(sender: String, assetId: String, quantity: Long, fee: Long, timestamp: Option[Long] = None)

object BurnV1Request {
  implicit val burnV1Reads: Reads[BurnV1Request] = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json._

    ((JsPath \ "sender").read[String] ~
      (JsPath \ "assetId").read[String] ~
      ((JsPath \ "quantity").read[Long] | (JsPath \ "amount").read[Long]) ~
      (JsPath \ "fee").read[Long] ~
      (JsPath \ "timestamp").readNullable[Long])(BurnV1Request.apply _)
  }

  implicit val burnV1Writes: Writes[BurnV1Request] = Json.writes[BurnV1Request]
} 
Example 34
Source File: JsonFileStorage.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import java.io.{File, PrintWriter}

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import play.api.libs.json.{Json, Reads, Writes}
import java.util.Base64

import scala.io.Source
import scala.util.control.NonFatal

object JsonFileStorage {
  private[this] val KeySalt           = "0495c728-1614-41f6-8ac3-966c22b4a62d"
  private[this] val AES               = "AES"
  private[this] val Algorithm         = AES + "/ECB/PKCS5Padding"
  private[this] val HashingAlgorithm  = "PBKDF2WithHmacSHA512"
  private[this] val HashingIterations = 999999
  private[this] val KeySizeBits       = 128

  def prepareKey(key: String): SecretKeySpec = {
    import java.security.NoSuchAlgorithmException
    import java.security.spec.InvalidKeySpecException

    import javax.crypto.SecretKeyFactory
    import javax.crypto.spec.PBEKeySpec

    def hashPassword(password: Array[Char], salt: Array[Byte], iterations: Int, keyLength: Int): Array[Byte] =
      try {
        val keyFactory = SecretKeyFactory.getInstance(HashingAlgorithm)
        val keySpec    = new PBEKeySpec(password, salt, iterations, keyLength)
        val key        = keyFactory.generateSecret(keySpec)
        key.getEncoded
      } catch {
        case e @ (_: NoSuchAlgorithmException | _: InvalidKeySpecException) =>
          throw new RuntimeException("Password hashing error", e)
      }

    new SecretKeySpec(hashPassword(key.toCharArray, KeySalt.utf8Bytes, HashingIterations, KeySizeBits), AES)
  }

  def save[T](value: T, path: String, key: Option[SecretKeySpec])(implicit w: Writes[T]): Unit = {
    val folder = new File(path).getParentFile
    if (!folder.exists()) folder.mkdirs()

    val file = new PrintWriter(path)
    try {
      val json = Json.toJson(value).toString()
      val data = key.fold(json)(k => encrypt(k, json))
      file.write(data)
    } finally file.close()
  }

  def save[T](value: T, path: String)(implicit w: Writes[T]): Unit =
    save(value, path, None)

  def load[T](path: String, key: Option[SecretKeySpec] = None)(implicit r: Reads[T]): T = {
    val file = Source.fromFile(path)
    try {
      val dataStr = file.mkString
      Json.parse(key.fold(dataStr)(k => decrypt(k, dataStr))).as[T]
    } finally file.close()
  }

  def load[T](path: String)(implicit r: Reads[T]): T =
    load(path, Option.empty[SecretKeySpec])(r)

  private[this] def encrypt(key: SecretKeySpec, value: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.ENCRYPT_MODE, key)
      new String(Base64.getEncoder.encode(cipher.doFinal(value.utf8Bytes)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage encrypt error", e)
    }
  }

  private[this] def decrypt(key: SecretKeySpec, encryptedValue: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.DECRYPT_MODE, key)
      new String(cipher.doFinal(Base64.getDecoder.decode(encryptedValue)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage decrypt error", e)
    }
  }
} 
Example 35
Source File: ReCaptchaService.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package models.services.captcha

import javax.inject.Inject
import play.api.libs.json.{JsPath, Reads}
import play.api.libs.functional.syntax._
import play.api.libs.ws.WSClient

import scala.concurrent.{ExecutionContext, Future}

trait CaptchaService {
  def validate(response: String, remoteIp: String): Future[Boolean]
}

class ReCaptchaService @Inject()(config: ReCaptchaConfig, ws: WSClient)(implicit ec: ExecutionContext) extends CaptchaService {

  def validate(recaptchaResponse: String, remoteIp: String) = {
    ws
      .url("https://www.google.com/recaptcha/api/siteverify")
      .withHttpHeaders("Accept" -> "application/json")
      .withQueryStringParameters(
        "secret" -> config.secretKey,
        "response" -> recaptchaResponse,
        "remoteip" -> remoteIp
      )
      .get()
      .map(r => r.json.as[ReCaptchaValidationResponse])
      .map { r =>
        val e = r.errors.getOrElse(Vector())
        if (e.isEmpty) {
          r.success
        } else {
          throw new Exception("Failed to retrieve reCaptcha confirmed response: " + e.mkString(";"))
        }
      }
  }
}

case class ReCaptchaConfig(secretKey: String)

private[captcha] case class ReCaptchaValidationResponse(success: Boolean, errors: Option[Vector[String]])

private[captcha] object ReCaptchaValidationResponse {
  implicit val reads: Reads[ReCaptchaValidationResponse] = (
    (JsPath \ "success").read[Boolean] and
      (JsPath \ "error-codes").readNullable[Vector[String]]
    ) (ReCaptchaValidationResponse.apply _)
} 
Example 36
Source File: Obligation.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.response.obligations

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, OWrites, Reads}

case class Obligation(periodKey: String,
                      start: String,
                      end: String,
                      due: String,
                      status: String,
                      received: Option[String])

object Obligation {

  implicit val writes: OWrites[Obligation] = Json.writes[Obligation]

  implicit val reads: Reads[Obligation] = (
    (JsPath \ "periodKey").read[String] and
      (JsPath \ "inboundCorrespondenceFromDate").read[String] and
      (JsPath \ "inboundCorrespondenceToDate").read[String] and
      (JsPath \ "inboundCorrespondenceDueDate").read[String] and
      (JsPath \ "status").read[String] and
      (JsPath \ "inboundCorrespondenceDateReceived").readNullable[String]
    )(Obligation.apply _)
} 
Example 37
Source File: NrsSubmissionHttpParser.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.httpparsers

import play.api.Logger
import play.api.http.Status._
import play.api.libs.json.{Json, Reads, Writes, _}
import uk.gov.hmrc.http.{HttpReads, HttpResponse}


object NrsSubmissionHttpParser {

  val logger: Logger = Logger(this.getClass)

  type NrsSubmissionOutcome = Either[NrsSubmissionFailure, NRSData]

  implicit object NrsSubmissionOutcomeReads extends HttpReads[NrsSubmissionOutcome] {
    override def read(method: String, url: String, response: HttpResponse): NrsSubmissionOutcome = {
      logger.debug(s"[NrsSubmissionHttpParser][#reads] - Reading NRS Response")
      response.status match {
        case BAD_REQUEST =>
          logger.warn(s"[NrsSubmissionHttpParser][#reads] - BAD_REQUEST status from NRS Response")
          Left(NrsError)
        case ACCEPTED =>
          response.json.validate[NRSData].fold(
            invalid => {
              logger.warn(s"[NrsSubmissionHttpParser][#reads] - Error reading NRS Response: $invalid")
              Left(NrsError)
            },
            valid => {
              logger.debug(s"[NrsSubmissionHttpParser][#reads] - Retrieved NRS Data: $valid")
              Right(valid)
            }
          )
        case e =>
          logger.debug(s"[NrsSubmissionHttpParser][#reads] - Retrieved NRS status : $e")
          Right(EmptyNrsData)
      }
    }
  }

}

sealed trait NrsSubmissionFailure

case class NRSData(nrSubmissionId: String,
                   cadesTSignature: String,
                   timestamp: String
                  )

object EmptyNrsData extends NRSData("", "This has been deprecated - DO NOT USE", "")

object NRSData {
  implicit val writes: Writes[NRSData] = Json.writes[NRSData]
  implicit val reads: Reads[NRSData] = {
    (__ \ "nrSubmissionId").read[String].map { id =>
      NRSData.apply(id, "This has been deprecated - DO NOT USE", "")
    }
  }
}

case object NrsError extends NrsSubmissionFailure 
Example 38
Source File: Obligations.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import play.api.libs.json.{Json, Reads}

case class Obligations(obligations: Seq[Obligation])

object Obligations {
  implicit val reads: Reads[Obligations] = Json.reads[Obligations]
}

case class Obligation(identification: Option[ObligationIdentification] = None, obligationDetails: Seq[ObligationDetail])

object Obligation {
  implicit val reads: Reads[Obligation] = Json.reads[Obligation]
}

case class ObligationIdentification(incomeSourceType: Option[String] = None, referenceNumber: String, referenceType: String)

object ObligationIdentification {
  implicit val reads: Reads[ObligationIdentification] = Json.reads[ObligationIdentification]
}

case class ObligationDetail(status: String,
                            inboundCorrespondenceFromDate: String,
                            inboundCorrespondenceToDate: String,
                            inboundCorrespondenceDateReceived: Option[String],
                            inboundCorrespondenceDueDate: String,
                            periodKey: String)

object ObligationDetail {
  implicit val reads: Reads[ObligationDetail] = Json.reads[ObligationDetail]
} 
Example 39
Source File: DesError.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import play.api.libs.json.{Format, Json, OFormat, Reads}
import uk.gov.hmrc.vatapi.models.EnumJson
import uk.gov.hmrc.vatapi.models.des.DesErrorCode.DesErrorCode

case class DesError(code: DesErrorCode, reason: String)

object DesError {
  implicit val format: OFormat[DesError] = Json.format[DesError]
  implicit val reads: Reads[DesError] = Json.reads[DesError]
}

object DesErrorCode extends Enumeration {
  type DesErrorCode = Value

  val INVALID_VRN,
  INVALID_ARN,
  INVALID_PAYLOAD,
  INVALID_PERIODKEY,
  DUPLICATE_SUBMISSION,
  DATE_RANGE_TOO_LARGE,
  SERVER_ERROR,
  SERVICE_UNAVAILABLE,
  INVALID_IDNUMBER,
  INVALID_DATETO,
  INVALID_DATEFROM,
  NOT_FOUND,
  VRN_NOT_FOUND,
  NOT_FOUND_VRN,
  INVALID_SUBMISSION,
  INVALID_IDENTIFIER,
  INVALID_IDTYPE,
  INVALID_STATUS,
  INVALID_REGIME,
  INVALID_DATE_TO,
  INVALID_DATE_FROM,
  INVALID_DATE_RANGE,
  NOT_FOUND_BPKEY,
  INVALID_REGIMETYPE,
  INVALID_ONLYOPENITEMS,
  INVALID_INCLUDELOCKS,
  INVALID_CALCULATEACCRUEDINTEREST,
  INVALID_CUSTOMERPAYMENTINFORMATION,
  INVALID_DATA,
  INVALID_INPUTDATA,
  TAX_PERIOD_NOT_ENDED,
  INVALID_ORIGINATOR_ID
  = Value

  implicit val format: Format[DesErrorCode] = EnumJson.enumFormat(DesErrorCode,
    Some(s"Recognized DesErrorCode values: ${DesErrorCode.values.mkString(", ")}"))
} 
Example 40
Source File: FinancialDataReadsUtils.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package utils

import java.time.LocalDate

import play.api.libs.json.{JsValue, Json, Reads}
import v1.models.response.common.TaxPeriod

trait FinancialDataReadsUtils {

  def filterNotArrayReads[T](filterName: String, notMatching: Seq[String])
                            (implicit rds: Reads[Seq[T]]): Reads[Seq[T]] = (json: JsValue) => {
    json
      .validate[Seq[JsValue]]
      .flatMap(
        readJson =>
          Json
            .toJson(readJson.filterNot {
              element =>
                (element \ filterName).asOpt[String].exists(item => notMatching.contains(item.toLowerCase()))
            })
            .validate[Seq[T]])
  }

  def dateCheck(taxPeriod: Option[TaxPeriod], requestToDate: String): Boolean = {
    val toDate = taxPeriod.fold(None: Option[LocalDate]) { l => Some(LocalDate.parse(l.to)) }
    toDate.fold(true) { desTo => desTo.compareTo(LocalDate.parse(requestToDate)) <= 0
    }
  }
} 
Example 41
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 42
Source File: StandardNrsWsParser.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.http.Status._
import play.api.libs.json.Reads
import play.api.libs.ws.WSResponse
import v1.connectors.NrsOutcome
import v1.models.nrs.response.NrsError

trait WsReads[A] {
  def wsRead(response: WSResponse, defaultResult: A): A
}

object StandardNrsWsParser extends WsParser {

  val logger = Logger(getClass)

  case class SuccessCode(status: Int) extends AnyVal

  implicit def nrsReads[A: Reads](implicit successCode: SuccessCode = SuccessCode(ACCEPTED)): WsReads[NrsOutcome[A]] =
    (response: WSResponse, defaultResult: NrsOutcome[A]) => doRead(response, defaultResult) { response =>
      response.validateJson[A] match {
        case Some(ref) => Right(ref)
        case None => Left(NrsError)
      }
    }

  private def doRead[A](response: WSResponse, defaultResult: NrsOutcome[A])(successOutcomeFactory: WSResponse => NrsOutcome[A])(
    implicit successCode: SuccessCode): NrsOutcome[A] = {

    if (response.status!=successCode.status){
      logger.info("[StandardNrsWsParser][read] - Error response received from NRS " +
        s"with status: ${response.status} and body\n ${response.body}")
    }
    response.status match {
      case successCode.status =>
        logger.info("[StandardNrsWsParser][read] - Success response received from NRS")
        successOutcomeFactory(response)
      case BAD_REQUEST => Left(NrsError)
      case _ => defaultResult
    }
  }
} 
Example 43
Source File: StandardDesHttpParser.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.http.Status._
import play.api.libs.json.Reads
import uk.gov.hmrc.http.{HttpReads, HttpResponse}
import v1.connectors.DesOutcome
import v1.models.errors.{ConnectorError, DownstreamError, OutboundError}
import v1.models.outcomes.ResponseWrapper

object StandardDesHttpParser extends HttpParser {

  case class SuccessCode(status: Int) extends AnyVal

  val logger = Logger(getClass)

  // Return Right[DesResponse[Unit]] as success response has no body - no need to assign it a value
  implicit def readsEmpty(implicit successCode: SuccessCode = SuccessCode(NO_CONTENT),
                          connectorError: ConnectorError): HttpReads[DesOutcome[Unit]] =
    (_: String, url: String, response: HttpResponse) => doRead(url, response) { correlationId =>
      Right(ResponseWrapper(correlationId, ()))
    }

  implicit def reads[A: Reads](implicit successCode: SuccessCode = SuccessCode(OK),
                               connectorError: ConnectorError): HttpReads[DesOutcome[A]] =
    (_: String, url: String, response: HttpResponse) => doRead(url, response) { correlationId =>
      response.validateJson[A] match {
        case Some(ref) => Right(ResponseWrapper(correlationId, ref))
        case None => Left(ResponseWrapper(correlationId, OutboundError(DownstreamError)))
      }
    }

  private def doRead[A](url: String, response: HttpResponse,
                       )(successOutcomeFactory: String => DesOutcome[A])(
    implicit successCode: SuccessCode, connectorError: ConnectorError): DesOutcome[A] = {

    val correlationId = retrieveCorrelationId(response)

    if (response.status != successCode.status) {
      logger.info(
        "[StandardDesHttpParser][read] - " +
          s"Error response received from DES with status: ${response.status} and body\n" +
          s"${response.body} and correlationId: $correlationId when calling $url - " +
          s"vrn: ${connectorError.vrn}, requestId: ${connectorError.requestId}")
    }
    response.status match {
      case successCode.status =>
        logger.info(
          "[StandardDesHttpParser][read] - " +
            s"Success response received from DES with correlationId: $correlationId when calling $url")
        successOutcomeFactory(correlationId)
      case BAD_REQUEST | NOT_FOUND | FORBIDDEN | CONFLICT | UNPROCESSABLE_ENTITY => Left(ResponseWrapper(correlationId, parseErrors(response)))
      case _                                                                     => Left(ResponseWrapper(correlationId, OutboundError(DownstreamError)))
    }
  }
} 
Example 44
Source File: ViewReturnResponse.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.response.viewReturn

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, OWrites, Reads}

case class ViewReturnResponse(periodKey: String,
                              vatDueSales: BigDecimal,
                              vatDueAcquisitions: BigDecimal,
                              totalVatDue: BigDecimal,
                              vatReclaimedCurrPeriod: BigDecimal,
                              netVatDue: BigDecimal,
                              totalValueSalesExVAT: BigDecimal,
                              totalValuePurchasesExVAT: BigDecimal,
                              totalValueGoodsSuppliedExVAT: BigDecimal,
                              totalAcquisitionsExVAT: BigDecimal)

object ViewReturnResponse {
  implicit val writes: OWrites[ViewReturnResponse] = Json.writes[ViewReturnResponse]
  implicit val reads: Reads[ViewReturnResponse] = (
    (JsPath \ "periodKey").read[String] and
      (JsPath \ "vatDueSales").read[BigDecimal] and
      (JsPath \ "vatDueAcquisitions").read[BigDecimal] and
      (JsPath \ "vatDueTotal").read[BigDecimal] and
      (JsPath \ "vatReclaimedCurrPeriod"). read[BigDecimal] and
      (JsPath \ "vatDueNet").read[BigDecimal] and
      (JsPath \ "totalValueSalesExVAT").read[BigDecimal] and
      (JsPath \ "totalValuePurchasesExVAT").read[BigDecimal] and
      (JsPath \ "totalValueGoodsSuppliedExVAT").read[BigDecimal] and
      (JsPath \ "totalAllAcquisitionsExVAT").read[BigDecimal]
    )(ViewReturnResponse.apply _)
} 
Example 45
Source File: JsonFormatValidationSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.controllers.requestParsers.validators.validations

import play.api.libs.json.{Json, Reads}
import support.UnitSpec
import v1.models.errors.MtdError
import v1.models.utils.JsonErrorValidators

class JsonFormatValidationSpec extends UnitSpec with JsonErrorValidators {

  case class TestDataObject(fieldOne: String, fieldTwo: String)

  implicit val testDataObjectReads: Reads[TestDataObject] = Json.reads[TestDataObject]

  val someError = MtdError("SOME_CODE", "some message")

  "validate" should {
    "return no errors" when {
      "when a valid JSON object with all the necessary fields is supplied" in {

        val validJson = Json.parse(
          """
            |{
            | "testDataObject" : {
            |     "fieldOne" : "Something",
            |     "fieldTwo" : "SomethingElse"
            | }
            |}
            |""".stripMargin)

        val validationResult = JsonFormatValidation.validate[TestDataObject](validJson \ "testDataObject", someError)
        validationResult shouldBe empty
      }
    }

    "return an error " when {
      "when a required field is missing" in {

        val json = Json.parse(
          """
            |{
            | "testDataObject": {
            |   "fieldOne" : "Something"
            | }
            |}""".stripMargin)

        val validationResult = JsonFormatValidation.validate[TestDataObject](json \ "testDataObject", someError)
        validationResult shouldBe List(someError)
      }

    }

  }
} 
Example 46
Source File: Liability.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.response.liabilities

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, OWrites, Reads}
import utils.NestedJsonReads
import v1.models.response.common.TaxPeriod

case class Liability(taxPeriod: Option[TaxPeriod],
                     `type`: String,
                     originalAmount: BigDecimal,
                     outstandingAmount: Option[BigDecimal],
                     due: Option[String])

object Liability extends NestedJsonReads {

  implicit val writes: OWrites[Liability] = Json.writes[Liability]

  implicit val reads: Reads[Liability] = (
    TaxPeriod.reads and
      (JsPath \ "chargeType").read[String] and
      (JsPath \ "originalAmount").read[BigDecimal] and
      (JsPath \ "outstandingAmount").readNullable[BigDecimal] and
      (JsPath \ "items" \\ "dueDate").readNestedNullable[String]
    )(Liability.apply _)
} 
Example 47
Source File: QueryFormats.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package daf.dataset.query.json

import daf.dataset.query._
import daf.web.json.JsonReadsSyntax
import play.api.data.validation.ValidationError
import play.api.libs.json.Reads

object QueryFormats {

  private val havingWithoutGroupBy = ValidationError { "Query with [having] clause is missing [groupBy]" }

  implicit val reader: Reads[Query] = for {
    select  <- SelectClauseFormats.reader.optional("select")
    where   <- WhereClauseFormats.reader.optional("where")
    groupBy <- GroupByClauseFormats.reader.optional("groupBy")
    having  <- HavingClauseFormats.reader.optional("having").filterNot(havingWithoutGroupBy) { clause => clause.nonEmpty && groupBy.isEmpty }
    limit   <- LimitClauseFormats.reader.optional("limit")
  } yield Query(
    select  = select getOrElse SelectClause.*,
    where   = where,
    groupBy = groupBy,
    having  = having,
    limit   = limit
  )

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

import play.api.libs.json.{Json, Reads, Writes}
import uk.gov.hmrc.http.cache.client.{CacheMap, SessionCache}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}
import scala.io.Source
import uk.gov.hmrc.http.{HeaderCarrier, HttpDelete, HttpGet, HttpPut, UserId}

object MockSessionCache extends SessionCache{
  val cachedNinoAndUsername = TestAccountBuilder.cachedNino
  val cachedUserId = UserId(s"/auth/oid/$cachedNinoAndUsername")

  override def defaultSource: String = ???
  override def baseUri: String = ???
  override def domain: String = ???
  override def http: HttpGet with HttpPut with HttpDelete = ???

  private def loadObjectFromFile[T](filename: String)(implicit rds: Reads[T]): Option[T] = {
    val fileContents = Source.fromFile(filename).mkString
    Json.parse(fileContents).validate[T].fold(invalid => None, valid => Some(valid))
  }

  private def loadObjectBasedOnKey[T](key: String)(implicit rds: Reads[T]): Option[T] =
    key match {
      case _ => None
    }

  override def fetchAndGetEntry[T](key: String)(implicit hc: HeaderCarrier, rds: Reads[T],ec:ExecutionContext): Future[Option[T]] =
    Future.successful(hc.userId.filter(_ == cachedUserId).flatMap(p => loadObjectBasedOnKey(key)))

  override def cache[A](formId: String, body: A)(implicit wts: Writes[A], hc: HeaderCarrier,ec:ExecutionContext): Future[CacheMap] = Future.successful(CacheMap("", Map()))
} 
Example 49
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 50
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 51
Source File: HttpV1OrderBook.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import java.nio.charset.StandardCharsets

import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, Reads}

case class HttpV1OrderBook(@ApiModelProperty(value = "Timestamp of the last Order Book update") timestamp: Long,
                           @ApiModelProperty(
                             value = "List of aggregated denormalized bid levels [price, amount]",
                             dataType = "[[Ljava.lang.String;",
                             example = """[ [ "1.18", "43800.00000000" ], [ "1.17", "52187.00000000" ], [ "1.16", "809.00000000" ] ]"""
                           ) bids: List[HttpV1LevelAgg],
                           @ApiModelProperty(
                             value = "List of aggregated denormalized ask levels [price, amount]",
                             dataType = "[[Ljava.lang.String;",
                             example = """[ [ "1.19", "2134.00000000" ], [ "1.20", "747.00000000" ] ]"""
                           ) asks: List[HttpV1LevelAgg])

object HttpV1OrderBook {

  implicit val httpV1OrderBookReads: Reads[HttpV1OrderBook] = Json.reads

  def fromHttpResponse(response: HttpResponse): HttpV1OrderBook =
    Json.parse(response.entity.asInstanceOf[HttpEntity.Strict].getData().decodeString(StandardCharsets.UTF_8)).as[HttpV1OrderBook]
} 
Example 52
Source File: HttpOrderStatus.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import cats.syntax.option._
import com.wavesplatform.dex.api.http.entities.HttpOrderStatus.Status
import com.wavesplatform.dex.meta.getSimpleName
import com.wavesplatform.dex.model.OrderStatus
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Format, Json, Reads, Writes}

case class HttpOrderStatus(@ApiModelProperty(
                             dataType = "string",
                             allowableValues = "Accepted, NotFound, PartiallyFilled, Filled, Cancelled"
                           ) status: Status,
                           @ApiModelProperty(
                             value = "Filled amount of existed order",
                             dataType = "integer",
                             allowEmptyValue = true
                           ) filledAmount: Option[Long] = None,
                           @ApiModelProperty(
                             value = "Filled fee of existed order",
                             dataType = "integer",
                             allowEmptyValue = true
                           ) filledFee: Option[Long] = None,
                           @ApiModelProperty(
                             value = "Brief message in case of not existed order",
                             allowEmptyValue = true
                           ) message: Option[String] = None)

object HttpOrderStatus {

  implicit val httpOrderStatusFormat: Format[HttpOrderStatus] = Json.format

  def from(x: OrderStatus): HttpOrderStatus = x match {
    case OrderStatus.Accepted                                 => HttpOrderStatus(Status.Accepted)
    case OrderStatus.NotFound                                 => HttpOrderStatus(Status.NotFound, message = Some("The limit order is not found"))
    case OrderStatus.PartiallyFilled(filledAmount, filledFee) => HttpOrderStatus(Status.PartiallyFilled, filledAmount.some, filledFee.some)
    case OrderStatus.Filled(filledAmount, filledFee)          => HttpOrderStatus(Status.Filled, filledAmount.some, filledFee.some)
    case OrderStatus.Cancelled(filledAmount, filledFee)       => HttpOrderStatus(Status.Cancelled, filledAmount.some, filledFee.some)
  }

  sealed abstract class Status extends Product with Serializable {
    val name: String = getSimpleName(this)
  }

  object Status {

    case object Accepted        extends Status
    case object NotFound        extends Status
    case object PartiallyFilled extends Status
    case object Filled          extends Status
    case object Cancelled       extends Status

    val All = List(Accepted, NotFound, PartiallyFilled, Filled, Cancelled)

    implicit val format: Format[Status] = Format(
      Reads.StringReads.map { x =>
        All.find(_.name == x) match {
          case Some(r) => r
          case None    => throw new IllegalArgumentException(s"Can't parse '$x' as ApiOrderStatus.Status")
        }
      },
      Writes.StringWrites.contramap(_.name)
    )
  }
} 
Example 53
Source File: Utilities.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.kernel

import java.nio.charset.Charset

import akka.util.{ByteString, Timeout}
import org.apache.toree.communication.ZMQMessage
import org.apache.toree.kernel.protocol.v5._
import org.apache.toree.utils.LogLike
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsPath, Json, Reads}

import scala.concurrent.duration._

object Utilities extends LogLike {
  //
  // NOTE: This is brought in to remove feature warnings regarding the use of
  //       implicit conversions regarding the following:
  //
  //       1. ByteStringToString
  //       2. ZMQMessageToKernelMessage
  //
  import scala.language.implicitConversions

  
  implicit val timeout = Timeout(21474835.seconds)

  implicit def ByteStringToString(byteString : ByteString) : String = {
    new String(byteString.toArray, Charset.forName("UTF-8"))
  }

  implicit def StringToByteString(string : String) : ByteString = {
    ByteString(string.getBytes)
  }

  implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = {
    val delimiterIndex: Int =
      message.frames.indexOf(ByteString("<IDS|MSG>".getBytes))
    //  TODO Handle the case where there is no delimiter
    val ids: Seq[Array[Byte]] =
      message.frames.take(delimiterIndex).map(
        (byteString : ByteString) =>  { byteString.toArray }
      )
    val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header]
    // TODO: Investigate better solution than setting parentHeader to null for {}
    val parentHeader = parseAndHandle(message.frames(delimiterIndex + 3),
                                  ParentHeader.headerReads,
                                  handler = (valid: ParentHeader) => valid,
                                  errHandler = _ => null
    )
    val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata]

    KMBuilder().withIds(ids.toList)
               .withSignature(message.frame(delimiterIndex + 1))
               .withHeader(header)
               .withParentHeader(parentHeader)
               .withMetadata(metadata)
               .withContentString(message.frame(delimiterIndex + 5)).build(false)
  }

  implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = {
    val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer()
    kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) )
    frames += "<IDS|MSG>"
    frames += kernelMessage.signature
    frames += Json.toJson(kernelMessage.header).toString()
    frames += Json.toJson(kernelMessage.parentHeader).toString()
    frames += Json.toJson(kernelMessage.metadata).toString
    frames += kernelMessage.contentString
    ZMQMessage(frames  : _*)
  }

  def parseAndHandle[T, U](json: String, reads: Reads[T],
                           handler: T => U) : U = {
    parseAndHandle(json, reads, handler,
      (invalid: Seq[(JsPath, Seq[ValidationError])]) => {
        logger.error(s"Could not parse JSON, ${json}")
        throw new Throwable(s"Could not parse JSON, ${json}")
      }
    )
  }

  def parseAndHandle[T, U](json: String, reads: Reads[T],
                           handler: T => U,
                           errHandler: Seq[(JsPath, Seq[ValidationError])] => U) : U = {
    Json.parse(json).validate[T](reads).fold(
      errHandler,
      (content: T) => handler(content)
    )
  }
} 
Example 54
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 55
Source File: KeysFactsImporter.scala    From codepropertygraph   with Apache License 2.0 5 votes vote down vote up
package io.shiftleft.cpgvalidator.facts

import play.api.libs.json.{Json, Reads}

import play.api.libs.json.Reads._

class KeysFactsImporter extends FactsImporter {

  import FactConstructionClasses._

  case class NodeKey(name: String, comment: String, valueType: String, cardinality: String)

  case class OutEdgeEntry(edgeName: String, inNodes: List[InNode])

  case class InNode(name: String, cardinality: Option[String])

  case class ContainedNode(nodeType: String, localName: String, cardinality: String)

  case class NodeType(name: String,
                      keys: List[String],
                      outEdges: List[OutEdgeEntry],
                      is: Option[List[String]],
                      containedNodes: Option[List[ContainedNode]])

  implicit val inNodeRead = Json.reads[InNode]
  implicit val outEdgeEntryRead: Reads[OutEdgeEntry] = Json.reads[OutEdgeEntry]
  implicit val containedNodeRead: Reads[ContainedNode] = Json.reads[ContainedNode]
  implicit val nodeKeysRead: Reads[NodeKey] = Json.reads[NodeKey]
  implicit val nodeTypesRead: Reads[NodeType] = Json.reads[NodeType]

  override def loadFacts: List[KeysFact] = {
    val nodeTypes = allNodeTypesByNodeTypeName
    val nodeKeys = allNodeKeys
    nodeTypes.flatMap {
      case (nodeTypeName, keys) =>
        keys.map(keyName => {
          val key = findKey(nodeKeys, keyName)
          nodeTypeName withKey key.name hasCardinality Cardinality(
            key.cardinality
          )
        })
    }
  }.toList

  private def findKey(keys: List[NodeKey], keyName: String): NodeKey =
    keys
      .find(_.name == keyName)
      .getOrElse(
        throw new AssertionError(
          s"Key '$keyName' is used but this key is not defined in nodeKeys!"
        )
      )

  private def allNodeKeys: List[NodeKey] =
    (cpgJson \ "nodeKeys").as[List[NodeKey]]

  private def allNodeTypesByNodeTypeName: Map[String, List[String]] =
    (cpgJson \ "nodeTypes")
      .as[List[NodeType]]
      .map(nodeType => nodeType.name -> nodeType.keys)
      .toMap
} 
Example 56
Source File: KafkaService.scala    From ws_to_kafka   with MIT License 5 votes vote down vote up
package com.pkinsky


import akka.actor.ActorSystem
import akka.stream.scaladsl.{Source, Flow, Sink}
import com.softwaremill.react.kafka.{ConsumerProperties, ProducerProperties, ProducerMessage, ReactiveKafka}
import org.apache.kafka.common.serialization.{Deserializer, Serializer}
import play.api.libs.json.{Json, Reads, Writes}

case class KafkaServiceConf(bootstrapServers: String)

class KafkaService(kafkaClient: ReactiveKafka, conf: KafkaServiceConf) {
  
  def consume[T](topic: String, groupId: String)(implicit writes: Reads[T], actorSystem: ActorSystem): Source[T, Unit] =
    Source.fromPublisher(kafkaClient.consume(
      ConsumerProperties(
        bootstrapServers = conf.bootstrapServers, // IP and port of local Kafka instance
        topic = topic, // topic to consume messages from
        groupId = groupId, // consumer group
        valueDeserializer = KafkaService.deserializer[T]
      )
    )).map(_.value())
}


object KafkaService {
  def serializer[T: Writes] = new Serializer[T] {
    override def serialize(topic: String, data: T): Array[Byte] = {
      val js = Json.toJson(data)
      js.toString().getBytes("UTF-8")
    }

    override def configure(configs: java.util.Map[String, _], isKey: Boolean): Unit = ()
    override def close(): Unit = ()
  }

  def deserializer[T: Reads] = new Deserializer[T] {
    override def deserialize(topic: String, data: Array[Byte]): T = {
      val s = new String(data, "UTF-8")
      Json.fromJson(Json.parse(s)).get //throw exception on error ¯\_(ツ)_/¯ (consider returning JsResult[T])
    }

    override def configure(configs: java.util.Map[String, _], isKey: Boolean): Unit = ()
    override def close(): Unit = ()
  }
} 
Example 57
Source File: ResponseTransformer.scala    From scala-play-realworld-example-app   with MIT License 5 votes vote down vote up
package commons_test.test_helpers

import play.api.libs.json.Reads
import play.api.libs.ws.WSResponse

trait ResponseTransformer[T] {
  def apply(rawResponse: WSResponse): T
}

object ResponseTransformer {
  implicit val identityResponseTransformer: ResponseTransformer[WSResponse] = IdentityResponseTransformer
}

object FromJsonToModelResponseTransformerFactory {
  def apply[WrapperType : Reads, ResultType](unwrap: WrapperType => ResultType): ResponseTransformer[ResultType] = {
    rawResponse: WSResponse => {
      unwrap(rawResponse.json.as[WrapperType])
    }
  }
}

object IdentityResponseTransformer extends ResponseTransformer[WSResponse] {
  override def apply(rawResponse: WSResponse): WSResponse = {
    rawResponse
  }
} 
Example 58
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 59
Source File: Customer.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.scaladsl.serialization.v2a

import com.lightbend.lagom.scaladsl.playjson.JsonMigration
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import play.api.libs.json.JsObject
import play.api.libs.json.JsPath
import play.api.libs.json.Json
import play.api.libs.json.Reads

import scala.collection.immutable.Seq

//#structural
case class Address(street: String, city: String, zipCode: String, country: String)

case class Customer(name: String, address: Address, shippingAddress: Option[Address])
//#structural

object Customer {
  implicit val addressFormat = Json.format[Address]
  val customerFormat         = Json.format[Customer]
}

class CustomerMigration extends JsonSerializerRegistry {
  override def serializers = Seq.empty

  // format: off
  //#structural-migration
  import play.api.libs.json._
  import play.api.libs.functional.syntax._

  val customerMigration = new JsonMigration(2) {

    // use arbitrary logic to parse an Address
    // out of the old schema
    val readOldAddress: Reads[Address] = {
      (JsPath \ "street")
        .read[String]
        .and(
          (JsPath \ "city").read[String])
        .and(
          (JsPath \ "zipCode").read[String])
        .and(
          (JsPath \ "country").read[String])(Address)
    }

    override def transform(fromVersion: Int, json: JsObject): JsObject = {
      if (fromVersion < 2) {
        val address           = readOldAddress.reads(json).get
        val withoutOldAddress = json - "street" - "city" - "zipCode" - "country"

        // use existing formatter to write the address in the new schema
        withoutOldAddress + ("address" -> Customer.addressFormat.writes(address))
      } else {
        json
      }
    }
  }

  override def migrations: Map[String, JsonMigration] = Map(
    classOf[Customer].getName -> customerMigration
  )
  //#structural-migration
  // format: on
} 
Example 60
Source File: AddOrder.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.scaladsl.serialization

import com.lightbend.lagom.scaladsl.playjson.JsonSerializer
import play.api.libs.json.Format
import play.api.libs.json.JsObject
import play.api.libs.json.Json
import play.api.libs.json.Reads

object AddOrder {
  case class AddOrder(productId: String, quantity: Int)

  import play.api.libs.functional.syntax._
  import play.api.libs.json._

  object AddOrder {
    implicit val format: Format[AddOrder] =
      (JsPath \ "product_id")
        .format[String]
        .and((JsPath \ "quantity").format[Int])
        .apply(AddOrder.apply, unlift(AddOrder.unapply))
  }
}

object OrderCommands {
  //#singleton
  case object GetOrders {
    implicit val format: Format[GetOrders.type] =
      JsonSerializer.emptySingletonFormat(GetOrders)
  }
  //#singleton
}

object Hierarchy {
  //#hierarchy
  import play.api.libs.json._

  sealed trait Fruit
  case object Pear                 extends Fruit
  case object Apple                extends Fruit
  case class Banana(ripe: Boolean) extends Fruit

  object Banana {
    implicit val format: Format[Banana] = Json.format
  }

  object Fruit {
    implicit val format = Format[Fruit](
      Reads { js =>
        // use the fruitType field to determine how to deserialize
        val fruitType = (JsPath \ "fruitType").read[String].reads(js)
        fruitType.fold(
          errors => JsError("fruitType undefined or incorrect"), {
            case "pear"   => JsSuccess(Pear)
            case "apple"  => JsSuccess(Apple)
            case "banana" => (JsPath \ "data").read[Banana].reads(js)
          }
        )
      },
      Writes {
        case Pear  => JsObject(Seq("fruitType" -> JsString("pear")))
        case Apple => JsObject(Seq("fruitType" -> JsString("apple")))
        case b: Banana =>
          JsObject(
            Seq(
              "fruitType" -> JsString("banana"),
              "data"      -> Banana.format.writes(b)
            )
          )
      }
    )
  }
  //#hierarchy
} 
Example 61
Source File: VariantsSpec.scala    From play-json-extra   with Apache License 2.0 5 votes vote down vote up
package play.json.extra

import org.specs2.mutable.Specification
import play.api.libs.json.{Reads, Json, Format, __}

object VariantsSpec extends Specification {

  sealed trait Foo
  final case class Bar(x: Int) extends Foo
  final case class Baz(s: String) extends Foo
  case object Bah extends Foo

  sealed trait Attachment
  final case class PhotoAttachment(photo: String) extends Attachment

  sealed trait Status
  case object ToDo extends Status
  case object Done extends Status

  val bar = Bar(42)
  val baz = Baz("bah")

  implicit val fooFormat: Format[Foo] = Variants.format[Foo]
  implicit val statusFormat: Format[Status] = Variants.format[Status]

  sealed trait A
  final case class B(x: Int) extends A
  final case class C(x: Int) extends A

  "Variants" should {

    "Generate an additional JSON field containing the variant name" in {
      (Json.toJson(bar) \ "$variant").as[String] must equalTo ("Bar")
      (Json.toJson(baz) \ "$variant").as[String] must equalTo ("Baz")
      (Json.toJson(Bah) \ "$variant").as[String] must equalTo ("Bah")
    }

    "Build the right variant from JSON data" in {
      Json.obj("$variant" -> "Bar", "x" -> 0).as[Foo] must equalTo (Bar(0))
      Json.obj("$variant" -> "Baz", "s" -> "hello").as[Foo] must equalTo (Baz("hello"))
      Json.obj("$variant" -> "Bah").as[Foo] must equalTo (Bah)
    }

    "Serialize and deserialize any variant of a sum type" in {
      Json.toJson(bar).as[Foo] must equalTo (bar)
      Json.toJson(baz).as[Foo] must equalTo (baz)
      Json.toJson(Bah).as[Foo] must equalTo (Bah)
    }

    "Support variants with the same types" in {
      implicit val format = Variants.format[A]
      Json.toJson(B(42)).as[A] must equalTo (B(42))
      Json.toJson(C(0)).as[A] must equalTo (C(0))
    }

    "Support case object style enumerations" in {
      Json.toJson(ToDo).as[Status] must equalTo (ToDo)
      Json.toJson(Done).as[Status] must equalTo (Done)
    }

    "Support customization of discriminator field name" in {
      implicit val format = Variants.format[A]((__ \ "type").format[String])
      (Json.toJson(B(42)) \ "type").as[String] must equalTo ("B")
      (Json.toJson(C(0)) \ "type").as[String] must equalTo ("C")
      Json.obj("type" -> "B", "x" -> 0).as[A] must equalTo (B(0))
      Json.obj("type" -> "C", "x" -> 0).as[A] must equalTo (C(0))

    }

    "Generate just a Reads" in {
      implicit val reads = Variants.reads[A]
      Json.obj("x" -> 42, "$variant" -> "B").as[A] must equalTo (B(42))
      Json.obj("x" -> 0, "$variant" -> "C").as[A] must equalTo (C(0))
    }

    "Generate just a Writes" in {
      implicit val writes = Variants.writes[A]
      Json.toJson(B(42)) must equalTo (Json.obj("x" -> 42, "$variant" -> "B"))
      Json.toJson(C(0)) must equalTo (Json.obj("x" -> 0, "$variant" -> "C"))
    }

    "deserialize json with custom discriminator" in {
      implicit val attachmentReads: Reads[Attachment] =
        Variants.reads[Attachment]((__ \ "type").read[String].map(s => s"${s.capitalize}Attachment"))

      val photoJson = Json.obj("type" -> "photo", "photo" -> "bar")
      photoJson.as[Attachment] must beAnInstanceOf[PhotoAttachment]
    }
  }

} 
Example 62
Source File: Payloads.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.examples.utils

import play.api.libs.json.{Json, Reads}
import java.time.LocalDate
import scala.io.Source

object XmlPayloads {
  val bankHolidays: String = Source.fromFile(getClass.getResource("/bankHolidays.xml").toURI, "UTF-8").getLines.mkString
}

object JsonPayloads {
  val bankHolidays: String = Source.fromFile(getClass.getResource("/bankHolidays.json").toURI, "UTF-8").getLines.mkString
  val userId: String = Source.fromFile(getClass.getResource("/userId.json").toURI, "UTF-8").getLines.mkString
}

case class BankHolidays(events: Seq[BankHoliday])
case class BankHoliday(title: String, date: LocalDate)

object BankHolidays {
  implicit val bhr: Reads[BankHoliday] = Json.reads[BankHoliday]
  val reads: Reads[BankHolidays] = Json.reads[BankHolidays]
}

case class User(email: String, fullName: String)

object User {
  val writes = Json.writes[User]
}

case class UserIdentifier(id: String)

object UserIdentifier {
  val reads = Json.reads[UserIdentifier]
} 
Example 63
Source File: Utilities.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.client

import java.nio.charset.Charset

import akka.util.{ByteString, Timeout}
import org.apache.toree.communication.ZMQMessage
import org.apache.toree.kernel.protocol.v5._
import org.apache.toree.kernel.protocol.v5.content.ExecuteRequest
import org.apache.toree.utils.LogLike
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsPath, Json, Reads}

import scala.concurrent.duration._

object Utilities extends LogLike {
  //
  // NOTE: This is brought in to remove feature warnings regarding the use of
  //       implicit conversions regarding the following:
  //
  //       1. ByteStringToString
  //       2. ZMQMessageToKernelMessage
  //
  import scala.language.implicitConversions

  private val sessionId: UUID = java.util.UUID.randomUUID().toString

  
  implicit val timeout = Timeout(21474835.seconds) // Maximum delay

  implicit def ByteStringToString(byteString : ByteString) : String = {
    new String(byteString.toArray, Charset.forName("UTF-8"))
  }

  implicit def StringToByteString(string : String) : ByteString = {
    ByteString(string.getBytes)
  }

  implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = {
    val delimiterIndex: Int =
      message.frames.indexOf(ByteString("<IDS|MSG>".getBytes))
    //  TODO Handle the case where there is no delimiter
    val ids: Seq[Array[Byte]] =
      message.frames.take(delimiterIndex).map(
        (byteString : ByteString) =>  { byteString.toArray }
      )
    val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header]
    val parentHeader = Json.parse(message.frames(delimiterIndex + 3)).validate[ParentHeader].fold[ParentHeader](
      // TODO: Investigate better solution than setting parentHeader to null for {}
      (invalid: Seq[(JsPath, Seq[ValidationError])]) => null, //HeaderBuilder.empty,
      (valid: ParentHeader) => valid
    )
    val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata]

    KMBuilder().withIds(ids.toList)
               .withSignature(message.frame(delimiterIndex + 1))
               .withHeader(header)
               .withParentHeader(parentHeader)
               .withMetadata(metadata)
               .withContentString(message.frame(delimiterIndex + 5)).build(false)
  }

  implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = {
    val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer()
    kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) )
    frames += "<IDS|MSG>"
    frames += kernelMessage.signature
    frames += Json.toJson(kernelMessage.header).toString()
    frames += Json.toJson(kernelMessage.parentHeader).toString()
    frames += Json.toJson(kernelMessage.metadata).toString
    frames += kernelMessage.contentString
    ZMQMessage(frames  : _*)
  }

  def parseAndHandle[T](json: String, reads: Reads[T], handler: T => Unit) : Unit = {
    Json.parse(json).validate[T](reads).fold(
      (invalid: Seq[(JsPath, Seq[ValidationError])]) =>
        logger.error(s"Could not parse JSON, ${json}"),
      (content: T) => handler(content)
    )
  }

  def getSessionId = sessionId

  def toKernelMessage(message: ExecuteRequest): KernelMessage = {
    // construct a kernel message whose content is an ExecuteRequest
    val id = java.util.UUID.randomUUID().toString
    val header = Header(
      id, "spark", sessionId, MessageType.Incoming.ExecuteRequest.toString, "5.0")

    KMBuilder().withIds(Seq[Array[Byte]]()).withSignature("").withHeader(header)
      .withParentHeader(HeaderBuilder.empty).withContentString(message).build
  }

} 
Example 64
Source File: IsCompleteRequest.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.content

import org.apache.toree.kernel.protocol.v5.KernelMessageContent
import play.api.libs.json.{Json, Reads, Writes}

case class IsCompleteRequest(
                            code: String
                          ) extends KernelMessageContent {
  override def content : String =
    Json.toJson(this)(IsCompleteRequest.isCompleteRequestWrites).toString
}

object IsCompleteRequest extends TypeString {
  implicit val isCompleteRequestReads: Reads[IsCompleteRequest] = Json.reads[IsCompleteRequest]
  implicit val isCompleteRequestWrites: Writes[IsCompleteRequest] = Json.writes[IsCompleteRequest]

  
  override def toTypeString: String = "is_complete_request"
} 
Example 65
Source File: IsCompleteReply.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.kernel.protocol.v5.content

import org.apache.toree.kernel.protocol.v5.{KernelMessageContent}
import play.api.libs.json.{Json, Reads, Writes}

case class IsCompleteReply (
                           status: String,
                           indent: String
                         ) extends KernelMessageContent {
  override def content : String =
    Json.toJson(this)(IsCompleteReply.isCompleteReplyWrites).toString
}

object IsCompleteReply extends TypeString {
  implicit val isCompleteReplyReads: Reads[IsCompleteReply] = Json.reads[IsCompleteReply]
  implicit val isCompleteReplyWrites: Writes[IsCompleteReply] = Json.writes[IsCompleteReply]

  
  override def toTypeString: String = "complete_reply"
} 
Example 66
Source File: TokenInfo.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Reads}

case class TokenInfo(
    accessToken: String,
    scope: Scope,
    tokenType: String,
    userUid: String,
    clientId: Option[String] = None,
    realm: String = "unknown")

object TokenInfo {
  implicit val tokenInfoReads: Reads[TokenInfo] = (
    (JsPath \ "access_token").read[String] and
    (JsPath \ "scope").read[Seq[String]].map(names => Scope(Set(names: _*))) and
    (JsPath \ "token_type").read[String] and
    (JsPath \ "uid").read[String] and
    (JsPath \ "client_id").readNullable[String] and
    (JsPath \ "realm").read[String])(TokenInfo.apply _)
} 
Example 67
Source File: HelloWorldController.scala    From playsonify   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.alexitc.example.UserError
import controllers.common.{MyJsonController, MyJsonControllerComponents}
import org.scalactic.{Bad, Every, Good}
import play.api.libs.json.{Json, Reads, Writes}

import scala.concurrent.Future

class HelloWorldController @Inject() (components: MyJsonControllerComponents)
    extends MyJsonController(components) {

  import Context._

  def hello = publicInput { context: HasModel[Person] =>
    val msg = s"Hello ${context.model.name}, you are ${context.model.age} years old"
    val helloMessage = HelloMessage(msg)
    val goodResult = Good(helloMessage)

    Future.successful(goodResult)
  }

  def authenticatedHello = authenticated { context: Authenticated =>
    val msg = s"Hello user with id ${context.auth}"
    val helloMessage = HelloMessage(msg)
    val goodResult = Good(helloMessage)

    Future.successful(goodResult)
  }

  def failedHello = public[HelloMessage] { context: Context =>
    val errors = Every(
      UserError.UserEmailIncorrect,
      UserError.UserAlreadyExist,
      UserError.UserNotFound)

    val badResult = Bad(errors)
    Future.successful(badResult)
  }

  def exceptionHello = public[HelloMessage] { context: Context =>
    Future.failed(new RuntimeException("database unavailable"))
  }
}

case class Person(name: String, age: Int)

object Person {
  implicit val reads: Reads[Person] = Json.reads[Person]
}


case class HelloMessage(message: String)

object HelloMessage {
  implicit val writes: Writes[HelloMessage] = Json.writes[HelloMessage]
} 
Example 68
Source File: KeyFormatTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.model

import org.coursera.common.jsonformat.JsonFormats
import org.coursera.naptime.model.KeyFormatTest.MembershipId
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.JsString
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json
import play.api.libs.json.Reads
import org.coursera.common.jsonformat.OrFormats.OrReads
import org.coursera.common.stringkey.StringKeyFormat

object KeyFormatTest {
  case class MembershipId(userId: Long, courseId: String)
  object MembershipId {

    implicit val stringKeyFormat: StringKeyFormat[MembershipId] = {
      StringKeyFormat.caseClassFormat((apply _).tupled, unapply)
    }

    val reads: Reads[MembershipId] =
      Json.reads[MembershipId].orReads(JsonFormats.stringKeyFormat[MembershipId])

    val keyFormat =
      KeyFormat.withFallbackReads(reads)(KeyFormat.idAsStringWithFields(Json.format[MembershipId]))
  }
}

class KeyFormatTest extends AssertionsForJUnit {

  @Test
  def testWithComplexReads(): Unit = {
    val oldSerialization = Json.obj("userId" -> 12345L, "courseId" -> "machine-learning")

    val newSerialization = JsString("12345~machine-learning")

    val expected = JsSuccess(MembershipId(12345L, "machine-learning"))

    assert(expected === MembershipId.keyFormat.reads(oldSerialization))
    assert(expected === MembershipId.keyFormat.reads(newSerialization))
  }
} 
Example 69
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]
    }
  }
}