play.api.libs.json._ Scala Examples

The following examples show how to use play.api.libs.json._. 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: WsError.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.ws.protocol

import cats.syntax.option._
import com.wavesplatform.dex.error.MatcherError
import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, _}

case class WsError(timestamp: Long, code: Int, message: String) extends WsServerMessage {
  override def tpe: String = WsError.tpe
}

object WsError {
  val tpe = "e"

  def from(error: MatcherError, timestamp: Long): WsError = WsError(
    timestamp = timestamp,
    code = error.code,
    message = error.message.text
  )

  def wsUnapply(arg: WsError): Option[(String, Long, Int, String)] = (arg.tpe, arg.timestamp, arg.code, arg.message).some

  implicit val wsErrorFormat: Format[WsError] = (
    (__ \ "T").format[String] and
      (__ \ "_").format[Long] and
      (__ \ "c").format[Int] and
      (__ \ "m").format[String]
  )(
    (_, timestamp, code, message) => WsError(timestamp, code, message),
    unlift(WsError.wsUnapply)
  )
} 
Example 2
Source File: WsInitial.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.ws.protocol

import cats.syntax.option._
import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, _}

case class WsInitial(connectionId: String, timestamp: Long) extends WsServerMessage {
  override def tpe: String = WsInitial.tpe
}

object WsInitial {

  val tpe = "i"

  def wsUnapply(arg: WsInitial): Option[(String, Long, String)] = (arg.tpe, arg.timestamp, arg.connectionId).some

  implicit val wsInitialFormat: Format[WsInitial] = (
    (__ \ "T").format[String] and
      (__ \ "_").format[Long] and
      (__ \ "i").format[String]
  )(
    (_, timestamp, connectionId) => WsInitial(connectionId, timestamp),
    unlift(WsInitial.wsUnapply)
  )
} 
Example 3
Source File: HttpV1LevelAgg.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.model.Denormalization
import com.wavesplatform.dex.error.ErrorFormatterContext
import com.wavesplatform.dex.json
import com.wavesplatform.dex.model.LevelAgg
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Format, JsArray, _}

case class HttpV1LevelAgg(@ApiModelProperty(
                            dataType = "string",
                            example = "831.87648950"
                          ) amount: Double,
                          @ApiModelProperty(
                            dataType = "string",
                            example = "0.00012079"
                          ) price: Double)

object HttpV1LevelAgg {

  implicit val doubleFormat: Format[Double] = json.stringAsDoubleFormat

  implicit val httpV1LevelAggReads: Reads[HttpV1LevelAgg] = Reads {
    case JsArray(value) if value.lengthCompare(2) == 0 => JsSuccess(HttpV1LevelAgg(value(1).as[Double], value(0).as[Double]))
    case x                                             => JsError(s"Cannot parse $x as ApiV1LevelAgg")
  }

  def fromLevelAgg(la: LevelAgg, assetPair: AssetPair)(implicit efc: ErrorFormatterContext): HttpV1LevelAgg = HttpV1LevelAgg(
    Denormalization.denormalizeAmountAndFee(la.amount, efc.assetDecimals(assetPair.amountAsset)).toDouble,
    Denormalization.denormalizePrice(la.price, efc.assetDecimals(assetPair.amountAsset), efc.assetDecimals(assetPair.priceAsset)).toDouble
  )
} 
Example 4
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 5
Source File: RestFormatsSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http.controllers

import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{JsSuccess, _}

class RestFormatsSpec extends AnyWordSpecLike with Matchers {
  "localDateTimeRead" should {
    "return a LocalDateTime for correctly formatted JsString" in {
      val testDate = new LocalDateTime(0)
      val jsValue  = RestFormats.localDateTimeWrite.writes(testDate)

      val JsSuccess(result, _) = RestFormats.localDateTimeRead.reads(jsValue)
      result shouldBe testDate
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.localDateTimeRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.localDateTimeRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }
  }

  "dateTimeRead" should {
    "return a DateTime in zone UTC for correctly formatted JsString" in {
      val testDate = new DateTime(0)
      val jsValue  = RestFormats.dateTimeWrite.writes(testDate)

      val JsSuccess(result, _) = RestFormats.dateTimeRead.reads(jsValue)
      result shouldBe testDate.withZone(DateTimeZone.UTC)
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.dateTimeRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.dateTimeRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }
  }

