play.api.libs.json.Format Scala Examples

The following examples show how to use play.api.libs.json.Format. 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: SessionAuditor.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package controllers.auth

import com.google.inject.Inject
import controllers.auth.SessionAuditor._
import controllers.auth.requests.AuthenticatedRequest
import play.api.Logger
import play.api.libs.json.{Format, Json}
import play.api.mvc.Result
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.auth.core.{ConfidenceLevel, Enrolment}
import uk.gov.hmrc.domain.{Nino, SaUtr}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.play.audit.http.connector.AuditResult.{Failure, Success}
import uk.gov.hmrc.play.audit.model.ExtendedDataEvent
import util.AuditServiceTools

import scala.concurrent.{ExecutionContext, Future}

private[auth] class SessionAuditor @Inject()(auditConnector: AuditConnector)(implicit ec: ExecutionContext)
    extends AuditTags {

  val logger = Logger(this.getClass)

  def auditOnce[A](request: AuthenticatedRequest[A], result: Result)(implicit hc: HeaderCarrier): Future[Result] =
    request.session.get(sessionKey) match {
      case None =>
        logger.info(request.profile.toString)

        val eventDetail = UserSessionAuditEvent(request)

        val sendAuditEvent = auditConnector
          .sendExtendedEvent(
            ExtendedDataEvent(
              auditSource = AuditServiceTools.auditSource,
              auditType = auditType,
              detail = Json.toJson(eventDetail),
              tags = buildTags(request))
          )
          .recover {
            case e: Exception =>
              Logger.warn(s"Unable to audit: ${e.getMessage}")
              Failure("UserSessionAuditor.auditOncePerSession exception occurred whilst auditing", Some(e))
          }

        sendAuditEvent.map {
          case Success => result.addingToSession(sessionKey -> "true")(request)
          case _       => result
        }

      case _ => Future.successful(result)
    }
}

object SessionAuditor {

  val sessionKey = "sessionAudited"
  val auditType = "user-session-visit"

  case class UserSessionAuditEvent(
    nino: Option[Nino],
    credentials: Credentials,
    confidenceLevel: ConfidenceLevel,
    name: Option[String],
    saUtr: Option[SaUtr],
    allEnrolments: Set[Enrolment])

  object UserSessionAuditEvent {

    def apply[A](request: AuthenticatedRequest[A]): UserSessionAuditEvent = {
      val nino = request.nino
      val credentials = request.credentials
      val confidenceLevel = request.confidenceLevel
      val name = request.name map (_.toString)
      val saUtr = request.saEnrolment map (_.saUtr)
      val enrolments = request.enrolments

      UserSessionAuditEvent(nino, credentials, confidenceLevel, name, saUtr, enrolments)
    }

    implicit val credentialsFormats = Json.format[Credentials]
    implicit val formats: Format[UserSessionAuditEvent] = Json.format[UserSessionAuditEvent]
  }

} 
Example 2
Source File: Element.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime
import play.api.libs.json.{Format, Json}



case class Element(elementId: Int,
                   tenantId: Int,
                   organizationId: Int,
                   isActive: Boolean = true,
                   created: DateTime =  DateTime.now,
                   createdBy: Int,
                   updated: DateTime =  DateTime.now,
                   updatedBy: Int,
                   columnName: String,
                   entityType: String,
                   name: String,
                   printName: Option[String],
                   description: Option[String],
                   help: Option[String],
                   namePO: Option[String],
                   printNamePO: Option[String],
                   descriptionPO : Option[String],
                   helpPO: Option[String],
                   referenceId: Option[Int],
                   fieldLength: Option[Int],
                   referenceValueId: Option[Int],
                   uuid: String
                   ) extends DomainModel
with ActiveEnabled
with Identifiable
with Traceable{
  override type DomainModel = this.type
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = elementId

  override val entityName: String = "AD_Element"
  override val identifier: String = "AD_Element_ID"
}

object Element {
  implicit val format: Format[Element] = Json.format
  def create(elementId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean ,
             created: DateTime ,
             createdBy: Int,
             updated: DateTime ,
             updatedBy: Int,
             columnName: String,
             entityType: String,
             name: String,
             printName: String,
             description: String,
             help: String,
             namePO: String,
             printNamePO: String,
             descriptionPO : String,
             helpPO: String,
             referenceId: Int,
             fieldLength: Int,
             referenceValueId: Int,
             uuid: String) = Element(elementId, tenantId, organizationId, isActive , created , createdBy ,
    updated , updatedBy , columnName, entityType, name, None, None, None, None, None, None, None, None, None, None,
    uuid)
} 
Example 3
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 4
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 5
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 6
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 7
Source File: HttpSuccessfulBatchCancel.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import io.swagger.annotations.{ApiModel, ApiModelProperty}
import play.api.libs.json.{Format, Json}

@ApiModel(description = "Cancel of multiple orders", parent = classOf[HttpSuccessfulCancel])
case class HttpSuccessfulBatchCancel(
                                      @ApiModelProperty(
      value = "List of successful cancellation messages or errors",
      dataType = "[[Lcom.wavesplatform.dex.api.http.entities.HttpSuccessfulSingleCancel;",
    )
    message: List[List[Either[HttpError, HttpSuccessfulSingleCancel]]], // TODO: In new API: should be a map id -> cancel result
                                      @ApiModelProperty(value = "Success flag")
    override val success: Boolean = HttpSuccessfulCancel.success,
                                      @ApiModelProperty(
      value = "Status",
      example = "BatchCancelCompleted",
      required = false
    ) override val status: String = "BatchCancelCompleted")
    extends HttpSuccessfulCancel

object HttpSuccessfulBatchCancel {

  implicit val httpSuccessfulBatchCancelFormat: Format[HttpSuccessfulBatchCancel] = {

    implicit val ef: Format[Either[HttpError, HttpSuccessfulSingleCancel]] =
      com.wavesplatform.dex.json.eitherFormat[HttpError, HttpSuccessfulSingleCancel]

    Json.format
  }

  def apply(message: List[Either[HttpError, HttpSuccessfulSingleCancel]]): HttpSuccessfulBatchCancel =
    HttpSuccessfulBatchCancel(message = List(message))
} 
Example 8
Source File: HttpError.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.error.MatcherError
import play.api.libs.json.{Format, JsObject, Json}

case class HttpError(error: Int,
                     message: String,
                     template: String,
                     params: Option[JsObject] = None,
                     status: String, // @deprecated(message = "This field is unnecessary", since = "1.2.0")
                     success: Boolean = false,
)
object HttpError {

  implicit val httpErrorFormat: Format[HttpError] = Json.format

  def apply(error: Int, message: String, template: String, params: JsObject, status: String): HttpError = new HttpError(
    error = error,
    message = message,
    template = template,
    params = Some(params),
    status = status
  )

  def from(x: MatcherError, status: String): HttpError = HttpError(
    error = x.code,
    message = x.message.text,
    template = x.message.template,
    params = if (x.message.params == JsObject.empty) None else Some(x.message.params),
    status = status
  )
} 
Example 9
Source File: HttpOrderRestrictions.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.json
import com.wavesplatform.dex.settings.OrderRestrictionsSettings
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Format, Json, OFormat}

case class HttpOrderRestrictions(@ApiModelProperty(dataType = "string", example = "0.001") stepAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "1000000") minAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.00000001") maxAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.001") stepPrice: Double,
                                 @ApiModelProperty(dataType = "string", example = "100000") minPrice: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.00000001") maxPrice: Double)

object HttpOrderRestrictions {

  implicit val doubleFormat: Format[Double]                                = json.stringAsDoubleFormat
  implicit val httpOrderRestrictionsFormat: OFormat[HttpOrderRestrictions] = Json.format[HttpOrderRestrictions]

  def fromSettings(settings: OrderRestrictionsSettings): HttpOrderRestrictions =
    HttpOrderRestrictions(
      stepAmount = settings.stepAmount,
      minAmount = settings.minAmount,
      maxAmount = settings.maxAmount,
      stepPrice = settings.stepPrice,
      minPrice = settings.minPrice,
      maxPrice = settings.maxPrice
    )
} 
Example 10
Source File: package.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http

import com.wavesplatform.dex.domain.account.PublicKey
import com.wavesplatform.dex.domain.asset.{Asset, AssetPair}
import com.wavesplatform.dex.json.{assetDoubleMapFormat, assetMapFormat, assetPairMapFormat}
import com.wavesplatform.dex.queue.QueueEventWithMeta
import play.api.libs.json.{Format, JsValue, Writes}

package object entities {

  type HttpMatcherPublicKey = PublicKey
  type HttpRates            = Map[Asset, Double]
  type HttpOffset           = QueueEventWithMeta.Offset
  type HttpSnapshotOffsets  = Map[AssetPair, HttpOffset]
  type HttpBalance          = Map[Asset, Long]

  implicit val httpMatcherPublicKeyFormat: Format[PublicKey]          = PublicKey.publicKeyJsonFormat
  implicit val httpRatesFormat: Format[HttpRates]                     = assetDoubleMapFormat
  implicit val httpSnapshotOffsetsFormat: Format[HttpSnapshotOffsets] = assetPairMapFormat[Long]
  implicit val httpBalanceFormat: Format[HttpBalance]                 = assetMapFormat[Long]

  implicit class HttpOps[A](private val self: A)(implicit writes: Writes[A]) {
    def toJson: JsValue = writes.writes(self)
  }
} 
Example 11
Source File: KeyPair.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.domain.account

import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.bytes.ByteStr._
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.domain.crypto
import com.wavesplatform.dex.domain.error.ValidationError.GenericError
import play.api.libs.json.{Format, Json, Writes}

import scala.util.{Failure, Success}

final case class KeyPair(seed: ByteStr) {
  lazy val (PrivateKey(privateKey), PublicKey(publicKey)) = crypto.createKeyPair(seed)
}

object KeyPair {

  def fromSeed(base58: String): Either[GenericError, KeyPair] = Base58.tryDecodeWithLimit(base58) match {
    case Success(x) => Right(KeyPair(x))
    case Failure(e) => Left(GenericError(s"Unable to get a private key from the seed '$base58': ${e.getMessage}"))
  }

  implicit class KeyPairImplicitOps(private val kp: KeyPair) extends AnyVal {
    def toAddress: Address = PublicKey.toAddress(kp)
  }

  implicit def toPublicKey(kp: KeyPair): PublicKey   = kp.publicKey
  implicit def toPrivateKey(kp: KeyPair): PrivateKey = kp.privateKey
  implicit def toAddress(keyPair: KeyPair): Address  = keyPair.toAddress

  implicit val jsonFormat: Format[KeyPair] = Format(
    byteStrFormat.map(KeyPair(_)),
    Writes(v => Json.obj("seed" -> Base58.encode(v.seed), "publicKey" -> v.publicKey, "privateKey" -> v.privateKey))
  )
} 
Example 12
Source File: PublicKey.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.domain.account

import com.google.common.collect.Interners
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.bytes.ByteStr._
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.domain.crypto._
import com.wavesplatform.dex.domain.error.ValidationError.InvalidAddress
import com.wavesplatform.dex.domain.utils.base58Length
import play.api.libs.json.{Format, Writes}
import supertagged._

object PublicKey extends TaggedType[ByteStr] {

  private[this] val interner = Interners.newWeakInterner[PublicKey]()

  val KeyStringLength: Int = base58Length(KeyLength)

  val empty: PublicKey = apply(ByteStr.empty)

  def apply(publicKey: ByteStr): PublicKey     = interner.intern(publicKey @@ this)
  def apply(publicKey: Array[Byte]): PublicKey = apply(ByteStr(publicKey))

  def fromBase58String(base58: String): Either[InvalidAddress, PublicKey] =
    (for {
      _     <- Either.cond(base58.length <= KeyStringLength, (), "Bad public key string length")
      bytes <- Base58.tryDecodeWithLimit(base58).toEither.left.map(ex => s"Unable to decode base58: ${ex.getMessage}")
    } yield PublicKey(bytes)).left.map(err => InvalidAddress(s"Invalid sender: $err"))

  def unapply(arg: Array[Byte]): Option[PublicKey] = Some(apply(arg))

  implicit def toAddress(pk: PublicKey): Address = pk.toAddress

  implicit class PublicKeyImplicitOps(private val pk: PublicKey) extends AnyVal {
    def toAddress: Address = Address.fromPublicKey(pk)
  }

  implicit val publicKeyJsonFormat: Format[PublicKey] = Format[PublicKey](
    byteStrFormat.map(this.apply),
    Writes(pk => byteStrFormat.writes(pk))
  )
} 
Example 13
Source File: MatcherError.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.api.responses.dex

import play.api.libs.json.{Format, Json}
import shapeless.ops.hlist.{Mapper, ToTraversable, Zip}
import shapeless.{::, Generic, HList, HNil, Poly1}

// TODO use ApiError instead
case class MatcherError(error: Int, message: String, status: String, params: Option[MatcherError.Params])
object MatcherError {
  implicit val format: Format[MatcherError] = Json.format[MatcherError]

  case class Params(assetId: Option[String] = None, address: Option[String] = None, insignificantDecimals: Option[Int] = None) {
    def isEmpty: Boolean = assetId.isEmpty && address.isEmpty
  }

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

    private object containsPoly extends Poly1 {
      implicit def contains[T: Ordering] = at[(Option[T], Option[T])] {
        case (Some(l), Some(r)) => l == r
        case (None, None)       => true
        case _                  => false
      }
    }

    private def internalContains[HParams <: HList, ZHParams <: HList, Booleans <: HList](obj: Params, part: Params)(
        implicit gen: Generic.Aux[Params, HParams],
        zip: Zip.Aux[HParams :: HParams :: HNil, ZHParams],
        mapper: Mapper.Aux[containsPoly.type, ZHParams, Booleans],
        toList: ToTraversable.Aux[Booleans, List, Boolean]): Boolean =
      gen.to(obj).zip(gen.to(part))(zip).map(containsPoly).toList[Boolean](toList).forall(identity)

    def contains(obj: Params, part: Params): Boolean = internalContains(obj, part)
  }
} 
Example 14
Source File: TestSpec.scala    From intro-to-akka-streams   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.streams

import akka.NotUsed
import akka.actor.{ ActorRef, ActorSystem, PoisonPill }
import akka.event.{ Logging, LoggingAdapter }
import akka.stream.Materializer
import akka.stream.scaladsl.Source
import akka.stream.testkit.TestSubscriber
import akka.stream.testkit.scaladsl.TestSink
import akka.testkit.TestProbe
import akka.util.Timeout
import com.github.dnvriend.streams.util.ClasspathResources
import org.scalatest._
import org.scalatest.concurrent.{ Eventually, ScalaFutures }
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.inject.BindingKey
import play.api.libs.json.{ Format, Json }
import play.api.test.WsTestClient

import scala.collection.immutable._
import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future }
import scala.reflect.ClassTag
import scala.util.Try

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

final case class Person(firstName: String, age: Int)

class TestSpec extends FlatSpec
    with Matchers
    with GivenWhenThen
    with OptionValues
    with TryValues
    with ScalaFutures
    with WsTestClient
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with Eventually
    with ClasspathResources
    with GuiceOneServerPerSuite {

  def getComponent[A: ClassTag] = app.injector.instanceOf[A]
  def getNamedComponent[A](name: String)(implicit ct: ClassTag[A]): A =
    app.injector.instanceOf[A](BindingKey(ct.runtimeClass.asInstanceOf[Class[A]]).qualifiedWith(name))

  // set the port number of the HTTP server
  override lazy val port: Int = 8081
  implicit val timeout: Timeout = 1.second
  implicit val pc: PatienceConfig = PatienceConfig(timeout = 30.seconds, interval = 300.millis)
  implicit val system: ActorSystem = getComponent[ActorSystem]
  implicit val ec: ExecutionContext = getComponent[ExecutionContext]
  implicit val mat: Materializer = getComponent[Materializer]
  val log: LoggingAdapter = Logging(system, this.getClass)

  // ================================== Supporting Operations ====================================
  def id: String = java.util.UUID.randomUUID().toString

  implicit class FutureToTry[T](f: Future[T]) {
    def toTry: Try[T] = Try(f.futureValue)
  }

  implicit class SourceOps[A](src: Source[A, NotUsed]) {
    def testProbe(f: TestSubscriber.Probe[A] ⇒ Unit): Unit =
      f(src.runWith(TestSink.probe(system)))
  }

  def withIterator[T](start: Int = 0)(f: Source[Int, NotUsed] ⇒ T): T =
    f(Source.fromIterator(() ⇒ Iterator from start))

  def fromCollection[A](xs: Iterable[A])(f: TestSubscriber.Probe[A] ⇒ Unit): Unit =
    f(Source(xs).runWith(TestSink.probe(system)))

  def killActors(refs: ActorRef*): Unit = {
    val tp = TestProbe()
    refs.foreach { ref ⇒
      tp watch ref
      tp.send(ref, PoisonPill)
      tp.expectTerminated(ref)
    }
  }
} 
Example 15
Source File: NationalInsuranceTaxYear.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import play.api.libs.json.{Format, Json}

case class NationalInsuranceTaxYear(
                                     taxYear: String,
                                     qualifying: Boolean,
                                     classOneContributions: BigDecimal,
                                     classTwoCredits: Int,
                                     classThreeCredits: Int,
                                     otherCredits: Int,
                                     classThreePayable: BigDecimal,
                                     classThreePayableBy: Option[LocalDate],
                                     classThreePayableByPenalty: Option[LocalDate],
                                     payable: Boolean,
                                     underInvestigation: Boolean
                                   ) {

  def currentDateAfterCutOff(currentDate: LocalDate): Boolean = {
    classThreePayableBy match {
      case Some(classThreeDate) => currentDate.isAfter(classThreeDate)
      case None => payable
    }
  }

}



object NationalInsuranceTaxYear {
  implicit val formats: Format[NationalInsuranceTaxYear] = Json.format[NationalInsuranceTaxYear]
} 
Example 16
Source File: BackendConnector.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.connectors

import play.api.data.validation.ValidationError
import play.api.libs.json.{Format, JsObject, JsPath}
import uk.gov.hmrc.http.cache.client.SessionCache
import uk.gov.hmrc.nisp.models.enums.APIType._
import uk.gov.hmrc.nisp.services.MetricsService
import uk.gov.hmrc.nisp.utils.JsonDepersonaliser
import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Future
import scala.util.{Failure, Success}
import uk.gov.hmrc.http.{ HeaderCarrier, HttpGet, HttpResponse }

trait BackendConnector {

  def http: HttpGet
  def serviceUrl: String
  def sessionCache: SessionCache
  val metricsService: MetricsService

  protected def retrieveFromCache[A](api: APIType, url: String)(implicit hc: HeaderCarrier, formats: Format[A]): Future[A] = {
    val keystoreTimerContext = metricsService.keystoreReadTimer.time()

    val sessionCacheF = sessionCache.fetchAndGetEntry[A](api.toString)
    sessionCacheF.onFailure {
      case _ => metricsService.keystoreReadFailed.inc()
    }
    sessionCacheF.flatMap { keystoreResult =>
      keystoreTimerContext.stop()
      keystoreResult match {
        case Some(data) =>
          metricsService.keystoreHitCounter.inc()
          Future.successful(data)
        case None =>
          metricsService.keystoreMissCounter.inc()
          connectToMicroservice[A](url, api) map {
            data: A => cacheResult(data, api.toString)
          }
      }
    }
  }

  private def connectToMicroservice[A](urlToRead: String, apiType: APIType)(implicit hc: HeaderCarrier, formats: Format[A]): Future[A] = {
    val timerContext = metricsService.startTimer(apiType)

    val httpResponseF = http.GET[HttpResponse](urlToRead)
    httpResponseF onSuccess {
      case _ => timerContext.stop()
    }
    httpResponseF onFailure {
      case _ => metricsService.incrementFailedCounter(apiType)
    }
    httpResponseF.map {
      httpResponse => httpResponse.json.validate[A].fold(
        errs => {
          val json = JsonDepersonaliser.depersonalise(httpResponse.json) match {
            case Success(s) => s"Depersonalised JSON\n$s"
            case Failure(e) => s"JSON could not be depersonalised\n${e.toString()}"
          }
          throw new JsonValidationException(s"Unable to deserialise $apiType: ${formatJsonErrors(errs)}\n$json")
        },
        valid => valid
      )
    }
  }

  private def cacheResult[A](a:A,name: String)(implicit hc: HeaderCarrier, formats: Format[A]): A = {
    val timerContext = metricsService.keystoreWriteTimer.time()
    val cacheF = sessionCache.cache[A](name, a)
    cacheF.onSuccess {
      case _ => timerContext.stop()
    }
    cacheF.onFailure {
      case _ => metricsService.keystoreWriteFailed.inc()
    }
    a
  }

  private def formatJsonErrors(errors: Seq[(JsPath, Seq[ValidationError])]): String = {
    errors.map(p => p._1 + " - " + p._2.map(e => removeJson(e.message)).mkString(",")).mkString(" | ")
  }

  private def removeJson(message: String): String = {
    message.indexOf("{") match {
      case i if i != -1  => message.substring(0, i - 1) + " [JSON removed]"
      case _ => message
    }
  }

  private[connectors] class JsonValidationException(message: String) extends Exception(message)
} 
Example 17
Source File: StatePensionConnector.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.connectors

import play.api.libs.json.{Format, Json, Writes}
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.nisp.models.enums.APIType
import uk.gov.hmrc.nisp.models.{StatePension, StatePensionExclusion}
import uk.gov.hmrc.nisp.utils.EitherReads.eitherReads

import scala.concurrent.Future

trait StatePensionConnector extends BackendConnector {
  implicit val reads = eitherReads[StatePensionExclusion, StatePension]

  implicit val writes = Writes[Either[StatePensionExclusion, StatePension]] {
    case Left(exclusion) => Json.toJson(exclusion)
    case Right(statePension) => Json.toJson(statePension)
  }

  implicit val formats = Format[Either[StatePensionExclusion, StatePension]](reads, writes)

  val apiHeader = "Accept" -> "application/vnd.hmrc.1.0+json"

  def getStatePension(nino: Nino)(implicit hc: HeaderCarrier): Future[Either[StatePensionExclusion, StatePension]] = {
    val urlToRead = s"$serviceUrl/ni/$nino"
    val headerCarrier = hc.copy(extraHeaders = hc.extraHeaders :+ apiHeader)
    retrieveFromCache[Either[StatePensionExclusion, StatePension]](APIType.StatePension, urlToRead)(headerCarrier, formats)
  }
} 
Example 18
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 19
Source File: UTCFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.joda.time.{DateTime, DateTimeZone}
import org.scalatest.WordSpec
import play.api.libs.json.{Format, Json}

case class NotUTC(when: DateTime)
object NotUTC {
  implicit val format: Format[NotUTC] = Json.format[NotUTC]
}

case class UseUTC(when: DateTime)
object UseUTC extends UTCFormats {
  implicit val format: Format[UseUTC] = Json.format[UseUTC]
}

class UTCFormatSpec extends WordSpec {

  private[this] val pacificTimeZone = DateTimeZone.forID("US/Pacific")

  "Json.format by default" should {
    "deserialize with the current time zone" in {
      val dt = new DateTime(pacificTimeZone)
      assertResult(DateTimeZone.getDefault) {
        val notUTC = Json.toJson(NotUTC(dt)).as[NotUTC]
        notUTC.when.getZone
      }
    }
  }

  "UTCFormats" should {

    "override the standard Format[DateTime]" in {
      val dt = new DateTime(pacificTimeZone)
      assertResult(DateTimeZone.UTC) {
        val useUTC = Json.toJson(UseUTC(dt)).as[UseUTC]
        useUTC.when.getZone
      }
    }
  }
} 
Example 20
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.FlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with FlatSpecLike
  with ScalaTestBridge {

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 21
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.FreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatest.prop.GeneratorDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends FreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 22
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.flatspec.AnyFlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with AnyFlatSpecLike
  with ScalaTestBridge {

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 23
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 24
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.Tag
import org.scalatest.flatspec.AnyFlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with AnyFlatSpecLike
  with ScalaTestBridge {

  override def registerTest(testText: String, testTags: Tag*)(testFun: => Unit): Unit = {
    super[AnyFlatSpecLike].registerTest(testText, testTags: _*)(testFun)
  }

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 25
Source File: Metadata.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.nrs.request

import org.joda.time.DateTime
import play.api.libs.json.{Format, JsValue, Json, OFormat}
import utils.DateUtils

case class Metadata(businessId: String,
                    notableEvent: String,
                    payloadContentType: String,
                    payloadSha256Checksum: Option[String],
                    userSubmissionTimestamp: DateTime,
                    identityData: Option[IdentityData],
                    userAuthToken: String,
                    headerData: JsValue,
                    searchKeys: SearchKeys)

object Metadata {
  implicit val idformat: OFormat[IdentityData] = IdentityData.format
  implicit val dateFormats: Format[DateTime] = DateUtils.isoInstantDateFormat
  implicit val format: OFormat[Metadata] = Json.format[Metadata]
} 
Example 26
Source File: IdentityData.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.nrs.request

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json.{Format, Json, OFormat}
import uk.gov.hmrc.auth.core.retrieve._
import uk.gov.hmrc.auth.core.{AffinityGroup, ConfidenceLevel, CredentialRole}
import utils.DateUtils

case class IdentityData(internalId: Option[String] = None,
                        externalId: Option[String] = None,
                        agentCode: Option[String] = None,
                        credentials: Option[Credentials] = None,
                        confidenceLevel: ConfidenceLevel,
                        nino: Option[String] = None,
                        saUtr: Option[String] = None,
                        name: Option[Name] = None,
                        dateOfBirth: Option[LocalDate] = None,
                        email: Option[String] = None,
                        agentInformation: AgentInformation,
                        groupIdentifier: Option[String] = None,
                        credentialRole: Option[CredentialRole],
                        mdtpInformation: Option[MdtpInformation] = None,
                        itmpName: ItmpName,
                        itmpDateOfBirth: Option[LocalDate] = None,
                        itmpAddress: ItmpAddress,
                        affinityGroup: Option[AffinityGroup],
                        credentialStrength: Option[String] = None,
                        loginTimes: LoginTimes)

object IdentityData {
  implicit val localDateFormats: Format[LocalDate] = DateUtils.dateFormat
  implicit val credFormat: OFormat[Credentials] = Json.format[Credentials]
  implicit val nameFormat: OFormat[Name] = Json.format[Name]
  implicit val agentInfoFormat: OFormat[AgentInformation] = Json.format[AgentInformation]
  implicit val mdtpInfoFormat: OFormat[MdtpInformation] = Json.format[MdtpInformation]
  implicit val itmpNameFormat: OFormat[ItmpName] = Json.format[ItmpName]
  implicit val itmpAddressFormat: OFormat[ItmpAddress] = Json.format[ItmpAddress]
  implicit val dateTimeFormats: Format[DateTime] = DateUtils.isoInstantDateFormat
  implicit val loginTimesFormat: OFormat[LoginTimes] = Json.format[LoginTimes]
  implicit val format: OFormat[IdentityData] = Json.format[IdentityData]
} 
Example 27
Source File: DateUtils.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package utils

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json.{Format, JodaReads, JodaWrites}

object DateUtils {

  val isoInstantDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"
  val isoInstantDateRegex = """(\d){4}-(\d){2}-(\d){2}T(\d){2}:(\d){2}:(\d){2}Z"""
  val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  val datePattern = "yyyy-MM-dd"

  val dateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(dateTimePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )

  val isoInstantDateFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(isoInstantDatePattern)
  )

  val defaultDateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )

  val dateFormat: Format[LocalDate] = Format[LocalDate](
    JodaReads.jodaLocalDateReads(datePattern),
    JodaWrites.jodaLocalDateWrites(datePattern)
  )
} 
Example 28
Source File: ApiDefinition.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package definition

import play.api.libs.json.{Format, Json, OFormat}
import utils.enums.Enums

case class Access(`type`: String, whitelistedApplicationIds: Seq[String])

object Access {
  implicit val formatAccess: OFormat[Access] = Json.format[Access]
}

case class Parameter(name: String, required: Boolean = false)

object Parameter {
  implicit val formatParameter: OFormat[Parameter] = Json.format[Parameter]
}

case class PublishingException(message: String) extends Exception(message)

sealed trait APIStatus

object APIStatus extends Enumeration {
  case object ALPHA extends APIStatus
  case object BETA extends APIStatus
  case object STABLE extends APIStatus
  case object DEPRECATED extends APIStatus
  case object RETIRED extends APIStatus

  implicit val formatApiVersion: Format[APIStatus] = Enums.format[APIStatus]
  val parser: PartialFunction[String, APIStatus] = Enums.parser[APIStatus]
}

case class APIVersion(version: String, access: Option[Access] = None, status: APIStatus, endpointsEnabled: Boolean) {

  require(version.nonEmpty, "version is required")
}

object APIVersion {
  implicit val formatAPIVersion: OFormat[APIVersion] = Json.format[APIVersion]
}

case class APIDefinition(name: String,
                         description: String,
                         context: String,
                         categories: Seq[String],
                         versions: Seq[APIVersion],
                         requiresTrust: Option[Boolean]) {

  require(name.nonEmpty, "name is required")
  require(context.nonEmpty, "context is required")
  require(categories.nonEmpty, "at least one category is required")
  require(description.nonEmpty, "description is required")
  require(versions.nonEmpty, "at least one version is required")
  require(uniqueVersions, "version numbers must be unique")

  private def uniqueVersions = {
    !versions.map(_.version).groupBy(identity).mapValues(_.size).exists(_._2 > 1)
  }
}

object APIDefinition {
  implicit val formatAPIDefinition: OFormat[APIDefinition] = Json.format[APIDefinition]
}

case class Scope(key: String, name: String, description: String)

object Scope {
  implicit val formatScope: OFormat[Scope] = Json.format[Scope]
}

case class Definition(scopes: Seq[Scope], api: APIDefinition)

object Definition {
  implicit val formatDefinition: OFormat[Definition] = Json.format[Definition]
} 
Example 29
Source File: ErrorCode.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import play.api.libs.json.Format

object ErrorCode extends Enumeration {
  type ErrorCode = Value
  val
  INVALID_VALUE,
  INVALID_FIELD_LENGTH,
  INVALID_FIELD_FORMAT,
  INVALID_MONETARY_AMOUNT,
  INVALID_NUMERIC_VALUE,
  INVALID_STRING_VALUE,
  INVALID_TAX_DEDUCTION_AMOUNT,
  INVALID_DISALLOWABLE_AMOUNT,
  DEPRECIATION_DISALLOWABLE_AMOUNT,
  DATE_NOT_IN_THE_PAST,
  DATE_IN_THE_FUTURE,
  START_DATE_INVALID,
  BOTH_EXPENSES_SUPPLIED,
  INVALID_PERIOD,
  PERIOD_KEY_INVALID,
  INVALID_ACCOUNTING_PERIOD,
  ALREADY_EXISTS,
  TOO_MANY_SOURCES,
  INVALID_BALANCING_CHARGE_BPRA,
  NOT_IMPLEMENTED,
  TAX_YEAR_INVALID,
  VRN_INVALID,
  AGENT_NOT_SUBSCRIBED,
  AGENT_NOT_AUTHORIZED,
  CLIENT_NOT_SUBSCRIBED,
  CLIENT_OR_AGENT_NOT_AUTHORISED,
  INVALID_BUSINESS_DESCRIPTION,
  INVALID_POSTCODE,
  NOT_CONTIGUOUS_PERIOD,
  OVERLAPPING_PERIOD,
  MISALIGNED_PERIOD,
  MANDATORY_FIELD_MISSING,
  INVALID_REQUEST,
  INVALID_TYPE,
  VAT_TOTAL_VALUE,
  VAT_NET_VALUE,
  NOT_FINALISED,
  INVALID_DATE,
  INVALID_FROM_DATE,
  INVALID_TO_DATE,
  INVALID_DATE_RANGE,
  DUPLICATE_SUBMISSION
  = Value

  implicit val format: Format[ErrorCode] = EnumJson.enumFormat(ErrorCode,
    Some(s"Recognized ErrorCode values: ${ErrorCode.values.mkString(", ")}"))
} 
Example 30
Source File: VatReturn.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import org.joda.time.DateTime
import play.api.libs.json.{Format, Json}
import uk.gov.hmrc.vatapi.models.Amount

case class VatReturn(periodKey: String,
                     vatDueSales: Amount,
                     vatDueAcquisitions: Amount,
                     vatDueTotal: Amount,
                     vatReclaimedCurrPeriod: Amount,
                     vatDueNet: Amount,
                     totalValueSalesExVAT: Amount,
                     totalValuePurchasesExVAT: Amount,
                     totalValueGoodsSuppliedExVAT: Amount,
                     totalAllAcquisitionsExVAT: Amount,
                     agentReferenceNumber: Option[String] = None,
                     receivedAt: Option[DateTime] = None)

object VatReturn {
  implicit val dateFormats: Format[DateTime] = uk.gov.hmrc.vatapi.models.dateTimeFormat
  implicit val format: Format[VatReturn] = Json.format[VatReturn]
} 
Example 31
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 32
Source File: EnumJsonSpecSupport.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package utils.enums

import play.api.libs.json.{Format, Json}
import support.UnitSpec

trait EnumJsonSpecSupport {
  self: UnitSpec =>

  

  def testRoundTrip[A: Format](namesAndValues: (String, A)*): Unit =
    "JSON formats" must {
      "support round trip" in {
        namesAndValues.foreach {
          case (name, obj) =>
            val json = Json.parse(s""""$name"""")

            Json.toJson(obj) shouldBe json
            json.as[A] shouldBe obj
        }
      }
    }
} 
Example 33
Source File: ThingType.scala    From swagger-check   with MIT License 5 votes vote down vote up
package models

import play.api.libs.json.{Format, JsResult, JsString, JsValue}
import play.api.mvc.QueryStringBindable.Parsing

object ThingType extends Enumeration {
  type Type = Value
  val Primary, Secondary, Other = Value

  implicit val jsonFormat = new Format[Type] {
    override def reads(json: JsValue): JsResult[Type] =
      json.validate[String].map(ThingType.withName)

    override def writes(o: Type): JsValue = JsString(o.toString)
  }

  implicit val queryBinder = new Parsing[Type](
    parse = ThingType.withName,
    serialize = v => v.toString,
    error = (key: String, e: Exception) => "Cannot parse parameter %s as ThingType: %s".format(key, e.getMessage)
  )
} 
Example 34
Source File: Slug.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.actions

import org.coursera.common.jsonformat.JsonFormats
import org.coursera.common.stringkey.StringKeyFormat
import play.api.libs.json.Format

import scala.annotation.tailrec


  def slugify(input: String): Slug = {
    // Convert the unicode input to ascii. This ensures that non Latin based languages have
    // reasonable conversions.
    val slugString = input //Junidecode.unidecode(input)
      .replaceAll("([a-z])'s([^a-z])", "$1s$2") // Convert apostrophes.
      .replaceAll("[^a-zA-Z0-9]", "-") // Convert all non alphanumeric characters with hyphen.
      .replaceAll("-{2,}", "-") // Collapse multiple hyphens into one
      .stripPrefix("-")
      .stripSuffix("-")
      .toLowerCase

    val words = slugString.split("-").toList
    if (words.head.length() > MaxSlugLength) {
      Slug(words.head.take(MaxSlugLength))
    } else {
      @tailrec
      def buildTruncatedSlug(currentWord: String, wordList: List[String]): String = {
        wordList match {
          case firstWord :: tail =>
            val candidate = currentWord + "-" + firstWord
            if (candidate.length() > MaxSlugLength) {
              currentWord
            } else {
              buildTruncatedSlug(candidate, tail)
            }
          case Nil => currentWord
        }
      }
      Slug(buildTruncatedSlug(words.head, words.drop(1)))
    }
  }

} 
Example 35
Source File: ShopService.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
package ch15

import ch15.model._
import com.lightbend.lagom.scaladsl.api.Service._
import com.lightbend.lagom.scaladsl.api._
import play.api.libs.json.{Format, Json}
import ShopService._
import com.lightbend.lagom.scaladsl.api.transport.Method

trait ShopService extends Service {
  def order: ServiceCall[Order, Purchase]

  override def descriptor: Descriptor = {
    named("GroceryShop").withCalls(restCall(Method.POST, "/purchase", order))
  }
}

object ShopService {
  final case class Order(order: ShoppingList)
  final case class Purchase(order: Groceries)
  implicit val purchase: Format[Purchase] = Json.format
  implicit val order: Format[Order] = Json.format
} 
Example 36
Source File: PlayDefinitions.scala    From circe-benchmarks   with Apache License 2.0 5 votes vote down vote up
package io.circe.benchmarks

import org.openjdk.jmh.annotations._
import play.api.libs.functional.syntax._
import play.api.libs.json.{ Format, JsPath, JsValue, Json, Writes }

trait PlayFooInstances {
  implicit val playFormatFoo: Format[Foo] = (
    (JsPath \ "s")
      .format[String]
      .and((JsPath \ "d").format[Double])
      .and((JsPath \ "i").format[Int])
      .and((JsPath \ "l").format[Long])
      .and((JsPath \ "bs").format[List[Boolean]])
    )(Foo.apply, unlift(Foo.unapply))
}

trait PlayData { self: ExampleData =>
  @inline def encodeP[A](a: A)(implicit encode: Writes[A]): JsValue = encode.writes(a)

  val foosP: JsValue = encodeP(foos)
  val intsP: JsValue = encodeP(ints)
}

trait PlayWriting { self: ExampleData =>
  @Benchmark
  def writeFoosPlay: String = Json.stringify(encodeP(foos))

  @Benchmark
  def writeIntsPlay: String = Json.stringify(encodeP(ints))
}

trait PlayReading { self: ExampleData =>
  @Benchmark
  def readFoosPlay: Map[String, Foo] = Json.parse(foosJson).as[Map[String, Foo]]

  @Benchmark
  def readIntsPlay: List[Int] = Json.parse(intsJson).as[List[Int]]
}

trait PlayEncoding { self: ExampleData =>
  @Benchmark
  def encodeFoosPlay: JsValue = encodeP(foos)

  @Benchmark
  def encodeIntsPlay: JsValue = encodeP(ints)
}

trait PlayDecoding { self: ExampleData =>
  @Benchmark
  def decodeFoosPlay: Map[String, Foo] = foosP.as[Map[String, Foo]]

  @Benchmark
  def decodeIntsPlay: List[Int] = intsP.as[List[Int]]
}

trait PlayPrinting { self: ExampleData =>
  @Benchmark
  def printFoosPlay: String = Json.stringify(foosP)

  @Benchmark
  def printIntsPlay: String = Json.stringify(intsP)
}

trait PlayParsing { self: ExampleData =>
  @Benchmark
  def parseFoosPlay: JsValue = Json.parse(foosJson)

  @Benchmark
  def parseIntsPlay: JsValue = Json.parse(intsJson)
} 
Example 37
Source File: JsonEntitiesFromCodecs.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.algebra.playjson

import endpoints4s.{Codec, Invalid, Valid, Validated}
import play.api.libs.json.{Format, JsPath, Json, JsonValidationError}

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


trait JsonEntitiesFromCodecs extends endpoints4s.algebra.JsonEntitiesFromCodecs {

//#type-carrier
  type JsonCodec[A] = Format[A]
//#type-carrier

  def stringCodec[A: Format]: Codec[String, A] =
    new Codec[String, A] {

      def decode(from: String): Validated[A] =
        (Try(Json.parse(from)) match {
          case Failure(_) => Left(Invalid("Unable to parse entity as JSON"))
          case Success(a) => Right(a)
        }).flatMap { json =>
          def showErrors(
              errors: collection.Seq[
                (JsPath, collection.Seq[JsonValidationError])
              ]
          ): Invalid =
            Invalid(
              (
                for {
                  (path, pathErrors) <- errors.iterator
                  error <- pathErrors
                } yield s"${error.message} for ${path.toJsonString}"
              ).toSeq
            )
          Json
            .fromJson[A](json)
            .asEither
            .left
            .map(showErrors)
            .map(Valid(_))
        }.merge

      def encode(from: A): String = Json.stringify(Json.toJson(from))

    }

} 
Example 38
Source File: ServiceMethod.scala    From typebus   with MIT License 5 votes vote down vote up
package io.surfkit.typebus.annotations

import java.nio.file.Files

import io.surfkit.typebus.ResourceDb
import play.api.libs.json.{Json, OFormat, Format}

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context

@compileTimeOnly("enable macro to expand macro annotations")
class ServiceMethod extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro ServiceMethod.impl
}