  "localDateRead" should {
    "return a LocalDate in zone UTC for correctly formatted JsString" in {
      val json         = JsString("1994-05-01")
      val expectedDate = new LocalDate(1994, 5, 1)

      val JsSuccess(result, _) = RestFormats.localDateRead.reads(json)
      result shouldBe expectedDate
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.localDateRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.localDateRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is well formatted but has bad values" in {
      RestFormats.localDateRead.reads(JsString("1994-13-32")) shouldBe a[JsError]
    }
  }
} 
Example 6
Source File: EndpointSubscriberService.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import org.hatdex.hat.api.models._
import org.hatdex.hat.api.service.richData.JsonDataTransformer
import org.joda.time.DateTime
import play.api.Logger
import play.api.libs.json.Reads._
import play.api.libs.json.{ JsArray, JsValue, Json, _ }

case class EndpointQueryException(message: String = "", cause: Throwable = None.orNull)
  extends Exception(message, cause)

object EndpointSubscriberService {
  private val logger = Logger(this.getClass)

  def matchesBundle(data: EndpointData, bundle: EndpointDataBundle): Boolean = {
    val endpointQueries = bundle.flatEndpointQueries
      .filter(_.endpoint == data.endpoint)

    endpointQueries collectFirst {
      case q if q.filters.isEmpty                             => true
      case q if q.filters.exists(dataMatchesFilters(data, _)) => true
    } getOrElse {
      false
    }
  }

  private implicit val dateReads: Reads[DateTime] = JodaReads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ssZ")

  private def dataMatchesFilters(data: EndpointData, filters: Seq[EndpointQueryFilter]): Boolean = {
    logger.debug("Checking if data matches provided filters")
    filters.exists { f =>
      data.data.transform(JsonDataTransformer.parseJsPath(f.field).json.pick).fold(
        invalid = {
          _ => false
        },
        valid = {
          fieldData =>
            val data = f.transformation map {
              case _: FieldTransformation.Identity =>
                fieldData
              case trans: FieldTransformation.DateTimeExtract =>
                Json.toJson(dateTimeExtractPart(fieldData.as[DateTime](dateReads), trans.part))
              case trans: FieldTransformation.TimestampExtract =>
                Json.toJson(dateTimeExtractPart(new DateTime(fieldData.as[Long] * 1000L), trans.part))
              case trans =>
                throw EndpointQueryException(s"Invalid field transformation `${trans.getClass.getName}` for ongoing tracking")
            } getOrElse {
              fieldData
            }
            f.operator match {
              case op: FilterOperator.In       => jsContains(op.value, data)
              case op: FilterOperator.Contains => jsContains(data, op.value)
              case op: FilterOperator.Between  => jsLessThanOrEqual(op.lower, data) && jsLessThanOrEqual(data, op.upper)
              case op                          => throw EndpointQueryException(s"Invalid match operator `${op.getClass.getName}` for ongoing tracking")
            }

        })
    }
  }

  private def dateTimeExtractPart(d: DateTime, part: String): Int = {
    part match {
      case "milliseconds" => d.getMillisOfSecond
      case "second"       => d.getSecondOfMinute
      case "minute"       => d.getMinuteOfDay
      case "hour"         => d.getHourOfDay
      case "day"          => d.getDayOfMonth
      case "week"         => d.getWeekOfWeekyear
      case "month"        => d.getMonthOfYear
      case "year"         => d.getYear
      case "decade"       => d.getYear / 10
      case "century"      => d.getCenturyOfEra
      case "dow"          => d.getDayOfWeek
      case "doy"          => d.getDayOfYear
      case "epoch"        => (d.getMillis / 1000).toInt
    }
  }

  private def jsContains(contains: JsValue, contained: JsValue): Boolean = {
    (contains, contained) match {
      case (a: JsObject, b: JsObject) => b.fieldSet.subsetOf(a.fieldSet)
      case (a: JsArray, b: JsArray)   => a.value.containsSlice(b.value)
      case (a: JsArray, b: JsValue)   => a.value.contains(b)
      case (a: JsValue, b: JsValue)   => a == b
      case _                          => false
    }
  }