object ServiceMethod extends ResourceDb{

  val databaseTableName = "_Service"

  sealed trait Store
  object Store{
    implicit val format: OFormat[Store] = Json.format[Store]
  }
  final case class ServiceMethod(in: String, out: String) extends Store
  object ServiceMethod{
    implicit val format: Format[ServiceMethod] = Json.format[ServiceMethod]
  }
  final case class ServiceStore(methods: Set[ServiceMethod]) extends Store
  object ServiceStore{
    implicit val format: Format[ServiceStore] = Json.format[ServiceStore]
  }

  var methods = Set.empty[ServiceMethod]

  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val result =
      annottees.map(_.tree).toList match {
        case q"$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType] = { ..$body }" :: Nil =>
        //case q"$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType]{..$body}" :: Nil =>
          // https://stackoverflow.com/questions/19379436/cant-access-parents-members-while-dealing-with-macro-annotations
          val retTpe = c.typecheck(q"(??? : $returnType)").tpe
          val argChild = arg.children.head
          val argTpe = c.typecheck(q"(??? : $argChild)").tpe
          //println(s"retTpe:${retTpe}  ${retTpe.typeSymbol.fullName}")
          //println(s"argTpe:${argTpe}  ${argTpe.typeSymbol.fullName}")
          // FIXME: packaging a jar will fail when trying to access the resource files.  For now we can skip this.
          try {
            methods += ServiceMethod(argTpe.typeSymbol.fullName, retTpe.typeSymbol.fullName)
            val servicePath = databaseTablePath(databaseTableName)
            Files.write(servicePath, serialiseServiceStore(ServiceStore(methods)).getBytes)
          }catch{
            case _: Throwable =>
          }
          q"""$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType] = { ..$body }"""

        case _ => c.abort(c.enclosingPosition, s"Annotation @ServiceMethod can be used only with methods of the form (T, EventMeta) => Future[U] instead of: ${annottees.map(_.tree).toList}")
      }
    c.Expr[Any](result)
  }

  def serialiseServiceStore(value: ServiceStore): String = Json.toJson(value).toString()
    //Pickle.intoBytes(value).array

  def deSerialiseServiceStore(json: String): ServiceStore = Json.parse(json).as[ServiceStore]
    //Unpickle[ServiceStore].fromBytes(java.nio.ByteBuffer.wrap(bytes))
} 
Example 39
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 40
Source File: Messages.scala    From Akka-Cookbook   with MIT License 5 votes vote down vote up
package com.packt.chapter11.token.api

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

case class RetrieveTokenRequest(clientId: String, clientSecret: String)
case class RetrieveTokenResult(successful: Boolean, token: Option[String] = None)
case class ValidateTokenRequest(clientId: String, token: String)
case class ValidateTokenResult(successful: Boolean)

object RetrieveTokenRequest {
  implicit val retrieveTokenRequestFormat: Format[RetrieveTokenRequest] = Json.format[RetrieveTokenRequest]
}
object RetrieveTokenResult {
  implicit val retrieveTokenResultFormat: Format[RetrieveTokenResult] = Json.format[RetrieveTokenResult]
}
object ValidateTokenRequest {
  implicit val validateTokenRequestFormat: Format[ValidateTokenRequest] = Json.format[ValidateTokenRequest]
}
object ValidateTokenResult {
  implicit val validateTokenResultFormat: Format[ValidateTokenResult] = Json.format[ValidateTokenResult]
} 
Example 41
Source File: CommandEventState.scala    From Akka-Cookbook   with MIT License 5 votes vote down vote up
package com.packt.chapter11.trip.impl

import akka.Done
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import com.packt.chapter11.trip.api.ReportLocation
import play.api.libs.json.{Format, Json}

sealed trait ClientCommand[R] extends ReplyType[R]
case object StartTrip extends ClientCommand[Done]
case object EndTrip extends ClientCommand[Done]
case class AddLocation(reportLocationRequest: ReportLocation) extends ClientCommand[Done]

sealed trait ClientEvent
case class TripStarted(time: Long) extends ClientEvent
case class TripEnded(time: Long) extends ClientEvent
case class LocationAdded(location: Location) extends ClientEvent

case class Location(lat: Double, lon: Double)
case class ClientState(tripInProgress: Boolean, locations: List[Location])

object Location {
  implicit val format : Format[Location] = Json.format[Location]
}
object ClientState {
  implicit val format: Format[ClientState] = Json.format
}
object TripStarted {
  implicit val format: Format[TripStarted] = Json.format
}
object TripEnded {
  implicit val format: Format[TripEnded] = Json.format
}
object LocationAdded {
  implicit val format: Format[LocationAdded] = Json.format
}
object AddLocation {
  implicit val format: Format[AddLocation] = Json.format
} 
Example 42
Source File: ScodecHelper.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.util

import cats.MonadError
import cats.data.{NonEmptyList => Nel}
import cats.implicits._
import com.evolutiongaming.kafka.journal.JsonCodec
import play.api.libs.json.Format
import scodec.bits.ByteVector
import scodec.{Attempt, Codec, Err, codecs}

import scala.annotation.tailrec
import scala.util.Try

object ScodecHelper {

  implicit val attemptMonadError: MonadError[Attempt, Attempt.Failure] = {

    import Attempt._

    new MonadError[Attempt, Failure] {

      def raiseError[A](a: Failure) = a

      def handleErrorWith[A](fa: Attempt[A])(f: Failure => Attempt[A]) = {
        fa match {
          case fa: Successful[A] => fa
          case fa: Failure       => f(fa)
        }
      }

      def pure[A](a: A) = Successful(a)

      def flatMap[A, B](fa: Attempt[A])(f: A => Attempt[B]) = fa.flatMap(f)

      @tailrec
      def tailRecM[A, B](a: A)(f: A => Attempt[Either[A, B]]): Attempt[B] = {
        f(a) match {
          case b: Failure                  => b
          case b: Successful[Either[A, B]] => b.value match {
            case Left(b1) => tailRecM(b1)(f)
            case Right(a) => Successful(a)
          }
        }
      }
    }
  }


  def nelCodec[A](codec: Codec[List[A]]): Codec[Nel[A]] = {
    val to = (a: List[A]) => {
      Attempt.fromOption(a.toNel, Err("list is empty"))
    }
    val from = (a: Nel[A]) => Attempt.successful(a.toList)
    codec.exmap(to, from)
  }


  def formatCodec[A](implicit format: Format[A], jsonCodec: JsonCodec[Try]): Codec[A] = {
    val fromBytes = (bytes: ByteVector) => {
      val jsValue = jsonCodec.decode.fromBytes(bytes)
      for {
        a <- Attempt.fromTry(jsValue)
        a <- format.reads(a).fold(a => Attempt.failure(Err(a.toString())), Attempt.successful)
      } yield a
    }
    val toBytes = (a: A) => {
      val jsValue = format.writes(a)
      val bytes = jsonCodec.encode.toBytes(jsValue)
      Attempt.fromTry(bytes)
    }
    codecs.bytes.exmap(fromBytes, toBytes)
  }
} 
Example 43
Source File: HelloWorldEntity.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.example.helloworld.impl

import java.time.LocalDateTime

import akka.Done
import com.lightbend.lagom.scaladsl.persistence.AggregateEventShards
import com.lightbend.lagom.scaladsl.persistence.{ PersistentEntity, AggregateEventTag, AggregateEvent }
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import com.lightbend.lagom.scaladsl.playjson.{ JsonSerializer, JsonSerializerRegistry }
import play.api.libs.json.{ Format, Json }

import scala.collection.immutable.Seq

class HelloWorldEntity extends PersistentEntity {

  override type Command = HelloWorldCommand[_]
  override type Event = HelloWorldEvent
  override type State = HelloWorldState

  override def initialState: HelloWorldState = HelloWorldState("Hello", LocalDateTime.now.toString)

  override def behavior: Behavior = {
    case HelloWorldState(message, _) => Actions().onCommand[UseGreetingMessage, Done] {
      case (UseGreetingMessage(newMessage), ctx, state) =>
        ctx.thenPersist(
          GreetingMessageChanged(entityId, newMessage)
        ) { _ =>
          ctx.reply(Done)
        }
    }.onReadOnlyCommand[Hello, String] {
      case (Hello(name), ctx, state) =>
        ctx.reply(s"$message, $name!")
    }.onEvent {
      case (GreetingMessageChanged(_, newMessage), state) =>
        HelloWorldState(newMessage, LocalDateTime.now().toString)
    }
  }
}

case class HelloWorldState(message: String, timestamp: String)
object HelloWorldState {
  implicit val format: Format[HelloWorldState] = Json.format
}

sealed trait HelloWorldEvent extends AggregateEvent[HelloWorldEvent] {
  override def aggregateTag: AggregateEventShards[HelloWorldEvent] = HelloWorldEvent.Tag
}
object HelloWorldEvent {
  val NumShards = 4
  val Tag = AggregateEventTag.sharded[HelloWorldEvent](NumShards)
}

case class GreetingMessageChanged(id:String, message: String) extends HelloWorldEvent
object GreetingMessageChanged {
  implicit val format: Format[GreetingMessageChanged] = Json.format
}

sealed trait HelloWorldCommand[R] extends ReplyType[R]

case class UseGreetingMessage(message: String) extends HelloWorldCommand[Done]
object UseGreetingMessage {
  implicit val format: Format[UseGreetingMessage] = Json.format
}

case class Hello(name: String) extends HelloWorldCommand[String]
object Hello {
  implicit val format: Format[Hello] = Json.format
}

object HelloWorldSerializerRegistry extends JsonSerializerRegistry {
  override def serializers: Seq[JsonSerializer[_]] = Seq(
    JsonSerializer[UseGreetingMessage],
    JsonSerializer[Hello],
    JsonSerializer[GreetingMessageChanged],
    JsonSerializer[HelloWorldState]
  )
} 
Example 44
Source File: ShoppingCartService.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.example.shoppingcart.api

import java.time.Instant

import akka.{Done, NotUsed}
import com.lightbend.lagom.scaladsl.api.transport.Method
import com.lightbend.lagom.scaladsl.api.{Service, ServiceCall}
import play.api.libs.json.{Format, Json}


trait ShoppingCartService extends Service {

  def get(id: String): ServiceCall[NotUsed, String]

  def getReport(id: String): ServiceCall[NotUsed, String]

  def updateItem(id: String, productId: String, qty: Int): ServiceCall[NotUsed, String]

  def checkout(id: String): ServiceCall[NotUsed, String]

  override final def descriptor = {
    import Service._
    named("shopping-cart")
      .withCalls(
        restCall(Method.GET, "/shoppingcart/:id", get _),
        restCall(Method.GET, "/shoppingcart/:id/report", getReport _),
        // for the RESTafarians, my formal apologies but the GET calls below do mutate state
        // we just want an easy way to mutate data from a sbt scripted test, so no POST/PUT here
        restCall(Method.GET, "/shoppingcart/:id/:productId/:num", updateItem _),
        restCall(Method.GET, "/shoppingcart/:id/checkout", checkout _)
      )
      .withAutoAcl(true)
  }
} 
Example 45
Source File: ServiceRegistryInteropSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.registry.impl

import java.net.URI
import java.util.Collections
import java.util.Optional

import akka.actor.ActorSystem
import akka.testkit.TestKit
import akka.util.ByteString
import com.lightbend.lagom.devmode.internal.scaladsl.registry.RegisteredService
import com.lightbend.lagom.devmode.internal.scaladsl.registry.ServiceRegistryService
import com.lightbend.lagom.internal.javadsl.registry.{ RegisteredService => jRegisteredService }
import com.lightbend.lagom.internal.javadsl.registry.{ ServiceRegistryService => jServiceRegistryService }
import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ RegisteredService => sRegisteredService }
import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ ServiceRegistryService => sServiceRegistryService }
import com.lightbend.lagom.javadsl.api.ServiceAcl
import com.lightbend.lagom.javadsl.api.deser.MessageSerializer
import com.lightbend.lagom.javadsl.api.deser.StrictMessageSerializer
import com.lightbend.lagom.javadsl.api.transport.MessageProtocol
import com.lightbend.lagom.javadsl.api.transport.Method
import com.lightbend.lagom.javadsl.jackson.JacksonSerializerFactory
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.Futures
import play.api.libs.json.Format
import play.api.libs.json.Json
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class ServiceRegistryInteropSpec extends AnyFlatSpec with Matchers with Futures with BeforeAndAfterAll {
  val system                   = ActorSystem()
  val jacksonSerializerFactory = new JacksonSerializerFactory(system)

  protected override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(actorSystem = system, verifySystemShutdown = true)
  }

  behavior.of("ServiceRegistry serializers")

  it should "should interop between java and scala (RegisteredService)" in {
    val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.of("https"))
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala when optional fields are empty (RegisteredService)" in {
    val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.empty[String])
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala (ServiceRegistryService)" in {
    val msg = jServiceRegistryService.of(
      URI.create("https://localhost:123/asdf"),
      Collections.singletonList(ServiceAcl.methodAndPath(Method.GET, "/items"))
    )
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala when optional fields are empty (ServiceRegistryService)" in {
    val msg = jServiceRegistryService.of(URI.create("https://localhost:123/asdf"), Collections.emptyList[ServiceAcl])
    roundTrip(msg) should be(msg)
  }

  private def roundTrip(input: jServiceRegistryService): jServiceRegistryService = {
    roundTrip(
      input,
      jacksonSerializerFactory.messageSerializerFor[jServiceRegistryService](classOf[jServiceRegistryService]),
      com.lightbend.lagom.scaladsl.playjson.JsonSerializer[ServiceRegistryService].format
    )(sServiceRegistryService.format)
  }

  private def roundTrip(input: jRegisteredService): jRegisteredService = {
    roundTrip(
      input,
      jacksonSerializerFactory.messageSerializerFor[jRegisteredService](classOf[jRegisteredService]),
      com.lightbend.lagom.scaladsl.playjson.JsonSerializer[RegisteredService].format
    )(sRegisteredService.format)
  }

  private def roundTrip[J, S](
      input: J,
      jacksonSerializer: StrictMessageSerializer[J],
      playJsonFormatter: Format[S]
  )(implicit format: Format[S]): J = {
    val byteString: ByteString = jacksonSerializer.serializerForRequest().serialize(input)
    val scalaValue: S          = playJsonFormatter.reads(Json.parse(byteString.toArray)).get
    val str: String            = playJsonFormatter.writes(scalaValue).toString()
    val jacksonDeserializer: MessageSerializer.NegotiatedDeserializer[J, ByteString] =
      jacksonSerializer.deserializer(
        new MessageProtocol(Optional.of("application/json"), Optional.empty[String], Optional.empty[String])
      )
    jacksonDeserializer.deserialize(ByteString(str))
  }
} 
Example 46
Source File: HelloService.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.scaladsl.mb

import akka.Done
import akka.NotUsed

//#hello-service
import com.lightbend.lagom.scaladsl.api.broker.Topic
import com.lightbend.lagom.scaladsl.api.Service
import com.lightbend.lagom.scaladsl.api.ServiceCall
import play.api.libs.json.Format
import play.api.libs.json.Json

object HelloService {
  val TOPIC_NAME = "greetings"
}
trait HelloService extends Service {
  final override def descriptor = {
    import Service._
    named("brokerdocs")
      .withCalls(
        pathCall("/api/hello/:id", hello _),
        pathCall("/api/hello/:id", useGreeting _)
      )
      .withTopics(
        topic(HelloService.TOPIC_NAME, greetingsTopic)
      )
      .withAutoAcl(true)
  }

  // The topic handle
  def greetingsTopic(): Topic[GreetingMessage]

  def hello(id: String): ServiceCall[NotUsed, String]
  def useGreeting(id: String): ServiceCall[GreetingMessage, Done]
}
//#hello-service

case class GreetingMessage(message: String)

object GreetingMessage {
  implicit val format: Format[GreetingMessage] = Json.format[GreetingMessage]
} 
Example 47
Source File: PublishServiceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.scaladsl.mb

import com.lightbend.lagom.scaladsl.api.broker.Topic
import com.lightbend.lagom.scaladsl.server.LagomApplication
import com.lightbend.lagom.scaladsl.server.LagomApplicationContext
import com.lightbend.lagom.scaladsl.server.LagomServer
import com.lightbend.lagom.scaladsl.server.LocalServiceLocator
import com.lightbend.lagom.scaladsl.testkit.ServiceTest
import com.lightbend.lagom.scaladsl.testkit.TestTopicComponents
import play.api.libs.ws.ahc.AhcWSComponents
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AsyncWordSpec
import akka.NotUsed
import akka.Done
import akka.stream.scaladsl.Source
import akka.stream.testkit.scaladsl.TestSink
import akka.stream.testkit.TestSubscriber
import akka.stream.testkit.TestSubscriber.Probe

abstract class PublishApplication(context: LagomApplicationContext)
    extends LagomApplication(context)
    with AhcWSComponents {
  override lazy val lagomServer = serverFor[service.PublishService](new service.PublishServiceImpl())
}

package service {
  import com.lightbend.lagom.scaladsl.api.Service
  import com.lightbend.lagom.scaladsl.broker.TopicProducer

  object PublishService {
    val TOPIC_NAME = "events"
  }

  trait PublishService extends Service {
    final override def descriptor = {
      import Service._
      named("brokerdocs")
        .withTopics(topic(PublishService.TOPIC_NAME, events))
        .withAutoAcl(true)
    }

    def events(): Topic[PubMessage]
  }

  case class PubMessage(message: String)

  object PubMessage {
    import play.api.libs.json.Format
    import play.api.libs.json.Json
    implicit val format: Format[PubMessage] = Json.format[PubMessage]
  }

  class PublishServiceImpl() extends PublishService {
    override def events(): Topic[PubMessage] =
      TopicProducer.singleStreamWithOffset { offset =>
        Source((1 to 10)).map(i => (PubMessage(s"msg $i"), offset))
      }
  }
}

class PublishServiceSpec extends AsyncWordSpec with Matchers {
  import service._

  //#topic-test-publishing-into-a-topic
  "The PublishService" should {
    "publish events on the topic" in ServiceTest.withServer(ServiceTest.defaultSetup) { ctx =>
      new PublishApplication(ctx) with LocalServiceLocator with TestTopicComponents
    } { server =>
      implicit val system = server.actorSystem
      implicit val mat    = server.materializer

      val client: PublishService = server.serviceClient.implement[PublishService]
      val source                 = client.events().subscribe.atMostOnceSource
      source
        .runWith(TestSink.probe[PubMessage])
        .request(1)
        .expectNext should ===(PubMessage("msg 1"))
    }
  }
  //#topic-test-publishing-into-a-topic
} 
Example 48
Source File: HelloEntity.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.scaladsl.mb

import java.time.LocalDateTime

import akka.Done
import com.lightbend.lagom.scaladsl.persistence.AggregateEvent
import com.lightbend.lagom.scaladsl.persistence.AggregateEventTag
import com.lightbend.lagom.scaladsl.persistence.AggregateEventTagger
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.playjson.JsonSerializer
import play.api.libs.json.Format
import play.api.libs.json.Json

import scala.collection.immutable.Seq

class HelloEntity extends PersistentEntity {
  override type Command = HelloCommand[_]
  override type Event   = HelloEvent
  override type State   = HelloState

  override def initialState: HelloState = HelloState("Hello", LocalDateTime.now.toString)

  override def behavior: Behavior = {
    case HelloState(message, _) =>
      Actions()
        .onCommand[UseGreetingMessage, Done] {
          // Command handler for the UseGreetingMessage command
          case (UseGreetingMessage(newMessage), ctx, state) =>
            // In response to this command, we want to first persist it as a
            // GreetingMessageChanged event
            ctx.thenPersist(GreetingMessageChanged(newMessage)) {
              // Then once the event is successfully persisted, we respond with done.
              _ =>
                ctx.reply(Done)
            }
        }
        .onReadOnlyCommand[Hello, String] {
          // Command handler for the Hello command
          case (Hello(name, organization), ctx, state) =>
            // Reply with a message built from the current message, and the name of
            // the person we're meant to say hello to.
            ctx.reply(s"$message, $name!")
        }
        .onEvent {
          // Event handler for the GreetingMessageChanged event
          case (GreetingMessageChanged(newMessage), state) =>
            // We simply update the current state to use the greeting message from
            // the event.
            HelloState(newMessage, LocalDateTime.now().toString)
        }
  }
}

case class HelloState(message: String, timestamp: String)

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

object HelloEventTag {
  val INSTANCE: AggregateEventTag[HelloEvent] = AggregateEventTag[HelloEvent]()
}

sealed trait HelloEvent extends AggregateEvent[HelloEvent] {
  override def aggregateTag: AggregateEventTagger[HelloEvent] = HelloEventTag.INSTANCE
}

case class GreetingMessageChanged(message: String) extends HelloEvent

object GreetingMessageChanged {
  implicit val format: Format[GreetingMessageChanged] = Json.format
}
sealed trait HelloCommand[R] extends ReplyType[R]

case class UseGreetingMessage(message: String) extends HelloCommand[Done]

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

case class Hello(name: String, organization: Option[String]) extends HelloCommand[String]

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

object HelloSerializerRegistry extends JsonSerializerRegistry {
  override def serializers: Seq[JsonSerializer[_]] = Seq(
    JsonSerializer[UseGreetingMessage],
    JsonSerializer[Hello],
    JsonSerializer[GreetingMessageChanged],
    JsonSerializer[HelloState]
  )
} 
Example 49
Source File: AddComment.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.scaladsl.serialization

import play.api.libs.json.Format
import play.api.libs.json.Json

//#complexMembers
case class UserMetadata(twitterHandle: String)
object UserMetadata {
  implicit val format: Format[UserMetadata] = Json.format
}
case class AddComment(userId: String, comment: String, userMetadata: UserMetadata)
object AddComment {
  implicit val format: Format[AddComment] = Json.format
}
//#complexMembers 
Example 50
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 51
Source File: OrderAdded.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.scaladsl.serialization

import play.api.libs.json.Format
import play.api.libs.json.Json

case class OrderAdded(shoppingCartId: String)

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

object ManualMappingOrderAdded {
  //#manualMapping
  case class OrderAdded(productId: String, quantity: Int)

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

  object OrderAdded {
    implicit val format: Format[OrderAdded] =
      (JsPath \ "product_id")
        .format[String]
        .and((JsPath \ "quantity").format[Int])
        .apply(OrderAdded.apply, unlift(OrderAdded.unapply))
  }
  //#manualMapping
} 
Example 52
Source File: ApiDefinition.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.definition

import play.api.libs.json.{Format, Json}
import router.definition.APIStatus.APIStatus
import router.enums.EnumJson


case class Access(`type`: String, whitelistedApplicationIds: Seq[String])

object Access {
  implicit val formatAccess = Json.format[Access]
}

case class Parameter(name: String, required: Boolean = false)

object Parameter {
  implicit val formatParameter = Json.format[Parameter]
}

case class PublishingException(message: String) extends Exception(message)

object APIStatus extends Enumeration {
  type APIStatus = Value
  val ALPHA, BETA, STABLE, DEPRECATED, RETIRED = Value

  implicit val formatAPIStatus: Format[APIStatus] = EnumJson.enumFormat(APIStatus)
}

case class APIVersion(version: String,
                      access: Option[Access] = None,
                      status: APIStatus,
                      endpointsEnabled: Boolean) {

  require(version.nonEmpty, "version is required")
}

object APIVersion {
  implicit val formatAPIVersion = Json.format[APIVersion]
}

case class APIDefinition(name: String,
                         description: String,
                         context: String,
                         versions: Seq[APIVersion],
                         requiresTrust: Option[Boolean]) {

  require(name.nonEmpty, "name is required")
  require(context.nonEmpty, "context is required")
  require(description.nonEmpty, "description is required")
  require(versions.nonEmpty, "at least one version is required")
  require(uniqueVersions, "version numbers must be unique")

  private def uniqueVersions = {
    !versions.map(_.version).groupBy(identity).mapValues(_.size).exists(_._2 > 1)
  }
}

object APIDefinition {
  implicit val formatAPIDefinition = Json.format[APIDefinition]
}

case class Scope(key: String,
                 name: String,
                 description: String)

object Scope {
  implicit val formatScope = Json.format[Scope]
}

case class Definition(scopes: Seq[Scope],
                      api: APIDefinition)

object Definition {
  implicit val formatDefinition = Json.format[Definition]
} 
Example 53
Source File: ArticleWithTags.scala    From scala-play-realworld-example-app   with MIT License 5 votes vote down vote up
package articles.models