  private def jsLessThanOrEqual(a: JsValue, b: JsValue): Boolean = {
    (a, b) match {
      case (aa: JsNumber, bb: JsNumber) => aa.value <= bb.value
      case (aa: JsString, bb: JsString) => aa.value <= bb.value
      case _                            => false
    }
  }
} 
Example 7
Source File: LoginDetails.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.phata.models

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

import scala.collection.JavaConverters._

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

object ApiPasswordChange {

  private val nbvcxzDictionaryList = resources.ConfigurationBuilder.getDefaultDictionaries

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

  private val nbvcxz = new Nbvcxz(nbvcxzConfiguration)

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

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

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

case class ApiPasswordResetRequest(
    email: String)

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

import com.typesafe.scalalogging.LazyLogging
import org.scalatest.{AsyncFunSpec, Inspectors, Matchers}
import play.api.libs.json.{JsValue, _}

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._

class AggregationTests extends AsyncFunSpec with Matchers with Inspectors with Helpers with LazyLogging {

  describe("Agg API should") {
    val agg = scala.io.Source.fromURL(this.getClass.getResource("/agg/aggnames_293846.nq"))
    val ingestAgg = {
      Http.post(_in, agg.mkString, Some("text/nquads;charset=UTF-8"), List("format" -> "nquads"), tokenHeader)
    }.map { res =>
        withClue(res) {
          res.status should be(200)
          jsonSuccessPruner(Json.parse(res.payload)) shouldEqual jsonSuccess
        }
    }

    agg.close()


    val path = cmw / "test.agg.org" / "Test201903_05_1501_11" / "testStatsApiTerms"

    val aggForIntField = executeAfterCompletion(ingestAgg) {
      spinCheck(100.millis, true)(Http.get(
        uri = path,
        queryParams = List("op" -> "stats", "format" -> "json", "ap" -> "type:term,field::$http://qa.test.rfnt.com/v1.1/testns/num$,size:3")))
      { r =>
        (Json.parse(r.payload) \ "AggregationResponse" \\ "buckets": @unchecked) match {
          case n: collection.IndexedSeq[JsValue] => (r.status == 200) && n.forall(jsonval=> jsonval.as[JsArray].value.size == 3)
        }
      }.map { res =>
        withClue(res) {
          res.status should be(200)
          val total = (Json.parse(res.payload) \ "AggregationResponse" \\ "buckets").map(jsonval=> jsonval.as[JsArray].value.size)
          total should equal (ArrayBuffer(3))
        }
      }
    }


    val aggForExactTextField = executeAfterCompletion(ingestAgg) {
      spinCheck(100.millis, true)(Http.get(
        uri = path,
        queryParams = List("op" -> "stats", "format" -> "json", "ap" -> "type:term,field::$http://qa.test.rfnt.com/v1.1/testns/Test_Data$,size:2")))
      { r =>
        (Json.parse(r.payload) \ "AggregationResponse" \\ "buckets": @unchecked) match {
          case n: collection.IndexedSeq[JsValue] => (r.status == 200) && n.forall(jsonval=> jsonval.as[JsArray].value.size == 2)
        }
      }.map { res =>
        withClue(res) {
          res.status should be(200)
          val total = (Json.parse(res.payload) \ "AggregationResponse" \\ "buckets").map(jsonval=> jsonval.as[JsArray].value.size)
          total should equal (ArrayBuffer(2))
        }
      }
    }


    val badQueryNonExactTextMatch = executeAfterCompletion(ingestAgg) {
      spinCheck(100.millis, true)(Http.get(
        uri = path,
        queryParams = List("op" -> "stats", "format" -> "json", "ap" -> "type:term,field:$http://qa.test.rfnt.com/v1.1/testns/Test_Data$,size:2")))
      { r =>
        Json.parse(r.payload).toString()
          .contains("Stats API does not support non-exact value operator for text fields. Please use :: instead of :") && r.status == 400
      }.map { res =>
        withClue(res) {
          res.status should be(400)
          val result = (Json.parse(res.payload) \ "error").as[String]
          result should include ("Stats API does not support non-exact value operator for text fields. Please use :: instead of :")
        }
      }
    }



    it("ingest aggnames data successfully")(ingestAgg)
    it("get stats for int field")(aggForIntField)
    it("get exact stats for string field")(aggForExactTextField)
    it("get stats for non exact string field should be bad response")(badQueryNonExactTextMatch)

  }

}