import java.time.Instant

import users.models.Profile
import play.api.libs.json.{Format, Json}

case class ArticleWithTags(id: ArticleId,
                           slug: String,
                           title: String,
                           description: String,
                           body: String,
                           createdAt: Instant,
                           updatedAt: Instant,
                           tagList: Seq[String],
                           author: Profile,
                           favorited: Boolean,
                           favoritesCount: Int)

object ArticleWithTags {

  implicit val articleWithTagsFormat: Format[ArticleWithTags] = Json.format[ArticleWithTags]

  def apply(article: Article, tags: Seq[Tag], author: Profile, favorited: Boolean,
            favoritesCount: Int): ArticleWithTags = {
    val tagValuesSorted = tags.map(_.name).sorted
    ArticleWithTags(
      article.id,
      article.slug,
      article.title,
      article.description,
      article.body,
      article.createdAt,
      article.updatedAt,
      tagValuesSorted,
      author,
      favorited,
      favoritesCount
    )
  }

  def fromTagValues(article: Article, tagValues: Seq[String], author: Profile, favorited: Boolean,
                    favoritesCount: Int): ArticleWithTags = {
    val tagValuesSorted = tagValues.sorted
    ArticleWithTags(
      article.id,
      article.slug,
      article.title,
      article.description,
      article.body,
      article.createdAt,
      article.updatedAt,
      tagValuesSorted,
      author,
      favorited,
      favoritesCount
    )
  }
} 
Example 54
Source File: CouchbaseReadSideQuery.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package docs.home.persistence

// #imports
import akka.NotUsed
import akka.stream.alpakka.couchbase.scaladsl.CouchbaseSession
import com.lightbend.lagom.scaladsl.api.{Service, ServiceCall}
import com.lightbend.lagom.scaladsl.persistence.ReadSide
import com.lightbend.lagom.scaladsl.persistence.couchbase.CouchbaseReadSide
import docs.home.persistence.CouchbaseReadSideProcessorTwo.HelloEventProcessor
import play.api.libs.json.{Format, Json}

import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
// #imports

object CouchbaseReadSideQuery {
  trait GreetingService extends Service {
    def userGreetings(): ServiceCall[NotUsed, List[UserGreeting]]

    override final def descriptor = {
      import Service._
      named("hello")
        .withCalls(
          pathCall("/api/user-greetings/", userGreetings _)
        )
        .withAutoAcl(true)
    }
  }

  case class UserGreeting(name: String, message: String)
  object UserGreeting {
    implicit val format: Format[UserGreeting] = Json.format[UserGreeting]
  }

  // #service-impl
  //#register-event-processor
  class GreetingServiceImpl(couchbaseReadSide: CouchbaseReadSide, readSideRegistry: ReadSide, session: CouchbaseSession)(
      implicit ec: ExecutionContext
  ) extends GreetingService {
    readSideRegistry.register[HelloEvent](new HelloEventProcessor(couchbaseReadSide))
    //#register-event-processor
    override def userGreetings() =
      ServiceCall { request =>
        session.get("users-actual-greetings").map {
          case Some(jsonDoc) =>
            val json = jsonDoc.content()
            json.getNames().asScala.map(name => UserGreeting(name, json.getString(name))).toList
          case None => List.empty[UserGreeting]
        }
      }
  }
  // #service-impl
} 
Example 55
Source File: StatefulStore.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.operator

import play.api.libs.json.{Format, JsObject, Json}
import skuber.ResourceSpecification.Subresources
import skuber.apiextensions.CustomResourceDefinition
import skuber.{CustomResource, ListResource, ResourceDefinition}

object StatefulStore {

  type Resource = CustomResource[StatefulStore.Spec, Status]
  type ResourceList = ListResource[Resource]

  case class Spec(`type`: Option[String], deployment: Option[String], config: Option[JsObject])

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

  case class Status(conditions: Option[List[Condition]], lastConfig: Option[String])

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

  implicit val statefulStoreResourceDefinition = ResourceDefinition[Resource](
    group = "cloudstate.io",
    version = "v1alpha1",
    kind = "StatefulStore",
    shortNames = Nil,
    subresources = Some(Subresources().withStatusSubresource)
  )

  implicit val statusSubEnabled = CustomResource.statusMethodsEnabler[Resource]

  val crd = CustomResourceDefinition[Resource]

  def apply(name: String, spec: Spec) = CustomResource[Spec, Status](spec).withName(name)
} 
Example 56
Source File: GenericStatus.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.operator

import java.time.ZonedDateTime

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

case class GenericStatus(
    conditions: Option[List[Condition]]
)

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

case class Condition(
    `type`: String,
    status: String,
    reason: Option[String] = None,
    message: Option[String] = None,
    severity: Option[String] = None,
    lastUpdateTime: Option[ZonedDateTime] = None,
    lastTransitionTime: Option[ZonedDateTime] = None
)

object Condition {
  private implicit val timeFormat: Format[ZonedDateTime] =
    Format(skuber.json.format.timeReads, skuber.json.format.timewWrites)
  implicit val format: Format[Condition] = Json.format
} 
Example 57
Source File: Watcher.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.operator

import akka.{Done, NotUsed}
import akka.stream.{KillSwitch, KillSwitches, Materializer}
import akka.stream.scaladsl.{Flow, Keep, RestartSource, Sink, Source}
import play.api.libs.json.Format
import skuber.{ListResource, ObjectResource, ResourceDefinition}
import skuber.api.client.{EventType, KubernetesClient, WatchEvent}

import scala.concurrent.duration._
import skuber.json.format._

import scala.concurrent.ExecutionContext

object Watcher {

  private implicit def listResourceFormat[Resource <: ObjectResource: Format]: Format[ListResource[Resource]] =
    ListResourceFormat(implicitly[Format[Resource]])

  def watch[Resource <: ObjectResource: Format: ResourceDefinition](
      client: KubernetesClient,
      handler: Flow[WatchEvent[Resource], _, _]
  )(implicit ec: ExecutionContext, mat: Materializer): KillSwitch =
    // Summary of what we want our event loop to look like:
    // * We start by listing all the resources, and process them.
    // * Then we start watching from the resourceVersion that we got in our list, so we get all updates.
    // * But we also want to periodically recheck all resources, since sometimes there are race conditions
    //   between operators handling dependent resources (eg, if you deploy a journal and a service that uses
    //   it at the same time), so we only run the watch for a maximum of that time (eg, 5 minutes), before
    //   restarting.
    // * Also, if errors are encountered, we don't want to continually restart in a hot loop, so we use the
    //   RestartSource to restart with backoff.
    RestartSource
      .onFailuresWithBackoff(2.seconds, 20.seconds, 0.2) { () =>
        val source = Source
          .repeat(NotUsed)
          .flatMapConcat { _ =>
            Source
              .fromFutureSource(
                client
                  .list[ListResource[Resource]]()
                  .map { resources =>
                    val watch = client
                      .watchAllContinuously[Resource](sinceResourceVersion = Some(resources.resourceVersion))

                    Source(resources)
                      .map(WatchEvent(EventType.MODIFIED, _))
                      .concat(watch)
                  }
              )
              .takeWithin(5.minutes)
          }

        source.via(handler)
      }
      .viaMat(KillSwitches.single)(Keep.right)
      .to(Sink.ignore)
      .run()

  def watchSingle[Resource <: ObjectResource: Format: ResourceDefinition](
      client: KubernetesClient,
      resourceName: String,
      handler: Flow[WatchEvent[Resource], _, _]
  )(implicit ec: ExecutionContext, mat: Materializer): KillSwitch =
    RestartSource
      .onFailuresWithBackoff(2.seconds, 20.seconds, 0.2) { () =>
        val source = Source
          .repeat(NotUsed)
          .flatMapConcat { _ =>
            Source
              .fromFutureSource(
                client.getOption[Resource](resourceName).map {
                  case Some(resource) =>
                    val watch =
                      client.watchContinuously[Resource](resourceName,
                                                         sinceResourceVersion = Some(resource.resourceVersion))
                    Source
                      .single(resource)
                      .map(WatchEvent(EventType.MODIFIED, _))
                      .concat(watch)
                  case None =>
                    throw new RuntimeException(
                      s"Resource $resourceName not found in namespace ${client.namespaceName}!"
                    )
                }
              )
              .takeWithin(5.minutes)
          }

        source.via(handler)
      }
      .viaMat(KillSwitches.single)(Keep.right)
      .to(Sink.ignore)
      .run()
} 
Example 58
Source File: AutocompletionResponse.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index
package api

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

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

case class AutocompletionResponse(
    organization: String,
    repository: String,
    description: String
) 
Example 59
Source File: WFCommand.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package com.packt.publishing.wf.impl

import akka.Done
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import com.lightbend.lagom.scaladsl.playjson.{JsonSerializer, JsonSerializerRegistry}
import play.api.libs.json.{Format, Json}
import scala.collection.immutable.Seq

sealed trait WFCommand[R] extends ReplyType[R]

case class UseWFMessage(city: String, temperature: String) extends WFCommand[Done]

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

case class WF(city: String, temperature: String) extends WFCommand[String]

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

object WFSerializerRegistry extends JsonSerializerRegistry {
  override def serializers: Seq[JsonSerializer[_]] = Seq(
    JsonSerializer[UseWFMessage],
    JsonSerializer[WF],
    JsonSerializer[WFChanged],
    JsonSerializer[WFState]
  )
} 
Example 60
Source File: WFConsumerController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.packt.publishing.wf.consumer.api.models.WeatherForcasting
import play.api.libs.json.{Format, Json}
import scala.concurrent.ExecutionContext

class WFConsumerController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

  def weather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findTopTenWFData().invoke().map {
      (result: Seq[WeatherForcasting]) => Ok(Json.toJson(result))
    }
  }

  def weatherOne(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findOneWFData().invoke().map {
      (result: WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

  def latestWeather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.latestWF().invoke().map {
      (result:WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

} 
Example 61
Source File: WFCommand.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package com.packt.publishing.wf.impl

import akka.Done
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import com.lightbend.lagom.scaladsl.playjson.{JsonSerializer, JsonSerializerRegistry}
import play.api.libs.json.{Format, Json}
import scala.collection.immutable.Seq

sealed trait WFCommand[R] extends ReplyType[R]

case class UseWFMessage(city: String, temperature: String) extends WFCommand[Done]

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

case class WF(city: String, temperature: String) extends WFCommand[String]

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

object WFSerializerRegistry extends JsonSerializerRegistry {
  override def serializers: Seq[JsonSerializer[_]] = Seq(
    JsonSerializer[UseWFMessage],
    JsonSerializer[WF],
    JsonSerializer[WFChanged],
    JsonSerializer[WFState]
  )
} 
Example 62
Source File: WFConsumerController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.packt.publishing.wf.consumer.api.models.WeatherForcasting
import play.api.libs.json.{Format, Json}
import scala.concurrent.ExecutionContext

class WFConsumerController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

  def weather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findTopTenWFData().invoke().map {
      (result: Seq[WeatherForcasting]) => Ok(Json.toJson(result))
    }
  }

  def weatherOne(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findOneWFData().invoke().map {
      (result: WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

  def latestWeather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.latestWF().invoke().map {
      (result:WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

} 
Example 63
Source File: MetricResultsColumnarItem.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.agilelab.dataquality.api.model

import org.squeryl.annotations.Column
import play.api.libs.json.{Format, Json}


case class MetricResultsColumnarItem(
                                      @Column("metric_id")
                                      metricId: Option[String],
                                      @Column("source_date")
                                      date: Option[String],
                                      name: Option[String],
                                      @Column("source_id")
                                      sourceId: Option[String],
                                      @Column("column_names")
                                      columnNames: Option[String],
                                      params: Option[String],
                                      result: Option[String],
                                      @Column("additional_result")
                                      additionalResult: Option[String]
                                    )

object MetricResultsColumnarItem {
  implicit lazy val metricResultsColumnarItemJsonFormat: Format[MetricResultsColumnarItem] = Json.format[MetricResultsColumnarItem]
} 
Example 64
Source File: MetricResultsItem.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.agilelab.dataquality.api.model

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



@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2019-11-19T15:05:19.949+01:00[Europe/Rome]")
case class MetricResultsItem(
                              metricId: Option[String],
                              name: Option[String],
                              sourceId: Option[String],
                              result: Option[String],
                              metricType: Option[String],
                              date: Option[String]
                            )
object MetricResultsItem {
  implicit lazy val metricResultsItemJsonFormat: Format[MetricResultsItem] = Json.format[MetricResultsItem]
} 
Example 65
Source File: MetricResultsFileItem.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.agilelab.dataquality.api.model

import org.squeryl.annotations.Column
import play.api.libs.json.{Format, Json}

case class MetricResultsFileItem(
                                  @Column("metric_id")
                                  metricId: Option[String],
                                  @Column("source_date")
                                  date: Option[String],
                                  name: Option[String],
                                  @Column("source_id")
                                  sourceId: Option[String],
                                  result: Option[String],
                                  @Column("additional_result")
                                  additionalResult: Option[String]
                            )

object MetricResultsFileItem {
  implicit lazy val metricResultsFileItemJsonFormat: Format[MetricResultsFileItem] = Json.format[MetricResultsFileItem]
} 
Example 66
Source File: ChirpTimelineEvent.scala    From lagom-scala-chirper   with Apache License 2.0 5 votes vote down vote up
package sample.chirper.chirp.impl

import com.lightbend.lagom.scaladsl.persistence.{AggregateEvent, AggregateEventShards, AggregateEventTag, AggregateEventTagger}
import play.api.libs.json.{Format, Json}
import sample.chirper.chirp.api.Chirp

sealed trait ChirpTimelineEvent extends AggregateEvent[ChirpTimelineEvent] {
  override def aggregateTag: AggregateEventShards[ChirpTimelineEvent] = ChirpTimelineEvent.Tag
}

object ChirpTimelineEvent {
  val NumShards = 3
  val Tag = AggregateEventTag.sharded[ChirpTimelineEvent](NumShards)
}

case class ChirpAdded(chirp: Chirp) extends ChirpTimelineEvent

object ChirpAdded {
  implicit val format: Format[ChirpAdded] = Json.format[ChirpAdded]
} 
Example 67
Source File: PatchExamples.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.examples.patch

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import skuber._
import skuber.json.format._
import skuber.apps.v1beta1.StatefulSet

import scala.concurrent.Await
import scala.concurrent.duration.Duration.Inf
import play.api.libs.json.{Format, Json}
import skuber.api.patch.JsonMergePatch

object PatchExamples extends App {

  // API patch method.
  // This will change the replica count on the statefulset causing it to scale accordingly.
  case class ReplicaSpec(replicas: Int)
  case class ReplicaPatch(spec: ReplicaSpec) extends JsonMergePatch

  implicit val rsFmt: Format[ReplicaSpec] = Json.format[ReplicaSpec]
  implicit val rpFmt: Format[ReplicaPatch] = Json.format[ReplicaPatch]

  val statefulSetName = "nginx-patch-sts"

  def scaleNginx = {

    val nginxContainer = Container("nginx",image="nginx").exposePort(80)
    val nginxBaseSpec = Pod.Template.Spec().addContainer(nginxContainer)


    val nginxStsLabels=Map("patch-example" -> "statefulset")
    val nginxStsSel=LabelSelector(LabelSelector.IsEqualRequirement("patch-example","statefulset"))
    val nginxStsSpec=nginxBaseSpec.addLabels(nginxStsLabels)
    val nginxStatefulSet= StatefulSet(statefulSetName)
      .withReplicas(4)
      .withServiceName(statefulSetName)
      .withLabelSelector(nginxStsSel)
      .withTemplate(nginxStsSpec)

    // StatefulSet needs a headless service
    val nginxStsService: Service=Service(nginxStatefulSet.spec.get.serviceName.get, nginxStsLabels, 80).isHeadless

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    implicit val dispatcher = system.dispatcher

    val k8s = k8sInit

    println("Creating nginx stateful set")
    val createdStsFut = for {
      svc <- k8s create nginxStsService
      sts <- k8s create nginxStatefulSet
    } yield sts
   
    val stsFut = createdStsFut recoverWith {
      case ex: K8SException if (ex.status.code.contains(409)) => {
        println("It seems the stateful set or service already exists - retrieving latest version")
        k8s get[StatefulSet] nginxStatefulSet.name
      }
    }

    // Wait for stateful set creation before proceeding
    val sts = Await.result(stsFut, Inf)
    println("waiting two minutes to allow Stateful Set creation to complete before patching it")
    Thread.sleep(120000)


    println("Patching stateful set to assign replica count of 1")

    // Create the Patch
    val singleReplicaPatch=ReplicaPatch(ReplicaSpec(1))
    val singleReplicaPatchJson=Json.toJson(singleReplicaPatch)
    val singleReplicaPatchJsonStr=singleReplicaPatchJson.toString

    // Send the Patch to the statefulset on Kubernetes
    val patchedStsFut = k8s.patch[ReplicaPatch, StatefulSet](statefulSetName, singleReplicaPatch)

    val patchedSts = Await.result(patchedStsFut, Inf)
    println(s"Patched statefulset now has a desired replica count of ${patchedSts.spec.get.replicas}")
    println("waiting 5 minutes to allow scaling to be observed before cleaning up")
    Thread.sleep(300000)
    println("will now delete StatefulSet and its service")
    val cleanupRequested= for {
      sts <- k8s.deleteWithOptions[StatefulSet](nginxStatefulSet.name, DeleteOptions(propagationPolicy = Some(DeletePropagation.Foreground)))
      done <- k8s.delete[Service](nginxStsService.name)
    } yield done


    Await.ready(cleanupRequested, Inf)
    println("Finishing up")
    k8s.close
    system.terminate()
  }
  scaleNginx
} 
Example 68
Source File: BytesToWatchEventSource.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.api.watch

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

import scala.concurrent.ExecutionContext


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

import play.api.libs.json.{Format, JsPath, Json}
import skuber.batch.{Job, JobList, JobTemplate, CronJob, CronJobList}


import play.api.libs.functional.syntax._
import skuber._
import skuber.json.format._ // reuse some core formatters

package object format {

  // Job formatters
  implicit val jobConditionFormat: Format[Job.Condition] = (
      (JsPath \ "type").formatMaybeEmptyString() and
      (JsPath \ "status").formatMaybeEmptyString() and
      (JsPath \ "lastProbeTime").formatNullable[Timestamp] and
      (JsPath \ "lastTransitionTime").formatNullable[Timestamp] and
      (JsPath \ "reason").formatNullable[String] and
      (JsPath \ "message").formatNullable[String]
    )(Job.Condition.apply _, unlift(Job.Condition.unapply))

  implicit val jobStatusFormat: Format[Job.Status] = (
      (JsPath \ "conditions").formatMaybeEmptyList[Job.Condition] and
      (JsPath \ "startTime").formatNullable[Timestamp] and
      (JsPath \ "completionTime").formatNullable[Timestamp] and
      (JsPath \ "active").formatNullable[Int] and
      (JsPath \ "succeeded").formatNullable[Int] and
      (JsPath \ "failed").formatNullable[Int]
    )(Job.Status.apply _, unlift(Job.Status.unapply))

  implicit val jobSpecFormat: Format[Job.Spec] = (
      (JsPath \ "parallelism").formatNullable[Int] and
      (JsPath \ "completions").formatNullable[Int] and
      (JsPath \ "activeDeadlineSeconds").formatNullable[Long] and
      (JsPath \ "selector").formatNullableLabelSelector and
      (JsPath \ "manualSelector").formatNullable[Boolean] and
      (JsPath \ "template").formatNullable[Pod.Template.Spec] and
      (JsPath \ "backoffLimit").formatNullable[Int] and
      (JsPath \ "ttlSecondsAfterFinished").formatNullable[Int]
    )(Job.Spec.apply _, unlift(Job.Spec.unapply))

  implicit val jobFormat: Format[Job] = (
      (JsPath \ "kind").formatMaybeEmptyString() and
      (JsPath \ "apiVersion").formatMaybeEmptyString() and
      (JsPath \ "metadata").format[ObjectMeta] and
      (JsPath \ "spec").formatNullable[Job.Spec] and
      (JsPath \ "status").formatNullable[Job.Status]
    )(Job.apply _, unlift(Job.unapply))

  implicit val jobTmplSpecFmt: Format[JobTemplate.Spec] = Json.format[JobTemplate.Spec]

  implicit val cronJobSpecFmt:Format[CronJob.Spec] = Json.format[CronJob.Spec]

  implicit val cronJobStatusFmt: Format[CronJob.Status] = (
      (JsPath \ "lastScheduleTime").formatNullable[Timestamp] and
      (JsPath \ "active").formatMaybeEmptyList[ObjectReference]
  )(CronJob.Status.apply _, unlift(CronJob.Status.unapply))

  implicit val cronJob: Format[CronJob] = (
      (JsPath \ "kind").formatMaybeEmptyString() and
      (JsPath \ "apiVersion").formatMaybeEmptyString() and
      (JsPath \ "metadata").format[ObjectMeta] and
      (JsPath \ "spec").formatNullable[CronJob.Spec] and
      (JsPath \ "status").formatNullable[CronJob.Status]
  )(CronJob.apply _, unlift(CronJob.unapply))

  implicit val jobListFmt: Format[JobList] = ListResourceFormat[Job]
  implicit val cronJobListFmt: Format[CronJobList] = ListResourceFormat[CronJob]

} 
Example 70
Source File: PodDisruptionBudget.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.policy.v1beta1

import skuber.ResourceSpecification.{Names, Scope}
import skuber.{IntOrString, LabelSelector, NonCoreResourceSpecification, ObjectMeta, ObjectResource, ResourceDefinition, Scale, Timestamp}

case class PodDisruptionBudget(override val kind: String = "PodDisruptionBudget",
                               override val apiVersion: String = policyAPIVersion,
                               metadata: ObjectMeta,
                               spec: Option[PodDisruptionBudget.Spec] = None,
                               status: Option[PodDisruptionBudget.Status] = None) extends ObjectResource {

  private lazy val copySpec: PodDisruptionBudget.Spec = this.spec.getOrElse(PodDisruptionBudget.Spec(selector=Some(LabelSelector())))

  def withLabelSelector(sel: LabelSelector): PodDisruptionBudget = {
    this.copy(spec = Some(copySpec.copy(selector = Some(sel))))
  }

  def withMaxUnavailable(value: IntOrString): PodDisruptionBudget = {
    this.copy(spec = Some(copySpec.copy(maxUnavailable = Some(value))))
  }

  def withMinAvailable(value: IntOrString): PodDisruptionBudget = {
    this.copy(spec = Some(copySpec.copy(minAvailable = Some(value))))
  }
}

object PodDisruptionBudget {

  def apply(name: String): PodDisruptionBudget = {
    PodDisruptionBudget(metadata = ObjectMeta(name = name))
  }

  val specification = NonCoreResourceSpecification(
    apiGroup = "policy",
    version = "v1beta1",
    scope = Scope.Namespaced,
    names = Names(
      plural = "poddisruptionbudgets",
      singular = "poddisruptionbudget",
      kind = "PodDisruptionBudget",
      shortNames = List("pdb")
    )
  )
  implicit val stsDef: ResourceDefinition[PodDisruptionBudget] = new ResourceDefinition[PodDisruptionBudget] {
    def spec: NonCoreResourceSpecification = specification
  }
  implicit val stsListDef: ResourceDefinition[PodDisruptionBudgetList] = new ResourceDefinition[PodDisruptionBudgetList] {
    def spec: NonCoreResourceSpecification = specification
  }

  case class Spec(maxUnavailable: Option[IntOrString] = None,
                  minAvailable: Option[IntOrString] = None,
                  selector: Option[LabelSelector] = None)

  case class Status(currentHealthy: Int,
                    desiredHealthy: Int,
                    disruptedPods: Map[String, Timestamp],
                    disruptionsAllowed: Int,
                    expectedPods: Int,
                    observedGeneration: Option[Int])

  import play.api.libs.functional.syntax._
  import play.api.libs.json.{Format, JsPath}
  import skuber.json.format._

  implicit val depStatusFmt: Format[Status] = (
    (JsPath \ "currentHealthy").formatMaybeEmptyInt() and
      (JsPath \ "desiredHealthy").formatMaybeEmptyInt() and
      (JsPath \ "disruptedPods").formatMaybeEmptyMap[Timestamp] and
      (JsPath \ "disruptionsAllowed").formatMaybeEmptyInt() and
      (JsPath \ "expectedPods").formatMaybeEmptyInt() and
      (JsPath \ "observedGeneration").formatNullable[Int]
    ) (Status.apply, unlift(Status.unapply))

  implicit val depSpecFmt: Format[Spec] = (
    (JsPath \ "maxUnavailable").formatNullable[IntOrString] and
      (JsPath \ "minAvailable").formatNullable[IntOrString] and
      (JsPath \ "selector").formatNullableLabelSelector
    ) (Spec.apply, unlift(Spec.unapply))

  implicit lazy val pdbFormat: Format[PodDisruptionBudget] = (
    objFormat and
      (JsPath \ "spec").formatNullable[Spec] and
      (JsPath \ "status").formatNullable[Status]
    )(PodDisruptionBudget.apply, unlift(PodDisruptionBudget.unapply))

  implicit val pdbListFormat: Format[PodDisruptionBudgetList] = ListResourceFormat[PodDisruptionBudget]
} 
Example 71
Source File: PodPreset.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.settings

import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, JsPath}
import skuber.json.format.{objFormat,maybeEmptyFormatMethods,jsPath2LabelSelFormat,envVarFormat,envFromSourceFmt, volMountFormat, volumeFormat}
import skuber.ResourceSpecification.{Names, Scope}
import skuber.{EnvFromSource, EnvVar, LabelSelector, NonCoreResourceSpecification, ObjectMeta, ObjectResource, ResourceDefinition, Volume}



case class PodPreset(
  val kind: String ="PodPreset",
  override val apiVersion: String = "settings.k8s.io/v1alpha1",
  val metadata: ObjectMeta,
  spec: Option[PodPreset.Spec]=None) extends ObjectResource

object PodPreset {

  case class Spec(
    selector: LabelSelector,
    env: List[EnvVar] = Nil,
    envFrom: List[EnvFromSource] = Nil,
    volumes: List[Volume] = Nil,
    volumeMounts: List[Volume.Mount] = Nil
  )

  // Kubernetes resource specification

  val specification = NonCoreResourceSpecification(
    apiGroup ="settings.k8s.io",
    version = "v1alpha1",
    scope = Scope.Namespaced,
    names = Names(
      plural = "podpresets",
      singular = "podpreset",
      kind = "PodPreset",
      shortNames = List()
    )
  )

  implicit val ppDef = new ResourceDefinition[PodPreset] { def spec = specification }
  implicit val pplListDef = new ResourceDefinition[PodPresetList] { def spec = specification }

  // Json formatters
  implicit val podPresetSpecFmt: Format[Spec] = (
    (JsPath \ "selector").formatLabelSelector and
    (JsPath \ "env").formatMaybeEmptyList[EnvVar] and
    (JsPath \ "envFrom").formatMaybeEmptyList[EnvFromSource] and
    (JsPath \ "volumes").formatMaybeEmptyList[Volume] and
    (JsPath \ "volumeMounts").formatMaybeEmptyList[Volume.Mount]
  )(Spec.apply _, unlift(Spec.unapply))

  implicit val podPresetFmt: Format[PodPreset] = (
    objFormat and
    (JsPath \ "spec").formatNullable[Spec]
  )(PodPreset.apply _, unlift(PodPreset.unapply))

} 
Example 72
Source File: Scale.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber

import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, JsPath, Json}
import skuber.json.format.{maybeEmptyFormatMethods,jsPath2LabelSelFormat,objectMetaFormat}


case class Scale(
    val kind: String = "Scale",
    val apiVersion: String,
    val metadata: ObjectMeta,
    spec: Scale.Spec = Scale.Spec(),
    status: Option[Scale.Status] = None) extends ObjectResource
{
  def withSpecReplicas(count: Int) =  this.copy(spec=Scale.Spec(Some(count)))
  def withStatusReplicas(count: Int) = {
    val newStatus = this.status.map(_.copy(replicas = count)).getOrElse(Scale.Status(replicas=count))
    this.copy(status=Some(newStatus))
  }
}
    
object Scale {

  def named(name: String, apiVersion: String=v1) = new Scale(apiVersion=apiVersion,metadata=ObjectMeta(name=name))

  case class Spec(replicas: Option[Int] = None)
  object Spec {
    implicit val scaleSpecFormat: Format[Scale.Spec] = Json.format[Scale.Spec]
  }

  case class Status(
    replicas: Int = 0,
    selector: Option[LabelSelector] = None,
    targetSelector: Option[String] = None
  )

  object Status {
    implicit val scaleStatusFormat: Format[Scale.Status] = (
      (JsPath \ "replicas").formatMaybeEmptyInt() and
      (JsPath \ "selector").formatNullableLabelSelector and
      (JsPath \ "targetSelector").formatNullable[String]
    )(Scale.Status.apply _, unlift(Scale.Status.unapply))
  }

  implicit val scaleFormat: Format[Scale] = Json.format[Scale]

  // Any object resource type [O <: ObjectResource] that supports a Scale subresource must provide an implicit value of
  // SubresourceSpec type to enable the client API method `scale` to be used on such resources
  // Kubernetes supports Scale subresources on ReplicationController/ReplicaSet/Deployment/StatefulSet types
  trait SubresourceSpec[O <: ObjectResource] {
    def apiVersion: String // the API version to be set on any Scale subresource of the specific resource type O
  }
} 
Example 73
Source File: HorizontalPodAutoscaler.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.autoscaling

import play.api.libs.functional.syntax.unlift
import play.api.libs.json.{Format,  Json}
import skuber.ResourceSpecification.{Names, Scope}
import skuber.{NonCoreResourceSpecification, ObjectMeta, ObjectResource, ReplicationController, ResourceDefinition, Timestamp}
import skuber.json.format.objectMetaFormat


case class HorizontalPodAutoscaler(
  	val kind: String ="HorizontalPodAutoscaler",
  	override val apiVersion: String =  "autoscaling/v1",
    val metadata: ObjectMeta,
    spec: HorizontalPodAutoscaler.Spec,
    status: Option[HorizontalPodAutoscaler.Status] = None) 
      extends ObjectResource {

  def withResourceVersion(version: String) = this.copy(metadata = metadata.copy(resourceVersion=version))

  def withMinReplicas(min: Int) = this.copy(spec=this.spec.copy(minReplicas=Some(min)))
  def withMaxReplicas(max: Int) = this.copy(spec=this.spec.copy(maxReplicas=max))
  def withCPUTargetUtilization(cpu: Int) =
    this.copy(spec=this.spec.copy(cpuUtilization=Some(CPUTargetUtilization(cpu))))
}
      
object HorizontalPodAutoscaler {

  val specification=NonCoreResourceSpecification(
    apiGroup = "autoscaling",
    version = "v1",
    scope = Scope.Namespaced,
    names = Names(
      plural = "horizontalpodautoscalers",
      singular = "horizontalpodautoscaler",
      kind = "HorizontalPodAutoscaler",
      shortNames = List("hpa")
    )
  )
  implicit val hpasDef = new ResourceDefinition[HorizontalPodAutoscaler] { def spec=specification }
  implicit val hpasListDef = new ResourceDefinition[HorizontalPodAutoscalerList] { def spec=specification }

  def scale(rc: ReplicationController): HorizontalPodAutoscaler = 
    build(rc.name, rc.metadata.namespace, "ReplicationController")

  def scale(de: skuber.apps.Deployment): HorizontalPodAutoscaler =
    build(de.name, de.metadata.namespace, "Deployment")
   
  def build(name: String, namespace: String, kind: String, apiVersion: String = "v1") : HorizontalPodAutoscaler = {
    val meta = ObjectMeta(name=name,namespace=namespace)
    val scaleTargetRef = CrossVersionObjectReference(
        kind=kind,
        name=name,
        apiVersion=apiVersion)
   HorizontalPodAutoscaler(metadata=meta,spec=Spec(scaleTargetRef=scaleTargetRef))
  }

  case class Spec(
    scaleTargetRef: CrossVersionObjectReference,
    minReplicas: Option[Int] = Some(1),
    maxReplicas: Int = 1,
    cpuUtilization: Option[CPUTargetUtilization] = None
  )
  case class CrossVersionObjectReference(
    apiVersion: String = "autoscaling/v1",
    kind: String = "CrossVersionObjectReference",
    name: String
  )
  case class Status(
    observedGeneration: Option[Long] = None,
    lastScaleTime: Option[Timestamp] = None,
    currentReplicas: Int = 0,
    desiredReplicas: Int = 0,
    currentCPUUtilizationPercentage: Option[Int] = None)

  // HorizontalPodAutoscaler Json formatters
  implicit val cpuTUFmt: Format[CPUTargetUtilization] = Json.format[CPUTargetUtilization]
  implicit val cvObjRefFmt: Format[CrossVersionObjectReference] = Json.format[CrossVersionObjectReference]
  implicit val hpasSpecFmt: Format[HorizontalPodAutoscaler.Spec] = Json.format[HorizontalPodAutoscaler.Spec]
  implicit val hpasStatusFmt: Format[HorizontalPodAutoscaler.Status] = Json.format[HorizontalPodAutoscaler.Status]
  implicit val hpasFmt: Format[HorizontalPodAutoscaler] =  Json.format[HorizontalPodAutoscaler]
} 
Example 74
Source File: RewardApiRoute.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http

import akka.http.scaladsl.server.Route
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.state.Blockchain
import com.wavesplatform.transaction.TxValidationError.GenericError
import play.api.libs.json.{Format, Json}

case class RewardApiRoute(blockchain: Blockchain) extends ApiRoute {
  import RewardApiRoute._

  override lazy val route: Route = pathPrefix("blockchain" / "rewards") {
    rewards ~ rewardsAtHeight()
  }

  def rewards(): Route = (get & pathEndOrSingleSlash) {
    complete(getRewards(blockchain.height))
  }

  def rewardsAtHeight(): Route = (get & path(IntNumber)) { height =>
    complete(getRewards(height))
  }

  def getRewards(height: Int): Either[ValidationError, RewardStatus] =
    for {
      _ <- Either.cond(height <= blockchain.height, (), GenericError(s"Invalid height: $height"))
      activatedAt <- blockchain
        .featureActivationHeight(BlockchainFeatures.BlockReward.id)
        .filter(_ <= height)
        .toRight(GenericError("Block reward feature is not activated yet"))
      reward <- blockchain.blockReward(height).toRight(GenericError(s"No information about rewards at height = $height"))
      amount              = blockchain.wavesAmount(height)
      settings            = blockchain.settings.rewardsSettings
      nextCheck           = settings.nearestTermEnd(activatedAt, height)
      votingIntervalStart = nextCheck - settings.votingInterval + 1
      votingThreshold     = settings.votingInterval / 2 + 1
      votes               = blockchain.blockRewardVotes(height).filter(_ >= 0)
    } yield RewardStatus(
      height,
      amount,
      reward,
      settings.minIncrement,
      settings.term,
      nextCheck,
      votingIntervalStart,
      settings.votingInterval,
      votingThreshold,
      RewardVotes(votes.count(_ > reward), votes.count(_ < reward))
    )
}

object RewardApiRoute {
  final case class RewardStatus(
      height: Int,
      totalWavesAmount: BigInt,
      currentReward: Long,
      minIncrement: Long,
      term: Int,
      nextCheck: Int,
      votingIntervalStart: Int,
      votingInterval: Int,
      votingThreshold: Int,
      votes: RewardVotes
  )

  final case class RewardVotes(increase: Int, decrease: Int)

  implicit val rewardVotesFormat: Format[RewardVotes] = Json.format
  implicit val rewardFormat: Format[RewardStatus]     = Json.format
} 
Example 75
Source File: SetAssetScriptRequest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.transaction.assets.SetAssetScriptTransaction
import play.api.libs.json.{Format, JsNumber, JsObject, Json}

case class SetAssetScriptRequest(
    version: Option[Byte],
    sender: String,
    assetId: String,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long] = None
) {}

object SetAssetScriptRequest {
  implicit val jsonFormat: Format[SetAssetScriptRequest] = Json.format
  implicit class SetAssetScriptRequestExt(val self: SetAssetScriptRequest) extends AnyVal {
    def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(SetAssetScriptTransaction.typeId.toInt))
  }
} 
Example 76
Source File: SponsorFeeRequest.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.transaction.Asset.IssuedAsset
import com.wavesplatform.transaction.assets.SponsorFeeTransaction
import com.wavesplatform.transaction.{AssetIdStringLength, Proofs}
import play.api.libs.json.{Format, Json}

object SponsorFeeRequest {
  implicit val unsignedSponsorRequestFormat: Format[SponsorFeeRequest]     = Json.format
  implicit val signedSponsorRequestFormat: Format[SignedSponsorFeeRequest] = Json.format
}

case class SponsorFeeRequest(
    version: Option[Byte],
    sender: String,
    assetId: String,
    minSponsoredAssetFee: Option[Long],
    fee: Long,
    timestamp: Option[Long] = None
)

case class SignedSponsorFeeRequest(
    version: Option[Byte],
    senderPublicKey: String,
    assetId: String,
    minSponsoredAssetFee: Option[Long],
    fee: Long,
    timestamp: Long,
    proofs: Proofs
) {
  def toTx: Either[ValidationError, SponsorFeeTransaction] =
    for {
      _sender <- PublicKey.fromBase58String(senderPublicKey)
      _asset  <- parseBase58(assetId, "invalid.assetId", AssetIdStringLength).map(IssuedAsset)
      t       <- SponsorFeeTransaction.create(version.getOrElse(1.toByte), _sender, _asset, minSponsoredAssetFee.filterNot(_ == 0), fee, timestamp, proofs)
    } yield t
} 
Example 77
Source File: CreateAliasRequest.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.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.{CreateAliasTransaction, Proofs, TxAmount, TxTimestamp, TxVersion}
import play.api.libs.json.{Format, Json}

case class CreateAliasRequest(
    alias: String,
    version: Option[TxVersion] = None,
    sender: Option[String] = None,
    senderPublicKey: Option[String] = None,
    fee: Option[TxAmount] = None,
    timestamp: Option[TxTimestamp] = None,
    signature: Option[ByteStr] = None,
    proofs: Option[Proofs] = None
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, CreateAliasTransaction] =
    for {
      validProofs <- toProofs(signature, proofs)
      tx          <- CreateAliasTransaction.create(version.getOrElse(1.toByte), sender, alias, fee.getOrElse(0L), timestamp.getOrElse(0L), validProofs)
    } yield tx
}

object CreateAliasRequest {
  implicit val jsonFormat: Format[CreateAliasRequest] = Json.format
} 
Example 78
Source File: DataRequest.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.state.DataEntry
import com.wavesplatform.transaction.{DataTransaction, Proofs}
import play.api.libs.json.{Format, Json}

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

case class DataRequest(
    version: Byte,
    sender: String,
    data: List[DataEntry[_]],
    fee: Long,
    timestamp: Option[Long] = None
)

case class SignedDataRequest(version: Byte, senderPublicKey: String, data: List[DataEntry[_]], fee: Long, timestamp: Long, proofs: Proofs) {
  def toTx: Either[ValidationError, DataTransaction] =
    for {
      _sender <- PublicKey.fromBase58String(senderPublicKey)
      t       <- DataTransaction.create(version, _sender, data, fee, timestamp, proofs)
    } yield t
}

object SignedDataRequest {
  implicit val signedDataRequestReads: Format[SignedDataRequest] = Json.format
} 
Example 79
Source File: IssueRequest.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.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.lang.script.Script
import com.wavesplatform.transaction.assets.IssueTransaction
import com.wavesplatform.transaction.{Proofs, TxVersion}
import play.api.libs.json.{Format, Json}

case class IssueRequest(
    version: Option[Byte],
    sender: Option[String],
    senderPublicKey: Option[String],
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long],
    signature: Option[ByteStr],
    proofs: Option[Proofs]
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, IssueTransaction] = {
    val actualVersion = version.getOrElse(TxVersion.V3)

    for {
      validProofs <- toProofs(signature, proofs)
      validScript <- script match {
        case None         => Right(None)
        case Some(script) => Script.fromBase64String(script).map(Some(_))
      }
      tx <- IssueTransaction.create(
        actualVersion,
        sender,
        name,
        description,
        quantity,
        decimals,
        reissuable,
        validScript,
        fee,
        timestamp.getOrElse(defaultTimestamp),
        validProofs
      )
    } yield tx
  }
}

object IssueRequest {
  implicit val jsonFormat: Format[IssueRequest] = Json.format
} 
Example 80
Source File: SignedUpdateAssetInfoRequest.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.PublicKey
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves}
import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction
import com.wavesplatform.transaction.{AssetIdStringLength, Proofs, TxAmount, TxTimestamp, TxVersion}
import play.api.libs.json.{Format, Json}

case class SignedUpdateAssetInfoRequest(
    version: TxVersion,
    chainId: Byte,
    senderPublicKey: String,
    assetId: String,
    name: String,
    description: String,
    timestamp: TxTimestamp,
    fee: TxAmount,
    feeAssetId: Option[String],
    proofs: Proofs
) {

  def toTx: Either[ValidationError, UpdateAssetInfoTransaction] =
    for {
      _sender  <- PublicKey.fromBase58String(senderPublicKey)
      _assetId <- parseBase58(assetId, "invalid.assetId", AssetIdStringLength)
      _feeAssetId <- feeAssetId
        .traverse(parseBase58(_, "invalid.assetId", AssetIdStringLength).map(IssuedAsset))
        .map(_ getOrElse Waves)
      tx <- UpdateAssetInfoTransaction
        .create(version, _sender, _assetId, name, description, timestamp, fee, _feeAssetId, proofs, chainId)
    } yield tx

}

object SignedUpdateAssetInfoRequest {
  implicit val format: Format[SignedUpdateAssetInfoRequest] = Json.format
} 
Example 81
Source File: LeaseRequest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.{AddressOrAlias, PublicKey}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.lease.LeaseTransaction
import play.api.libs.json.{Format, Json}

case class LeaseRequest(
    version: Option[Byte],
    sender: Option[String],
    senderPublicKey: Option[String],
    recipient: String,
    amount: Long,
    fee: Long,
    timestamp: Option[Long],
    signature: Option[ByteStr],
    proofs: Option[Proofs]
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, LeaseTransaction] =
    for {
      validRecipient <- AddressOrAlias.fromString(recipient)
      validProofs    <- toProofs(signature, proofs)
      tx <- LeaseTransaction.create(
        version.getOrElse(1.toByte),
        sender,
        validRecipient,
        amount,
        fee,
        timestamp.getOrElse(0L),
        validProofs
      )
    } yield tx
}

object LeaseRequest {
  implicit val jsonFormat: Format[LeaseRequest] = Json.format
} 
Example 82
Source File: ReissueRequest.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.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Asset.IssuedAsset
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.assets.ReissueTransaction
import play.api.libs.json.{Format, Json}

case class ReissueRequest(
    version: Option[Byte],
    sender: Option[String],
    senderPublicKey: Option[String],
    assetId: IssuedAsset,
    quantity: Long,
    reissuable: Boolean,
    fee: Long,
    timestamp: Option[Long],
    signature: Option[ByteStr],
    proofs: Option[Proofs]
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, ReissueTransaction] =
    for {
      validProofs <- toProofs(signature, proofs)
      tx <- ReissueTransaction.create(
        version.getOrElse(defaultVersion),
        sender,
        assetId,
        quantity,
        reissuable,
        fee,
        timestamp.getOrElse(defaultTimestamp),
        validProofs
      )
    } yield tx
}

object ReissueRequest {
  implicit val jsonFormat: Format[ReissueRequest] = Json.format
} 
Example 83
Source File: ExchangeRequest.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.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order}
import com.wavesplatform.transaction.{Proofs, TxAmount, TxTimestamp, TxVersion}
import play.api.libs.json.{Format, Json}

case class ExchangeRequest(
    order1: Order,
    order2: Order,
    amount: Long,
    price: Long,
    buyMatcherFee: Long,
    sellMatcherFee: Long,
    version: Option[TxVersion] = None,
    sender: Option[String] = None,
    senderPublicKey: Option[String] = None,
    fee: Option[TxAmount] = None,
    timestamp: Option[TxTimestamp] = None,
    signature: Option[ByteStr] = None,
    proofs: Option[Proofs] = None
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, ExchangeTransaction] =
    for {
      validProofs <- toProofs(signature, proofs)
      tx <- ExchangeTransaction.create(
        version.getOrElse(1.toByte),
        order1,
        order2,
        amount,
        price,
        buyMatcherFee,
        sellMatcherFee,
        fee.getOrElse(0L),
        timestamp.getOrElse(0L),
        validProofs
      )
    } yield tx
}

object ExchangeRequest {
  implicit val jsonFormat: Format[ExchangeRequest] = Json.format
} 
Example 84
Source File: PrivateKey.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.account

import com.wavesplatform.common.state.ByteStr
import play.api.libs.json.{Format, Writes}
import supertagged._
import com.wavesplatform.crypto.KeyLength

object PrivateKey extends TaggedType[ByteStr] {
  def apply(privateKey: ByteStr): PrivateKey = {
    require(privateKey.arr.length == KeyLength, s"invalid public key length: ${privateKey.arr.length}")
    privateKey @@ PrivateKey
  }

  def apply(privateKey: Array[Byte]): PrivateKey =
    apply(ByteStr(privateKey))

  def unapply(arg: Array[Byte]): Option[PrivateKey] =
    Some(apply(arg))

  implicit lazy val jsonFormat: Format[PrivateKey] = Format[PrivateKey](
    com.wavesplatform.utils.byteStrFormat.map(this.apply),
    Writes(pk => com.wavesplatform.utils.byteStrFormat.writes(pk))
  )
} 
Example 85
Source File: KeyPair.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.account

import java.util

import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.Base58
import com.wavesplatform.transaction.TxValidationError.GenericError
import com.wavesplatform.{crypto, utils}
import play.api.libs.json.{Format, Json, Writes}

import scala.util.{Failure, Success}

final class KeyPair(val seed: Array[Byte]) {
  lazy val (PrivateKey(privateKey), PublicKey(publicKey)) = crypto.createKeyPair(seed)

  override def equals(obj: Any): Boolean = obj match {
    case kp: KeyPair => util.Arrays.equals(kp.seed, seed)
    case _           => false
  }

  private lazy val hc          = util.Arrays.hashCode(seed)
  override def hashCode(): Int = hc
}

object KeyPair {
  def apply(seed: ByteStr): KeyPair     = new KeyPair(seed.arr)
  def apply(seed: Array[Byte]): KeyPair = new KeyPair(seed)

  def fromSeed(base58: String): Either[GenericError, KeyPair] = Base58.tryDecodeWithLimit(base58) match {
    case Success(x) => Right(KeyPair(ByteStr(x)))
    case Failure(e) => Left(GenericError(s"Unable to get a private key from the seed '$base58': ${e.getMessage}"))
  }

  implicit class KeyPairImplicitOps(private val kp: KeyPair) extends AnyVal {
    def toAddress: Address                = kp.publicKey.toAddress
    def toAddress(chainId: Byte): Address = kp.publicKey.toAddress(chainId)
  }

  implicit val jsonFormat: Format[KeyPair] = Format(
    utils.byteStrFormat.map(KeyPair(_)),
    Writes(v => Json.obj("seed" -> Base58.encode(v.seed), "publicKey" -> v.publicKey, "privateKey" -> v.privateKey))
  )
} 
Example 86
Source File: PublicKey.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.account

import com.google.common.collect.Interners
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.Base58
import com.wavesplatform.crypto._
import com.wavesplatform.transaction.TxValidationError.InvalidAddress
import com.wavesplatform.utils.base58Length
import play.api.libs.json.{Format, Writes}
import supertagged._

object PublicKey extends TaggedType[ByteStr] {
  private[this] val interner = Interners.newWeakInterner[PublicKey]()

  val KeyStringLength: Int = base58Length(KeyLength)

  def apply(publicKey: ByteStr): PublicKey = {
    require(publicKey.arr.length == KeyLength, s"invalid public key length: ${publicKey.arr.length}")
    interner.intern(publicKey @@ this)
  }

  def apply(publicKey: Array[Byte]): PublicKey =
    apply(ByteStr(publicKey))

  def fromBase58String(base58: String): Either[InvalidAddress, PublicKey] =
    (for {
      _     <- Either.cond(base58.length <= KeyStringLength, (), "Bad public key string length")
      bytes <- Base58.tryDecodeWithLimit(base58).toEither.left.map(ex => s"Unable to decode base58: ${ex.getMessage}")
    } yield PublicKey(bytes)).left.map(err => InvalidAddress(s"Invalid sender: $err"))

  def unapply(arg: Array[Byte]): Option[PublicKey] =
    Some(apply(arg))

  implicit class PublicKeyImplicitOps(private val pk: PublicKey) extends AnyVal {
    def toAddress: Address                = Address.fromPublicKey(pk)
    def toAddress(chainId: Byte): Address = Address.fromPublicKey(pk, chainId)
  }

  implicit lazy val jsonFormat: Format[PublicKey] = Format[PublicKey](
    com.wavesplatform.utils.byteStrFormat.map(this.apply),
    Writes(pk => com.wavesplatform.utils.byteStrFormat.writes(pk))
  )
} 
Example 87
Source File: SignedLeaseV2Request.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.{AddressOrAlias, PublicKey}
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.lease.LeaseTransaction
import play.api.libs.json.{Format, Json}

case class SignedLeaseV2Request(senderPublicKey: String, amount: Long, fee: Long, recipient: String, timestamp: Long, proofs: List[String]) {
  def toTx: Either[ValidationError, LeaseTransaction] =
    for {
      _sender     <- PublicKey.fromBase58String(senderPublicKey)
      _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize))
      _proofs     <- Proofs.create(_proofBytes)
      _recipient  <- AddressOrAlias.fromString(recipient)
      _t          <- LeaseTransaction.create(2.toByte, _sender, _recipient, amount, fee, timestamp, _proofs)
    } yield _t
}

object SignedLeaseV2Request {
  implicit val broadcastLeaseRequestReadsFormat: Format[SignedLeaseV2Request] = Json.format
} 
Example 88
Source File: SignedLeaseV1Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.{AddressOrAlias, PublicKey}
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.lease.LeaseTransaction
import play.api.libs.json.{Format, Json}

case class SignedLeaseV1Request(
    senderPublicKey: String,
    amount: Long,
    fee: Long,
    recipient: String,
    timestamp: Long,
    signature: String
) {
  def toTx: Either[ValidationError, LeaseTransaction] =
    for {
      _sender    <- PublicKey.fromBase58String(senderPublicKey)
      _signature <- parseBase58(signature, "invalid.signature", SignatureStringLength)
      _recipient <- AddressOrAlias.fromString(recipient)
      _t         <- LeaseTransaction.create(1.toByte, _sender, _recipient, amount, fee, timestamp, Proofs(_signature))
    } yield _t
}

object SignedLeaseV1Request {
  implicit val broadcastLeaseRequestReadsFormat: Format[SignedLeaseV1Request] = Json.format
} 
Example 89
Source File: TransferV1Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

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

case class TransferV1Request(
    assetId: Option[String],
    feeAssetId: Option[String],
    amount: Long,
    fee: Long,
    sender: String,
    attachment: Option[String],
    recipient: String,
    timestamp: Option[Long] = None
)

object TransferV1Request {
  implicit val format: Format[TransferV1Request] = Json.format
} 
Example 90
Source File: SignedCreateAliasV2Request.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.PublicKey
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.{CreateAliasTransaction, Proofs, Transaction}
import play.api.libs.json.{Format, Json}

case class SignedCreateAliasV2Request(
    senderPublicKey: String,
    fee: Long,
    alias: String,
    timestamp: Long,
    proofs: List[String]
) {
  def toTx: Either[ValidationError, CreateAliasTransaction] =
    for {
      _sender     <- PublicKey.fromBase58String(senderPublicKey)
      _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize))
      _proofs     <- Proofs.create(_proofBytes)
      _t          <- CreateAliasTransaction.create(Transaction.V1, _sender, alias, fee, timestamp, _proofs)
    } yield _t
}

object SignedCreateAliasV2Request {
  implicit val broadcastAliasV2RequestReadsFormat: Format[SignedCreateAliasV2Request] = Json.format
} 
Example 91
Source File: TransferV2Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

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

case class TransferV2Request(
    assetId: Option[String],
    amount: Long,
    feeAssetId: Option[String],
    fee: Long,
    sender: String,
    attachment: Option[String],
    recipient: String,
    timestamp: Option[Long] = None
)

object TransferV2Request {
  implicit val format: Format[TransferV2Request] = Json.format
} 
Example 92
Source File: SignedCreateAliasV1Request.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.transaction.{CreateAliasTransaction, Proofs}
import play.api.libs.json.{Format, Json}

case class SignedCreateAliasV1Request(
    senderPublicKey: String,
    fee: Long,
    alias: String,
    timestamp: Long,
    signature: String
) {
  def toTx: Either[ValidationError, CreateAliasTransaction] =
    for {
      _sender    <- PublicKey.fromBase58String(senderPublicKey)
      _signature <- parseBase58(signature, "invalid.signature", SignatureStringLength)
      _t         <- CreateAliasTransaction.create(1: Byte, _sender, alias, fee, timestamp, Proofs(_signature))
    } yield _t
}

object SignedCreateAliasV1Request {
  implicit val jsonFormat: Format[SignedCreateAliasV1Request] = Json.format
} 
Example 93
Source File: SignedExchangeRequest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.Proofs
import com.wavesplatform.transaction.assets.exchange._
import play.api.libs.json.{Format, Json}

object SignedExchangeRequest {
  implicit val orderFormat: Format[Order]                                 = com.wavesplatform.transaction.assets.exchange.OrderJson.orderFormat
  implicit val signedExchangeRequestFormat: Format[SignedExchangeRequest] = Json.format
}

case class SignedExchangeRequest(
    senderPublicKey: String,
    order1: Order,
    order2: Order,
    amount: Long,
    price: Long,
    fee: Long,
    buyMatcherFee: Long,
    sellMatcherFee: Long,
    timestamp: Long,
    signature: String
) {
  def toTx: Either[ValidationError, ExchangeTransaction] =
    for {
      _signature <- parseBase58(signature, "invalid.signature", SignatureStringLength)
      _t         <- ExchangeTransaction.create(1.toByte, order1, order2, amount, price, buyMatcherFee, sellMatcherFee, fee, timestamp, Proofs(_signature))
    } yield _t

} 
Example 94
Source File: SignedReissueV1Request.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.transaction.Proofs
import com.wavesplatform.transaction.assets.ReissueTransaction
import play.api.libs.json.{Format, Json}

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

case class SignedReissueV1Request(
    senderPublicKey: String,
    assetId: String,
    quantity: Long,
    reissuable: Boolean,
    fee: Long,
    timestamp: Long,
    signature: String
) {
  def toTx: Either[ValidationError, ReissueTransaction] =
    for {
      _sender    <- PublicKey.fromBase58String(senderPublicKey)
      _signature <- parseBase58(signature, "invalid.signature", SignatureStringLength)
      _assetId   <- parseBase58ToIssuedAsset(assetId)
      _t         <- ReissueTransaction.create(1.toByte, _sender, _assetId, quantity, reissuable, fee, timestamp, Proofs(_signature))
    } yield _t
} 
Example 95
Source File: SignedIssueV1Request.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.transaction.assets.IssueTransaction
import com.wavesplatform.transaction.{Proofs, TxVersion}
import play.api.libs.json.{Format, Json}

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

case class SignedIssueV1Request(
    senderPublicKey: String,
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    fee: Long,
    timestamp: Long,
    signature: String
) {
  def toTx: Either[ValidationError, IssueTransaction] =
    for {
      _sender    <- PublicKey.fromBase58String(senderPublicKey)
      _signature <- parseBase58(signature, "invalid signature", SignatureStringLength)
      _t <- IssueTransaction.create(
        TxVersion.V1,
        _sender,
        name,
        description,
        quantity,
        decimals,
        reissuable,
        script = None,
        fee,
        timestamp,
        Proofs(_signature)
      )
    } yield _t
} 
Example 96
Source File: IssueV2Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.transaction.assets.IssueTransaction
import play.api.libs.json.{Format, JsNumber, JsObject, Json}

case class IssueV2Request(
    sender: String,
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long]
)

object IssueV2Request {
  implicit val jsonFormat: Format[IssueV2Request] = Json.format
  implicit class SmartIssueRequestExt(val self: IssueV2Request) extends AnyVal {
    def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(IssueTransaction.typeId.toInt))
  }
} 
Example 97
Source File: IssueV1Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

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

case class IssueV1Request(
    sender: String,
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    fee: Long,
    timestamp: Option[Long] = None
)

object IssueV1Request {
  implicit val issueFormat: Format[IssueV1Request] = Json.format
} 
Example 98
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 99
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpplayjson

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import play.api.libs.json.{ Format, JsValue, Json }

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final object Foo {
    implicit val fooFormat: Format[Foo] = Json.format[Foo]
  }
  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import Directives._
    import PlayJsonSupport._

    implicit val prettyPrint: JsValue => String = Json.prettyPrint

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 100
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 101
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 102
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 103
Source File: JsonFormatsTest.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.collection.Enum
import org.coursera.common.collection.EnumSymbol
import org.coursera.common.stringkey.StringKey
import org.coursera.common.stringkey.StringKeyFormat
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.Duration
import org.joda.time.Instant
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.Format
import play.api.libs.json.JsNumber
import play.api.libs.json.JsString
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json

class JsonFormatsTest extends AssertionsForJUnit {

  import JsonFormatsTest._

  @Test
  def stringKey(): Unit = {
    val id = TestId(2, "test")
    val idString = StringKey.stringify(id)
    assert(JsString(idString) === Json.toJson(id))
    assert(JsSuccess(id) === Json.fromJson[TestId](JsString(idString)))
    assert(JsString(s"invalid stuff $idString").validate[TestId].isError)
  }

  @Test
  def enums(): Unit = {
    assertResult(Color.Amber)(JsString("Amber").as[Color])

    assertResult(JsString("Green"))(Json.toJson(Color.Green))
  }

  @Test
  def instant(): Unit = {
    import JsonFormats.Implicits.instantFormat
    val testInstant = new Instant(137)
    assertResult(JsNumber(137))(Json.toJson(testInstant))
    assertResult(Some(testInstant))(Json.parse("137").asOpt[Instant])
  }


  @Test
  def duration(): Unit = {
    import JsonFormats.Implicits.durationFormat
    val testDuration = Duration.millis(137L)
    assertResult(JsNumber(137))(Json.toJson(testDuration))
    assertResult(Some(testDuration))(Json.parse("137").asOpt[Duration])
  }


  @Test
  def dateTime(): Unit = {
    import JsonFormats.Implicits.dateTimeFormat
    val testDatetime = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC)
    assertResult(JsNumber(1262304000000L))(Json.toJson(testDatetime))
    assertResult(Some(testDatetime))(Json.parse("1262304000000").asOpt[DateTime].map(_.withZone(DateTimeZone.UTC)))
  }
}

object JsonFormatsTest {

  case class TestId(part1: Int, part2: String)

  object TestId {
    implicit val stringKeyFormat: StringKeyFormat[TestId] =
      StringKeyFormat.caseClassFormat((apply _).tupled, unapply)
    implicit val format: Format[TestId] = JsonFormats.stringKeyFormat[TestId]
  }

  sealed trait Color extends EnumSymbol

  object Color extends Enum[Color] {
    case object Red extends Color
    case object Amber extends Color
    case object Green extends Color

    implicit val format: Format[Color] = JsonFormats.enumFormat(Color)
  }

} 
Example 104
Source File: package.scala    From akka-cluster-manager   with MIT License 5 votes vote down vote up
package io.orkestra.cluster

import akka.actor.ActorRef
import akka.http.scaladsl.model.{StatusCodes, StatusCode}
import play.api.libs.json.{JsString, Format, Json, JsValue}

package object protocol {

  case class Register(member: ActorRef, role: String)
  case class RegisterInternal(member: ActorRef, role: String)

  sealed trait Response {
    def asJson: JsValue
    def httpStatusCode: StatusCode
  }

  object Response {

    trait Success extends Response {
      override val httpStatusCode: StatusCode = StatusCodes.OK
    }

    object Success {

      case class Router(name: String, routees: List[String]) extends Success {
        override val asJson = Json.toJson(this)
      }
      object Router {
        implicit val fmt: Format[Router] = Json.format[Router]
      }

      case class Routers(routers: Iterable[JsValue]) extends Success {
        override val asJson = Json.toJson(routers)
      }

      case class RouteeDeleted(role: String, path: String) extends Success {
        override val asJson = JsString(s"routee: $path with role: $role successfully deleted")
      }

    }

    trait Failure extends Response

    object Failure {
      case class RouterNotFound(role: String) extends Failure {
        override val httpStatusCode: StatusCode = StatusCodes.NotFound
        override val asJson: JsValue = Json.obj("error" -> s"router with role: $role not found")
      }
    }
  }

} 
Example 105
Source File: GlobalScriptListResult.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package controllers.dto.script

import controllers.dto.meta.Metadata
import domains.script.{GlobalScript, GlobalScriptInstances, ScriptInstances}
import play.api.libs.json.{Format, Json, Writes}

case class GlobalScriptListResult(results: List[GlobalScript], metadata: Metadata)

object GlobalScriptListResult {
  implicit val format = {
    implicit val cF: Format[GlobalScript] = GlobalScriptInstances.format
    Json.format[GlobalScriptListResult]
  }

  implicit val partialFormat = {
    val write = Writes[GlobalScript] { gs =>
      Json.obj("label" -> gs.name, "value" -> gs.id)
    }
    implicit val sF                       = ScriptInstances.reads
    val reads                             = Json.reads[GlobalScript]
    implicit val cF: Format[GlobalScript] = Format(reads, write)
    Json.format[GlobalScriptListResult]
  }
} 
Example 106
Source File: UserInstances.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package domains.user

import domains.{AuthorizedPatterns, IsAllowed, Key}
import domains.auth.AuthInfo
import play.api.libs.json._

object UserNoPasswordInstances {
  import play.api.libs.json.{Format, Json}

  private val writes = UserInstances.writes.transform { o: JsObject =>
    o - "password"
  }

  implicit val format: Format[User] = Format(UserInstances.reads, writes)
}

object UserType {
  val Otoroshi = "Otoroshi"
  val Oauth    = "OAuth"
  val Izanami  = "Izanami"
}

object UserInstances {
  import play.api.libs.json._
  import play.api.libs.json.Reads.{email, pattern}

  private[user] val reads: Reads[User] = {
    import domains.AuthorizedPatterns._
    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    val commonReads = (
      (__ \ "id").read[String] and
      (__ \ "name").read[String] and
      (__ \ "email").read[String] and
      (__ \ "admin").read[Boolean] and
      (__ \ "authorizedPatterns").read[AuthorizedPatterns].orElse((__ \ "authorizedPattern").read[AuthorizedPatterns])
    )

    val readOtoroshiUser = commonReads(OtoroshiUser.apply _)
    val readOauthUser    = commonReads(OauthUser.apply _)

    val readIzanamiUser = (
      (__ \ "id").read[String] and
      (__ \ "name").read[String] and
      (__ \ "email").read[String] and
      (__ \ "password").readNullable[String] and
      (__ \ "admin").read[Boolean] and
      (__ \ "authorizedPatterns").read[AuthorizedPatterns].orElse((__ \ "authorizedPattern").read[AuthorizedPatterns])
    )(IzanamiUser.apply _)

    (__ \ "type").readNullable[String].flatMap {
      case Some(UserType.Otoroshi) => readOtoroshiUser.asInstanceOf[Reads[User]]
      case Some(UserType.Oauth)    => readOauthUser.asInstanceOf[Reads[User]]
      case Some(UserType.Izanami)  => readIzanamiUser.asInstanceOf[Reads[User]]
      case _                       => readIzanamiUser.asInstanceOf[Reads[User]]
    }
  }

  private[user] val writes: OWrites[User] = {
    import domains.AuthorizedPatterns._
    val writeOtoroshiUser = Json.writes[OtoroshiUser]
    val writeIzanamiUser  = Json.writes[IzanamiUser]
    val writeOauthUser    = Json.writes[OauthUser]
    OWrites[User] {
      case u: OtoroshiUser => writeOtoroshiUser.writes(u) ++ Json.obj("type" -> UserType.Otoroshi)
      case u: IzanamiUser  => writeIzanamiUser.writes(u) ++ Json.obj("type"  -> UserType.Izanami)
      case u: OauthUser    => writeOauthUser.writes(u) ++ Json.obj("type"    -> UserType.Oauth)
    }
  }

  implicit val format = Format[User](reads, writes)

}