play.api.libs.json.Writes Scala Examples
The following examples show how to use play.api.libs.json.Writes.
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: DnsChangeNotices.scala From vinyldns with Apache License 2.0 | 5 votes |
package models import com.typesafe.config.Config import models.DnsChangeNoticeType.DnsChangeNoticeType import models.DnsChangeStatus.DnsChangeStatus import play.api.libs.json.{JsValue, Json, Writes} import play.api.ConfigLoader import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.EnumerationReader._ import scala.collection.JavaConverters._ case class DnsChangeNotices(notices: JsValue) object DnsChangeNotices { implicit val dnsChangeNoticeWrites: Writes[DnsChangeNotice] = Json.writes[DnsChangeNotice] implicit val configLoader: ConfigLoader[DnsChangeNotices] = new ConfigLoader[DnsChangeNotices] { def load(config: Config, path: String): DnsChangeNotices = { val notices = config .getConfigList(path) .asScala .map(formatDnsChangeNotice) DnsChangeNotices(Json.toJson(notices)) } } def formatDnsChangeNotice(config: Config): DnsChangeNotice = { val status = config.as[DnsChangeStatus]("status") val alertType = config.as[DnsChangeNoticeType]("alertType") val text = config.getString("text") val hrefText = config.getOrElse[String]("hrefText", "") val href = config.getOrElse[String]("href", "") DnsChangeNotice(status, alertType, text, hrefText, href) } } case class DnsChangeNotice( status: DnsChangeStatus, alertType: DnsChangeNoticeType, text: String, hrefText: String, href: String ) object DnsChangeStatus extends Enumeration { type DnsChangeStatus = Value val Cancelled, Complete, Failed, PartialFailure, PendingProcessing, PendingReview, Rejected, Scheduled = Value } object DnsChangeNoticeType extends Enumeration { type DnsChangeNoticeType = Value val info, success, warning, danger = Value }
Example 2
Source File: ApiPartner.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import gospeak.core.domain.Partner import gospeak.core.domain.utils.{BasicCtx, Constants} import gospeak.web.api.domain.utils.ApiSocial import play.api.libs.json.{Json, Writes} object ApiPartner { // embedded data in other models, should be public final case class Embed(slug: String, name: String, logo: String, description: Option[String], social: ApiSocial) object Embed { implicit val writes: Writes[Embed] = Json.writes[Embed] } def embed(p: Partner)(implicit ctx: BasicCtx): Embed = new Embed( slug = p.slug.value, name = p.name.value, logo = p.logo.value, description = p.description.map(_.value), social = ApiSocial.from(p.social)) val unknown = new Embed( slug = "unknown", name = "Unknown", logo = Constants.Placeholders.unknownPartner, description = None, social = ApiSocial(None, None, None, None, None, None, None, None, None, None)) }
Example 3
Source File: ApiExternalCfp.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import java.time.LocalDateTime import gospeak.core.domain.ExternalCfp import gospeak.core.domain.utils.BasicCtx import play.api.libs.json.{Json, Writes} object ApiExternalCfp { // data to display publicly final case class Published(id: String, url: String, name: String, description: String, logo: Option[String], begin: Option[LocalDateTime], close: Option[LocalDateTime], eventUrl: Option[String], eventStart: Option[LocalDateTime], eventFinish: Option[LocalDateTime], eventLocation: Option[String], eventTwitterAccount: Option[String], eventTwitterHashtag: Option[String], tags: Seq[String]) object Published { implicit val writes: Writes[Published] = Json.writes[Published] } def published(cfp: ExternalCfp.Full)(implicit ctx: BasicCtx): Published = new Published( id = cfp.id.value, url = cfp.url.value, name = cfp.event.name.value, description = cfp.description.value, logo = cfp.event.logo.map(_.url.value), begin = cfp.begin, close = cfp.close, eventUrl = cfp.event.url.map(_.value), eventStart = cfp.event.start, eventFinish = cfp.event.finish, eventLocation = cfp.event.location.map(_.value), eventTwitterAccount = cfp.event.twitterAccount.map(_.url.value), eventTwitterHashtag = cfp.event.twitterHashtag.map(_.url), tags = cfp.event.tags.map(_.value)) }
Example 4
Source File: ApiCfp.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import java.time.LocalDateTime import gospeak.core.domain.utils.{BasicCtx, OrgaCtx} import gospeak.core.domain.{Cfp, CommonCfp, Group, User} import gospeak.web.api.domain.utils.{ApiInfo, ApiPlace} import play.api.libs.json.{Json, Writes} object ApiCfp { // data to display for orgas (everything) final case class Orga(slug: String, name: String, begin: Option[LocalDateTime], close: Option[LocalDateTime], description: String, tags: Seq[String], info: ApiInfo) object Orga { implicit val writes: Writes[Orga] = Json.writes[Orga] } def orga(cfp: Cfp, users: Seq[User])(implicit ctx: OrgaCtx): Orga = new Orga( slug = cfp.slug.value, name = cfp.name.value, begin = cfp.begin, close = cfp.close, description = cfp.description.value, tags = cfp.tags.map(_.value), info = ApiInfo.from(cfp.info, users)) // data to display publicly final case class Published(kind: String, ref: String, name: String, logo: Option[String], url: Option[String], begin: Option[LocalDateTime], close: Option[LocalDateTime], location: Option[ApiPlace], description: String, eventStart: Option[LocalDateTime], eventFinish: Option[LocalDateTime], eventUrl: Option[String], eventTickets: Option[String], eventVideos: Option[String], twitterAccount: Option[String], twitterHashtag: Option[String], tags: Seq[String], group: Option[ApiGroup.Embed]) object Published { implicit val writes: Writes[Published] = Json.writes[Published] } def published(cfp: CommonCfp, groups: Seq[Group])(implicit ctx: BasicCtx): Published = new Published( kind = cfp.fold(_ => "external")(_ => "internal"), ref = cfp.fold(_.id.value)(_.slug.value), name = cfp.name, logo = cfp.logo.map(_.value), url = cfp.external.map(_.url.value), begin = cfp.begin, close = cfp.close, location = cfp.location.map(ApiPlace.from), description = cfp.description.value, eventStart = cfp.external.flatMap(_.event.start), eventFinish = cfp.external.flatMap(_.event.finish), tags = cfp.tags.map(_.value), eventUrl = cfp.external.flatMap(_.event.url).map(_.value), eventTickets = cfp.external.flatMap(_.event.tickets).map(_.value), eventVideos = cfp.external.flatMap(_.event.videos).map(_.value), twitterAccount = cfp.external.flatMap(_.event.twitterAccount).map(_.url.value), twitterHashtag = cfp.external.flatMap(_.event.twitterHashtag).map(_.value), group = cfp.internal.flatMap(i => groups.find(_.id == i.group.id)).map(ApiGroup.embed)) // embedded data in other models, should be public final case class Embed(slug: String, name: String, begin: Option[LocalDateTime], close: Option[LocalDateTime]) object Embed { implicit val writes: Writes[Embed] = Json.writes[Embed] } def embed(cfp: Cfp)(implicit ctx: BasicCtx): Embed = new Embed( slug = cfp.slug.value, name = cfp.name.value, begin = cfp.begin, close = cfp.close) }
Example 5
Source File: ApiUser.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import gospeak.core.domain.User import gospeak.core.domain.utils.{BasicCtx, Constants} import gospeak.libs.scala.domain.{EmailAddress, Secret} import gospeak.web.api.domain.utils.ApiSocial import gospeak.web.api.domain.utils.JsonFormats._ import gospeak.web.utils.GsForms import play.api.libs.json.{Json, Reads, Writes} object ApiUser { // data to display publicly final case class Published(slug: String, firstName: String, lastName: String, avatar: String, bio: Option[String], website: Option[String], social: ApiSocial) object Published { implicit val writes: Writes[Published] = Json.writes[Published] } def published(user: User.Full)(implicit ctx: BasicCtx): Published = new Published( slug = user.slug.value, firstName = user.firstName, lastName = user.lastName, avatar = user.avatar.url.value, bio = user.bio.map(_.value), website = user.website.map(_.value), social = ApiSocial.from(user.social)) // embedded data in other models, should be public final case class Embed(slug: String, firstName: String, lastName: String, avatar: String, bio: Option[String], website: Option[String], social: ApiSocial) object Embed { implicit val writes: Writes[Embed] = Json.writes[Embed] } def embed(id: User.Id, users: Seq[User])(implicit ctx: BasicCtx): Embed = users.find(_.id == id).map(embed).getOrElse(unknown(id)) def embed(user: User)(implicit ctx: BasicCtx): Embed = new Embed( slug = user.slug.value, firstName = user.firstName, lastName = user.lastName, avatar = user.avatar.url.value, bio = user.bio.map(_.value), website = user.website.map(_.value), social = ApiSocial.from(user.social)) def unknown(id: User.Id)(implicit ctx: BasicCtx): Embed = new Embed( slug = "unknown", firstName = "Unknown", lastName = "User", avatar = Constants.Placeholders.unknownUser, bio = None, website = None, social = ApiSocial(None, None, None, None, None, None, None, None, None, None)) final case class SignupPayload(firstName: String, lastName: String, username: User.Slug, email: EmailAddress, password: Secret, rememberMe: Option[Boolean]) { def asData: GsForms.SignupData = GsForms.SignupData(username, firstName, lastName, email, password, rememberMe.getOrElse(false)) } object SignupPayload { implicit val reads: Reads[SignupPayload] = Json.reads[SignupPayload] } final case class LoginPayload(email: EmailAddress, password: Secret, rememberMe: Option[Boolean]) { def asData: GsForms.LoginData = GsForms.LoginData(email, password, rememberMe.getOrElse(false)) } object LoginPayload { implicit val reads: Reads[LoginPayload] = Json.reads[LoginPayload] } }
Example 6
Source File: ApiGroup.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import java.time.Instant import gospeak.core.domain.Group import gospeak.core.domain.utils.BasicCtx import gospeak.web.api.domain.utils.ApiPlace import play.api.libs.json.{Json, Writes} object ApiGroup { // data to display publicly final case class Published(slug: String, name: String, contact: Option[String], description: String, location: Option[ApiPlace], tags: Seq[String], created: Instant) object Published { implicit val writes: Writes[Published] = Json.writes[Published] } def published(group: Group.Full)(implicit ctx: BasicCtx): Published = new Published( slug = group.slug.value, name = group.name.value, contact = group.contact.map(_.value), description = group.description.value, location = group.location.map(ApiPlace.from), tags = group.tags.map(_.value), created = group.info.createdAt) // embedded data in other models, should be public final case class Embed(slug: String, name: String, contact: Option[String], description: String, location: Option[ApiPlace], tags: Seq[String]) object Embed { implicit val writes: Writes[Embed] = Json.writes[Embed] } def embed(group: Group)(implicit ctx: BasicCtx): Embed = new Embed( slug = group.slug.value, name = group.name.value, contact = group.contact.map(_.value), description = group.description.value, location = group.location.map(ApiPlace.from), tags = group.tags.map(_.value)) }
Example 7
Source File: ApiPlace.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain.utils import gospeak.core.domain.utils.BasicCtx import gospeak.libs.scala.domain.GMapPlace import play.api.libs.json.{Json, Writes} case class ApiPlace(name: String, address: String, locality: Option[String], country: String, url: String, geo: ApiGeo) object ApiPlace { def from(p: GMapPlace)(implicit ctx: BasicCtx): ApiPlace = new ApiPlace( name = p.name, address = p.formatted, locality = p.locality, country = p.country, url = p.url, geo = ApiGeo(p.geo.lat, p.geo.lng)) val unknown = ApiPlace("unknown", "Unknown address", None, "unknown", "https://maps.google.com/?cid=3360768160548514744", ApiGeo(48.8716827, 2.307039)) implicit val writes: Writes[ApiPlace] = Json.writes[ApiPlace] }
Example 8
Source File: ApiInfo.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain.utils import java.time.Instant import gospeak.core.domain.User import gospeak.core.domain.utils.{BasicCtx, Info} import gospeak.web.api.domain.ApiUser import play.api.libs.json.{Json, Writes} final case class ApiInfo(createdAt: Instant, createdBy: ApiUser.Embed, updatedAt: Instant, updatedBy: ApiUser.Embed) object ApiInfo { def from(i: Info, users: Seq[User])(implicit ctx: BasicCtx): ApiInfo = new ApiInfo( createdAt = i.createdAt, createdBy = ApiUser.embed(i.createdBy, users), updatedAt = i.updatedAt, updatedBy = ApiUser.embed(i.updatedBy, users)) implicit val writes: Writes[ApiInfo] = Json.writes[ApiInfo] }
Example 9
Source File: ApiSocial.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain.utils import gospeak.core.domain.utils.{BasicCtx, SocialAccounts} import play.api.libs.json.{Json, Writes} final case class ApiSocial(facebook: Option[ApiSocial.Account], instagram: Option[ApiSocial.Account], twitter: Option[ApiSocial.Account], linkedIn: Option[ApiSocial.Account], youtube: Option[ApiSocial.Account], meetup: Option[ApiSocial.Account], eventbrite: Option[ApiSocial.Account], slack: Option[ApiSocial.Account], discord: Option[ApiSocial.Account], github: Option[ApiSocial.Account]) object ApiSocial { final case class Account(url: String, handle: String) object Account { implicit val writes: Writes[Account] = Json.writes[Account] } def from(s: SocialAccounts)(implicit ctx: BasicCtx): ApiSocial = ApiSocial( facebook = s.facebook.map(a => Account(a.url.value, a.handle)), instagram = s.instagram.map(a => Account(a.url.value, a.handle)), twitter = s.twitter.map(a => Account(a.url.value, a.handle)), linkedIn = s.linkedIn.map(a => Account(a.url.value, a.handle)), youtube = s.youtube.map(a => Account(a.url.value, a.handle)), meetup = s.meetup.map(a => Account(a.url.value, a.handle)), eventbrite = s.eventbrite.map(a => Account(a.url.value, a.handle)), slack = s.slack.map(a => Account(a.url.value, a.handle)), discord = s.discord.map(a => Account(a.url.value, a.handle)), github = s.github.map(a => Account(a.url.value, a.handle))) implicit val writes: Writes[ApiSocial] = Json.writes[ApiSocial] }
Example 10
Source File: ApiVenue.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import gospeak.core.domain.Venue import gospeak.core.domain.utils.BasicCtx import gospeak.web.api.domain.utils.ApiPlace import play.api.libs.json.{Json, Writes} object ApiVenue { // embedded data in other models, should be public final case class Embed(address: ApiPlace, partner: ApiPartner.Embed) object Embed { implicit val writes: Writes[Embed] = Json.writes[Embed] } def embed(v: Venue.Full)(implicit ctx: BasicCtx): Embed = new Embed( address = ApiPlace.from(v.address), partner = ApiPartner.embed(v.partner)) def unknown(id: Venue.Id)(implicit ctx: BasicCtx): Embed = new Embed( address = ApiPlace.unknown, partner = ApiPartner.unknown) }
Example 11
Source File: playjson.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s import java.nio.charset.Charset import org.apache.pulsar.client.api.Schema import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType} import play.api.libs.json.{Json, Reads, Writes} import scala.annotation.implicitNotFound package object playjson { @implicitNotFound("No Writes or Reads for type ${T} found. Bring an implicit Writes[T] and Reads[T] instance in scope") implicit def playSchema[T: Manifest](implicit w: Writes[T], r: Reads[T]): Schema[T] = new Schema[T] { override def clone(): Schema[T] = this override def encode(t: T): Array[Byte] = Json.stringify(Json.toJson(t)(w)).getBytes(Charset.forName("UTF-8")) override def decode(bytes: Array[Byte]): T = Json.parse(bytes).as[T] override def getSchemaInfo: SchemaInfo = new SchemaInfo() .setName(manifest[T].runtimeClass.getCanonicalName) .setType(SchemaType.JSON) .setSchema("""{"type":"any"}""".getBytes("UTF-8")) } }
Example 12
Source File: ApiComment.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import java.time.Instant import gospeak.core.domain.Comment import gospeak.core.domain.utils.BasicCtx import play.api.libs.json.{Json, Writes} final case class ApiComment(id: String, answers: Option[String], text: String, createdAt: Instant, createdBy: ApiUser.Embed) object ApiComment { implicit val writes: Writes[ApiComment] = Json.writes[ApiComment] def from(c: Comment.Full)(implicit ctx: BasicCtx): ApiComment = new ApiComment( id = c.id.value, answers = c.answers.map(_.value), text = c.text, createdAt = c.createdAt, createdBy = ApiUser.embed(c.createdBy)) }
Example 13
Source File: SimpleWebSocketActor.scala From monix-sample with Apache License 2.0 | 5 votes |
package engine import akka.actor.{Actor, ActorRef, Props} import engine.SimpleWebSocketActor.Next import monix.execution.Scheduler import monix.reactive.Observable import monix.execution.Ack.Continue import monix.execution.cancelables.CompositeCancelable import org.joda.time.{DateTime, DateTimeZone} import play.api.libs.json.{JsValue, Json, Writes} import scala.concurrent.duration._ import engine.BackPressuredWebSocketActor._ class SimpleWebSocketActor[T: Writes] (producer: Observable[T], out: ActorRef)(implicit s: Scheduler) extends Actor { def receive: Receive = { case Next(jsValue) => out ! jsValue } private[this] val subscription = CompositeCancelable() override def preStart(): Unit = { super.preStart() val source = { val initial = Observable.evalOnce(initMessage(now())) val obs = initial ++ producer.map(x => Json.toJson(x)) val timeout = obs.debounce(3.seconds).map(_ => keepAliveMessage(now())) Observable.merge(obs, timeout) } subscription += source.subscribe { jsValue => self ! Next(jsValue) Continue } } override def postStop(): Unit = { subscription.cancel() super.postStop() } def now(): Long = DateTime.now(DateTimeZone.UTC).getMillis } object SimpleWebSocketActor { case class Next(value: JsValue) }
Example 14
Source File: AuditSerialiser.scala From play-auditing with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.audit.serialiser import play.api.libs.json.{JsString, JsValue, Json, Writes} import uk.gov.hmrc.play.audit.model.{DataCall, DataEvent, ExtendedDataEvent, MergedDataEvent} import java.time.{Instant, ZoneId} import java.time.format.DateTimeFormatter object DateWriter { // Datastream does not support default X offset (i.e. `Z` must be `+0000`) implicit def instantWrites = new Writes[Instant] { private val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ") def writes(instant: Instant): JsValue = JsString(dateFormat.withZone(ZoneId.of("UTC")).format(instant)) } } trait AuditSerialiserLike { def serialise(event: DataEvent): JsValue def serialise(event: ExtendedDataEvent): JsValue def serialise(event: MergedDataEvent): JsValue } class AuditSerialiser extends AuditSerialiserLike { private implicit val dateWriter: Writes[Instant] = DateWriter.instantWrites private implicit val dataEventWriter: Writes[DataEvent] = Json.writes[DataEvent] private implicit val dataCallWriter: Writes[DataCall] = Json.writes[DataCall] private implicit val extendedDataEventWriter: Writes[ExtendedDataEvent] = Json.writes[ExtendedDataEvent] private implicit val mergedDataEventWriter: Writes[MergedDataEvent] = Json.writes[MergedDataEvent] override def serialise(event: DataEvent): JsValue = Json.toJson(event) override def serialise(event: ExtendedDataEvent): JsValue = Json.toJson(event) override def serialise(event: MergedDataEvent): JsValue = Json.toJson(event) } object AuditSerialiser extends AuditSerialiser
Example 15
Source File: Webhook.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.webhook import cool.graph.messagebus.Conversions import play.api.libs.json.{Json, Reads, Writes} object Webhook { implicit val mapStringReads = Reads.mapReads[String] implicit val mapStringWrites = Writes.mapWrites[String] implicit val webhooksWrites = Json.format[Webhook] implicit val marshaller = Conversions.Marshallers.FromJsonBackedType[Webhook]() implicit val unmarshaller = Conversions.Unmarshallers.ToJsonBackedType[Webhook]() } case class Webhook( projectId: String, functionId: String, requestId: String, url: String, payload: String, id: String, headers: Map[String, String] )
Example 16
Source File: TestSpec.scala From study-category-theory with Apache License 2.0 | 5 votes |
package com.github.dnvriend import akka.actor.ActorSystem import akka.stream.Materializer import akka.util.Timeout 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.{ JsValue, Json, Writes } import play.api.test.WsTestClient import scala.concurrent.duration._ import scala.concurrent.{ ExecutionContext, Future } import scala.reflect.ClassTag import scala.util.Try object Person { implicit val format = Json.format[Person] implicit class ValueObjectOps(val self: Person) { def toJson: JsValue = Json.toJson(self) } implicit class IterableOps(val self: Iterable[Person]) { def toJson: JsValue = Json.toJson(self) } } 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 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 = getNamedComponent[Int]("test.port") implicit val timeout: Timeout = getComponent[Timeout] 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] // ================================== Supporting Operations ==================================== def id: String = java.util.UUID.randomUUID().toString implicit class PimpedFuture[T](self: Future[T]) { def toTry: Try[T] = Try(self.futureValue) } final val FirstName: String = "John" final val LastName: String = "Doe" override protected def beforeEach(): Unit = { } }
Example 17
Source File: HatClaims.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.phata.models import play.api.libs.json.{ JsPath, Json, Reads, Writes } import play.api.libs.functional.syntax._ case class ApiClaimHatRequest(applicationId: String, email: String) object ApiClaimHatRequest { implicit val claimHatRequestApiReads: Reads[ApiClaimHatRequest] = ( (JsPath \ "applicationId").read[String] and (JsPath \ "email").read[String](Reads.email))(ApiClaimHatRequest.apply _) implicit val claimHatRequestApiWrites: Writes[ApiClaimHatRequest] = Json.format[ApiClaimHatRequest] } case class HatClaimCompleteRequest( email: String, termsAgreed: Boolean, optins: Array[String], hatName: String, hatCluster: String, password: String) case class HattersClaimPayload( email: String, termsAgreed: Boolean, sandbox: Boolean, platform: String, newsletterOptin: Option[Boolean], hatName: String, hatCluster: String) object HatClaimCompleteRequest { implicit val hatClaimRequestReads: Reads[HatClaimCompleteRequest] = Json.reads[HatClaimCompleteRequest] } object HattersClaimPayload { def apply(claim: HatClaimCompleteRequest): HattersClaimPayload = new HattersClaimPayload( claim.email, claim.termsAgreed, claim.hatCluster == "hubat.net", "web", Some(claim.optins.nonEmpty), claim.hatName, claim.hatCluster) implicit val HatClaimRequestWrites: Writes[HattersClaimPayload] = Json.format[HattersClaimPayload] }
Example 18
Source File: AllocatedTask.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.models import de.frosner.broccoli.nomad.models.{ClientStatus, TaskState} import play.api.libs.json.{Json, Writes} import shapeless.tag.@@ import squants.information.Information import squants.time.Frequency final case class AllocatedTask( taskName: String, taskState: TaskState, allocationId: String, clientStatus: ClientStatus, resources: AllocatedTask.Resources ) object AllocatedTask { sealed trait CPURequired sealed trait CPUUsed sealed trait MemoryRequired sealed trait MemoryUsed final case class Resources( cpuRequired: Option[Frequency] @@ CPURequired, cpuUsed: Option[Frequency] @@ CPUUsed, memoryRequired: Option[Information] @@ MemoryRequired, memoryUsed: Option[Information] @@ MemoryUsed ) object Resources { implicit val resourcesTaskWrites: Writes[Resources] = Writes { resources => Json .obj( "cpuRequiredMhz" -> resources.cpuRequired.map(_.toMegahertz), "cpuUsedMhz" -> resources.cpuUsed.map(_.toMegahertz), "memoryRequiredBytes" -> resources.memoryRequired.map(_.toBytes), "memoryUsedBytes" -> resources.memoryUsed.map(_.toBytes) ) } } implicit val allocatedTaskWrites: Writes[AllocatedTask] = Writes { task => Json.obj( "taskName" -> task.taskName, "taskState" -> task.taskState, "allocationId" -> task.allocationId, "clientStatus" -> task.clientStatus, "resources" -> task.resources ) } }
Example 19
Source File: helpers.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.test import play.api.libs.json.Writes import uk.gov.hmrc.http._ import scala.concurrent.{ExecutionContext, Future} trait TestHttpCore extends CorePost with CoreGet with CorePut with CorePatch with CoreDelete with Request { override def applicableHeaders(url: String)(implicit hc: HeaderCarrier): Seq[(String, String)] = Nil override def POST[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def POSTString[O]( url: String, body: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def POSTForm[O]( url: String, body: Map[String, Seq[String]], headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def POSTEmpty[O]( url: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def GET[A]( url: String, queryParams: Seq[(String, String)], headers: Seq[(String, String)])( implicit rds: HttpReads[A], hc: HeaderCarrier, ec: ExecutionContext): Future[A] = ??? override def PUT[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def PUTString[O]( url: String, body: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def PATCH[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? override def DELETE[O]( url: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = ??? }
Example 20
Source File: HttpPatchSpec.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import akka.actor.ActorSystem import com.typesafe.config.Config import org.mockito.ArgumentCaptor import org.mockito.Matchers.{any, eq => is} import org.mockito.Mockito._ import org.scalatestplus.mockito.MockitoSugar import org.scalatest.wordspec.AnyWordSpecLike import org.scalatest.matchers.should.Matchers import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.hooks.{HookData, HttpHook} import scala.concurrent.{ExecutionContext, Future} import uk.gov.hmrc.http.HttpReads.Implicits._ class HttpPatchSpec extends AnyWordSpecLike with Matchers with CommonHttpBehaviour { import ExecutionContext.Implicits.global class StubbedHttpPatch(doPatchResult: Future[HttpResponse], doPatchWithHeaderResult: Future[HttpResponse]) extends HttpPatch with ConnectionTracingCapturing with MockitoSugar { val testHook1 = mock[HttpHook] val testHook2 = mock[HttpHook] val hooks = Seq(testHook1, testHook2) override def configuration: Option[Config] = None override protected def actorSystem: ActorSystem = ActorSystem("test-actor-system") def doPatch[A](url: String, body: A, headers: Seq[(String, String)])(implicit rds: Writes[A], hc: HeaderCarrier, ec: ExecutionContext) = doPatchResult } "HttpPatch" should { val testObject = TestRequestClass("a", 1) "be able to return plain responses" in { val response = HttpResponse(200, testBody) val testPatch = new StubbedHttpPatch(Future.successful(response), Future.successful(response)) testPatch.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")).futureValue shouldBe response } "be able to return objects deserialised from JSON" in { val response= Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")) val testPatch = new StubbedHttpPatch(response, response) testPatch.PATCH[TestRequestClass, TestClass](url, testObject, Seq("header" -> "foo")).futureValue should be(TestClass("t", 10)) } behave like anErrorMappingHttpCall( "PATCH", (url, responseF) => new StubbedHttpPatch(responseF, responseF).PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo"))) behave like aTracingHttpCall("PATCH", "PATCH", new StubbedHttpPatch(defaultHttpResponse, defaultHttpResponse)) { _.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")) } "Invoke any hooks provided" in { val dummyResponse = HttpResponse(200, testBody) val dummyResponseFuture = Future.successful(dummyResponse) val testPatch = new StubbedHttpPatch(dummyResponseFuture, dummyResponseFuture) val testJson = Json.stringify(trcreads.writes(testObject)) testPatch.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")).futureValue val respArgCaptor1 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]]) val respArgCaptor2 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]]) verify(testPatch.testHook1) .apply(is(url), is("PATCH"), is(Some(HookData.FromString(testJson))), respArgCaptor1.capture())(any(), any()) verify(testPatch.testHook2) .apply(is(url), is("PATCH"), is(Some(HookData.FromString(testJson))), respArgCaptor2.capture())(any(), any()) // verifying directly without ArgumentCaptor didn't work as Futures were different instances // e.g. Future.successful(5) != Future.successful(5) respArgCaptor1.getValue.futureValue shouldBe dummyResponse respArgCaptor2.getValue.futureValue shouldBe dummyResponse } } }
Example 21
Source File: WSPut.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.http.ws.default import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.{CorePut, HeaderCarrier, HttpResponse, PutHttpTransport} import uk.gov.hmrc.play.http.ws.{WSExecute, WSHttpResponse, WSRequestBuilder} import scala.concurrent.{ExecutionContext, Future} trait WSPut extends CorePut with PutHttpTransport with WSRequestBuilder with WSExecute{ override def doPut[A]( url: String, body: A, headers: Seq[(String, String)])( implicit rds: Writes[A], hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(Json.toJson(body)), "PUT") .map(WSHttpResponse.apply) override def doPutString( url: String, body: String, headers: Seq[(String, String)])( implicit hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(body), "PUT") .map(WSHttpResponse.apply) }
Example 22
Source File: PublicKey.scala From Waves with MIT License | 5 votes |
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 23
Source File: ClusterTest.scala From exhibitor-mesos-framework with Apache License 2.0 | 5 votes |
package ly.stealth.mesos.exhibitor import org.junit.Assert._ import org.junit.Test import play.api.libs.json.{Writes, Reads} import scala.util.{Failure, Try} class ClusterTest extends MesosTestCase { @Test def expandIds() { val cluster = Cluster() (0 until 5).foreach(i => cluster.addServer(ExhibitorServer("" + i))) Try(cluster.expandIds("")) match { case Failure(t) if t.isInstanceOf[IllegalArgumentException] => case other => fail(other.toString) } assertEquals(List("0"), cluster.expandIds("0")) assertEquals(List("0", "2", "4"), cluster.expandIds("0,2,4")) assertEquals(List("1", "2", "3"), cluster.expandIds("1..3")) assertEquals(List("0", "1", "3", "4"), cluster.expandIds("0..1,3..4")) assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("*")) // duplicates assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("0..3,2..4")) // sorting assertEquals(List("2", "3", "4"), cluster.expandIds("4,3,2")) } @Test def loadSave() { val cluster = Cluster() cluster.frameworkId = Some("some id") cluster.save() val loaded = Cluster() loaded.load() assertEquals(cluster.frameworkId, loaded.frameworkId) } }
Example 24
Source File: Storage.scala From exhibitor-mesos-framework with Apache License 2.0 | 5 votes |
package ly.stealth.mesos.exhibitor import java.io.{File, FileWriter} import play.api.libs.json.{Json, Reads, Writes} import scala.io.Source trait Storage[T] { def save(value: T)(implicit writes: Writes[T]) def load(implicit reads: Reads[T]): Option[T] } case class FileStorage[T](file: String) extends Storage[T] { override def save(value: T)(implicit writes: Writes[T]) { val writer = new FileWriter(file) try { writer.write(Json.stringify(Json.toJson(value))) } finally { writer.close() } } override def load(implicit reads: Reads[T]): Option[T] = { if (!new File(file).exists()) None else Json.parse(Source.fromFile(file).mkString).asOpt[T] } }
Example 25
Source File: GlobalScriptListResult.scala From izanami with Apache License 2.0 | 5 votes |
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 26
Source File: OrFormats.scala From courscala with Apache License 2.0 | 5 votes |
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 27
Source File: TypedFormats.scala From courscala with Apache License 2.0 | 5 votes |
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 28
Source File: play.scala From caliban with Apache License 2.0 | 5 votes |
package caliban.interop.play import caliban.introspection.adt.__Type import caliban.schema.Step.QueryStep import caliban.schema.Types.makeScalar import caliban.schema.{ ArgBuilder, PureStep, Schema, Step } import caliban.{ InputValue, ResponseValue } import play.api.libs.json.{ JsPath, JsValue, Json, JsonValidationError, Reads, Writes } import zio.ZIO import zio.query.ZQuery private[caliban] trait IsPlayJsonReads[F[_]] private[caliban] object IsPlayJsonReads { implicit val isPlayJsonReads: IsPlayJsonReads[Reads] = null } object json { implicit val jsonSchema: Schema[Any, JsValue] = new Schema[Any, JsValue] { private def parse(value: JsValue) = implicitly[Reads[ResponseValue]] .reads(value) .asEither .left .map(parsingException) override def toType(isInput: Boolean, isSubscription: Boolean): __Type = makeScalar("Json") override def resolve(value: JsValue): Step[Any] = QueryStep(ZQuery.fromEffect(ZIO.fromEither(parse(value))).map(PureStep)) } implicit val jsonArgBuilder: ArgBuilder[JsValue] = (input: InputValue) => Right(Json.toJson(input)) private[caliban] def parsingException( errs: scala.collection.Seq[(JsPath, scala.collection.Seq[JsonValidationError])] ) = new Throwable(s"Couldn't decode json: $errs") }
Example 29
Source File: Storage.scala From zipkin-mesos-framework with Apache License 2.0 | 5 votes |
package net.elodina.mesos.zipkin.storage import java.io.{File, FileWriter} import org.I0Itec.zkclient.ZkClient import org.I0Itec.zkclient.exception.ZkNodeExistsException import org.I0Itec.zkclient.serialize.ZkSerializer import play.api.libs.json.{Json, Reads, Writes} import scala.io.Source trait Storage[T] { def save(value: T)(implicit writes: Writes[T]) def load(implicit reads: Reads[T]): Option[T] } case class FileStorage[T](file: String) extends Storage[T] { override def save(value: T)(implicit writes: Writes[T]) { val writer = new FileWriter(file) try { writer.write(Json.stringify(Json.toJson(value))) } finally { writer.close() } } override def load(implicit reads: Reads[T]): Option[T] = { if (!new File(file).exists()) None else Json.parse(Source.fromFile(file).mkString).asOpt[T] } } case class ZkStorage[T](zk: String) extends Storage[T] { val (zkConnect, path) = zk.span(_ != '/') createChrootIfRequired() private def createChrootIfRequired() { if (path != "") { val client = zkClient try { client.createPersistent(path, true) } finally { client.close() } } } private def zkClient: ZkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer) override def save(value: T)(implicit writes: Writes[T]) { val client = zkClient val json = Json.stringify(Json.toJson(value)) try { client.createPersistent(path, json) } catch { case e: ZkNodeExistsException => client.writeData(path, json) } finally { client.close() } } override def load(implicit reads: Reads[T]): Option[T] = { val client = zkClient try { Option(client.readData(path, true).asInstanceOf[String]).flatMap(Json.parse(_).asOpt[T]) } finally { client.close() } } } private object ZKStringSerializer extends ZkSerializer { def serialize(data: Object): Array[Byte] = data.asInstanceOf[String].getBytes("UTF-8") def deserialize(bytes: Array[Byte]): Object = { if (bytes == null) null else new String(bytes, "UTF-8") } }
Example 30
Source File: AssetsRouteSpec.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.http import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Route import com.wavesplatform.account.Address import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi} import com.wavesplatform.api.http.assets.AssetsApiRoute import com.wavesplatform.api.http.requests.{TransferV1Request, TransferV2Request} import com.wavesplatform.http.ApiMarshallers._ import com.wavesplatform.state.Blockchain import com.wavesplatform.transaction.transfer._ import com.wavesplatform.wallet.Wallet import com.wavesplatform.{RequestGen, TestTime} import org.scalamock.scalatest.PathMockFactory import org.scalatest.concurrent.Eventually import play.api.libs.json.Writes class AssetsRouteSpec extends RouteSpec("/assets") with RequestGen with PathMockFactory with Eventually with RestAPISettingsHelper { private val wallet = stub[Wallet] private val state = stub[Blockchain] private val seed = "seed".getBytes("UTF-8") private val senderPrivateKey = Wallet.generateNewAccount(seed, 0) private val receiverPrivateKey = Wallet.generateNewAccount(seed, 1) (wallet.privateKeyAccount _).when(senderPrivateKey.toAddress).onCall((_: Address) => Right(senderPrivateKey)).anyNumberOfTimes() "/transfer" - { val route: Route = AssetsApiRoute( restAPISettings, wallet, DummyUtxPoolSynchronizer.accepting, state, new TestTime(), mock[CommonAccountsApi], mock[CommonAssetsApi] ).route def posting[A: Writes](v: A): RouteTestResult = Post(routePath("/transfer"), v).addHeader(ApiKeyHeader) ~> route "accepts TransferRequest" in { val req = TransferV1Request( assetId = None, feeAssetId = None, amount = 1 * Waves, fee = Waves / 3, sender = senderPrivateKey.toAddress.toString, attachment = Some("attachment"), recipient = receiverPrivateKey.toAddress.toString, timestamp = Some(System.currentTimeMillis()) ) posting(req) ~> check { status shouldBe StatusCodes.OK responseAs[TransferTransaction] } } "accepts VersionedTransferRequest" in { val req = TransferV2Request( assetId = None, amount = 1 * Waves, feeAssetId = None, fee = Waves / 3, sender = senderPrivateKey.toAddress.toString, attachment = None, recipient = receiverPrivateKey.toAddress.toString, timestamp = Some(System.currentTimeMillis()) ) posting(req) ~> check { status shouldBe StatusCodes.OK responseAs[TransferV2Request] } } "returns a error if it is not a transfer request" in { val req = issueReq.sample.get posting(req) ~> check { status shouldNot be(StatusCodes.OK) } } } }
Example 31
Source File: LeaseCancelV1Request.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.api.http.requests import play.api.libs.json.{Json, Reads, Writes} case class LeaseCancelV1Request(sender: String, txId: String, fee: Long, timestamp: Option[Long] = None) object LeaseCancelV1Request { implicit val leaseCancelRequestReads: Reads[LeaseCancelV1Request] = { import play.api.libs.functional.syntax._ import play.api.libs.json._ ((JsPath \ "sender").read[String] ~ ((JsPath \ "txId").read[String] | (JsPath \ "leaseId").read[String]) ~ (JsPath \ "fee").read[Long] ~ (JsPath \ "timestamp").readNullable[Long])(LeaseCancelV1Request.apply _) } implicit val leaseCancelRequestWrites: Writes[LeaseCancelV1Request] = Json.writes[LeaseCancelV1Request] }
Example 32
Source File: BurnV1Request.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.api.http.requests import play.api.libs.json.{Json, Reads, Writes} case class BurnV1Request(sender: String, assetId: String, quantity: Long, fee: Long, timestamp: Option[Long] = None) object BurnV1Request { implicit val burnV1Reads: Reads[BurnV1Request] = { import play.api.libs.functional.syntax._ import play.api.libs.json._ ((JsPath \ "sender").read[String] ~ (JsPath \ "assetId").read[String] ~ ((JsPath \ "quantity").read[Long] | (JsPath \ "amount").read[Long]) ~ (JsPath \ "fee").read[Long] ~ (JsPath \ "timestamp").readNullable[Long])(BurnV1Request.apply _) } implicit val burnV1Writes: Writes[BurnV1Request] = Json.writes[BurnV1Request] }
Example 33
Source File: WSPost.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.http.ws.default import play.api.libs.json.{Json, Writes} import play.api.libs.ws.WSRequest import uk.gov.hmrc.http.{CorePost, HeaderCarrier, HttpResponse, PostHttpTransport} import uk.gov.hmrc.play.http.ws.{WSExecute, WSHttpResponse, WSRequestBuilder} import scala.concurrent.{ExecutionContext, Future} trait WSPost extends CorePost with PostHttpTransport with WSRequestBuilder with WSExecute { def withEmptyBody(request: WSRequest): WSRequest override def doPost[A]( url: String, body: A, headers: Seq[(String, String)] )( implicit rds: Writes[A], hc: HeaderCarrier, ec: ExecutionContext ): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(Json.toJson(body)), "POST") .map(WSHttpResponse.apply) override def doFormPost( url: String, body: Map[String, Seq[String]], headers: Seq[(String, String)] )( implicit hc: HeaderCarrier, ec: ExecutionContext ): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(body), "POST") .map(WSHttpResponse.apply) override def doPostString( url: String, body: String, headers: Seq[(String, String)] )( implicit hc: HeaderCarrier, ec: ExecutionContext ): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(body), "POST") .map(WSHttpResponse.apply) override def doEmptyPost[A]( url: String, headers: Seq[(String, String)] )( implicit hc: HeaderCarrier, ec: ExecutionContext ): Future[HttpResponse] = execute(withEmptyBody(buildRequest(url, headers)), "POST") .map(WSHttpResponse.apply) }
Example 34
Source File: KeyPair.scala From Waves with MIT License | 5 votes |
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 35
Source File: PrivateKey.scala From Waves with MIT License | 5 votes |
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 36
Source File: JsonFileStorage.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.utils import java.io.{File, PrintWriter} import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec import play.api.libs.json.{Json, Reads, Writes} import java.util.Base64 import scala.io.Source import scala.util.control.NonFatal object JsonFileStorage { private[this] val KeySalt = "0495c728-1614-41f6-8ac3-966c22b4a62d" private[this] val AES = "AES" private[this] val Algorithm = AES + "/ECB/PKCS5Padding" private[this] val HashingAlgorithm = "PBKDF2WithHmacSHA512" private[this] val HashingIterations = 999999 private[this] val KeySizeBits = 128 def prepareKey(key: String): SecretKeySpec = { import java.security.NoSuchAlgorithmException import java.security.spec.InvalidKeySpecException import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec def hashPassword(password: Array[Char], salt: Array[Byte], iterations: Int, keyLength: Int): Array[Byte] = try { val keyFactory = SecretKeyFactory.getInstance(HashingAlgorithm) val keySpec = new PBEKeySpec(password, salt, iterations, keyLength) val key = keyFactory.generateSecret(keySpec) key.getEncoded } catch { case e @ (_: NoSuchAlgorithmException | _: InvalidKeySpecException) => throw new RuntimeException("Password hashing error", e) } new SecretKeySpec(hashPassword(key.toCharArray, KeySalt.utf8Bytes, HashingIterations, KeySizeBits), AES) } def save[T](value: T, path: String, key: Option[SecretKeySpec])(implicit w: Writes[T]): Unit = { val folder = new File(path).getParentFile if (!folder.exists()) folder.mkdirs() val file = new PrintWriter(path) try { val json = Json.toJson(value).toString() val data = key.fold(json)(k => encrypt(k, json)) file.write(data) } finally file.close() } def save[T](value: T, path: String)(implicit w: Writes[T]): Unit = save(value, path, None) def load[T](path: String, key: Option[SecretKeySpec] = None)(implicit r: Reads[T]): T = { val file = Source.fromFile(path) try { val dataStr = file.mkString Json.parse(key.fold(dataStr)(k => decrypt(k, dataStr))).as[T] } finally file.close() } def load[T](path: String)(implicit r: Reads[T]): T = load(path, Option.empty[SecretKeySpec])(r) private[this] def encrypt(key: SecretKeySpec, value: String): String = { try { val cipher: Cipher = Cipher.getInstance(Algorithm) cipher.init(Cipher.ENCRYPT_MODE, key) new String(Base64.getEncoder.encode(cipher.doFinal(value.utf8Bytes))) } catch { case NonFatal(e) => throw new RuntimeException("File storage encrypt error", e) } } private[this] def decrypt(key: SecretKeySpec, encryptedValue: String): String = { try { val cipher: Cipher = Cipher.getInstance(Algorithm) cipher.init(Cipher.DECRYPT_MODE, key) new String(cipher.doFinal(Base64.getDecoder.decode(encryptedValue))) } catch { case NonFatal(e) => throw new RuntimeException("File storage decrypt error", e) } } }
Example 37
Source File: IsCompleteRequest.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.KernelMessageContent import play.api.libs.json.{Json, Reads, Writes} case class IsCompleteRequest( code: String ) extends KernelMessageContent { override def content : String = Json.toJson(this)(IsCompleteRequest.isCompleteRequestWrites).toString } object IsCompleteRequest extends TypeString { implicit val isCompleteRequestReads: Reads[IsCompleteRequest] = Json.reads[IsCompleteRequest] implicit val isCompleteRequestWrites: Writes[IsCompleteRequest] = Json.writes[IsCompleteRequest] override def toTypeString: String = "is_complete_request" }
Example 38
Source File: IsCompleteReply.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.{KernelMessageContent} import play.api.libs.json.{Json, Reads, Writes} case class IsCompleteReply ( status: String, indent: String ) extends KernelMessageContent { override def content : String = Json.toJson(this)(IsCompleteReply.isCompleteReplyWrites).toString } object IsCompleteReply extends TypeString { implicit val isCompleteReplyReads: Reads[IsCompleteReply] = Json.reads[IsCompleteReply] implicit val isCompleteReplyWrites: Writes[IsCompleteReply] = Json.writes[IsCompleteReply] override def toTypeString: String = "complete_reply" }
Example 39
Source File: PlayJsonSupport.scala From kafka-serde-scala with Apache License 2.0 | 5 votes |
package io.github.azhur.kafkaserdeplayjson import java.nio.charset.StandardCharsets.UTF_8 import java.util import io.github.azhur.kafkaserdeplayjson.PlayJsonSupport.PlayJsonError import org.apache.kafka.common.errors.SerializationException import org.apache.kafka.common.serialization.{ Deserializer, Serde, Serializer } import play.api.libs.json.{ JsError, JsValue, Json, Reads, Writes } import scala.language.implicitConversions import scala.util.control.NonFatal trait PlayJsonSupport { implicit def toSerializer[T <: AnyRef]( implicit writes: Writes[T], printer: JsValue => String = Json.stringify ): Serializer[T] = new Serializer[T] { override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {} override def close(): Unit = {} override def serialize(topic: String, data: T): Array[Byte] = if (data == null) null else try printer(writes.writes(data)).getBytes(UTF_8) catch { case NonFatal(e) => throw new SerializationException(e) } } implicit def toDeserializer[T >: Null <: AnyRef: Manifest]( implicit reads: Reads[T] ): Deserializer[T] = new Deserializer[T] { override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {} override def close(): Unit = {} override def deserialize(topic: String, data: Array[Byte]): T = if (data == null) null else reads .reads(Json.parse(new String(data, UTF_8))) .recoverTotal { e => throw new SerializationException(PlayJsonError(e)) } } implicit def toSerde[T >: Null <: AnyRef: Manifest]( implicit writes: Writes[T], reads: Reads[T], printer: JsValue => String = Json.stringify ): Serde[T] = new Serde[T] { override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {} override def close(): Unit = {} override def serializer(): Serializer[T] = toSerializer[T] override def deserializer(): Deserializer[T] = toDeserializer[T] } } object PlayJsonSupport extends PlayJsonSupport { final case class PlayJsonError(error: JsError) extends RuntimeException { override def getMessage: String = JsError.toJson(error).toString() } }
Example 40
Source File: patch.scala From skuber with Apache License 2.0 | 5 votes |
package skuber.api import akka.http.scaladsl.model.{HttpCharsets, MediaType} import play.api.libs.json.Writes package object patch { object CustomMediaTypes { val `application/merge-patch+json` = MediaType.applicationWithFixedCharset("merge-patch+json", HttpCharsets.`UTF-8`) val `application/strategic-merge-patch+json` = MediaType.applicationWithFixedCharset("strategic-merge-patch+json", HttpCharsets.`UTF-8`) } object JsonPatchOperation { sealed trait Operation { def op: String } trait ValueOperation[T] extends Operation { type ValueType = T def path: String def value: ValueType def fmt: Writes[T] } trait UnaryOperation extends Operation { def path: String } trait DirectionalOperation extends Operation { def from: String def path: String } case class Add[T](path: String, value: T)(implicit val fmt: Writes[T]) extends ValueOperation[T] { val op = "add" } case class Remove(path: String) extends UnaryOperation { val op = "remove" } case class Replace[T](path: String, value: T)(implicit val fmt: Writes[T]) extends ValueOperation[T] { val op = "replace" } case class Move(from: String, path: String) extends DirectionalOperation { val op = "move" } case class Copy(from: String, path: String) extends DirectionalOperation { val op = "copy" } } trait Patch { val strategy: PatchStrategy } sealed trait PatchStrategy sealed trait MergePatchStrategy extends PatchStrategy case object StrategicMergePatchStrategy extends MergePatchStrategy case object JsonMergePatchStrategy extends MergePatchStrategy case object JsonPatchStrategy extends PatchStrategy case class JsonPatch(operations: List[JsonPatchOperation.Operation]) extends Patch { override val strategy = JsonPatchStrategy } trait JsonMergePatch extends Patch { override val strategy = JsonMergePatchStrategy } trait StrategicMergePatch extends Patch { override val strategy = StrategicMergePatchStrategy } case class MetadataPatch(labels: Option[Map[String, String]] = Some(Map()), annotations: Option[Map[String, String]] = Some(Map()), override val strategy: MergePatchStrategy = StrategicMergePatchStrategy) extends Patch }
Example 41
Source File: SttpPlayJsonApi.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.playJson import sttp.client._ import sttp.model._ import sttp.client.internal.Utf8 import play.api.libs.json.{JsError, Json, Reads, Writes} import sttp.client.{IsOption, JsonInput, ResponseAs, ResponseError} import sttp.model.MediaType import scala.util.{Failure, Success, Try} trait SttpPlayJsonApi { implicit def playJsonBodySerializer[B: Writes]: BodySerializer[B] = b => StringBody(Json.stringify(Json.toJson(b)), Utf8, Some(MediaType.ApplicationJson)) def asJsonAlwaysUnsafe[B: Reads: IsOption]: ResponseAs[B, Nothing] = asStringAlways.map(ResponseAs.deserializeOrThrow(deserializeJson)) // Note: None of the play-json utilities attempt to catch invalid // json, so Json.parse needs to be wrapped in Try def deserializeJson[B: Reads: IsOption]: String => Either[JsError, B] = JsonInput.sanitize[B].andThen { s => Try(Json.parse(s)) match { case Failure(e: Exception) => Left(JsError(e.getMessage)) case Failure(t: Throwable) => throw t case Success(json) => Json.fromJson(json).asEither match { case Left(failures) => Left(JsError(failures)) case Right(success) => Right(success) } } } }
Example 42
Source File: ApiAttendee.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain import java.time.Instant import gospeak.core.domain.utils.BasicCtx import gospeak.core.services.meetup.domain.{MeetupAttendee, MeetupGroup} import gospeak.libs.scala.domain.Image import play.api.libs.json.{Json, Writes} object ApiAttendee { // data to display publicly final case class Published(name: String, avatar: String, meetupProfile: String, host: Boolean, response: String, updated: Instant) object Published { implicit val writes: Writes[Published] = Json.writes[Published] } def published(attendee: MeetupAttendee, group: MeetupGroup.Slug)(implicit ctx: BasicCtx): Published = new Published( name = attendee.name, avatar = attendee.avatar.map(_.value).getOrElse(Image.AdorableUrl(attendee.id.value.toString, None).value), meetupProfile = s"https://www.meetup.com/${group.value}/members/${attendee.id.value}", host = attendee.host, response = attendee.response, updated = attendee.updated) }
Example 43
Source File: MockSessionCache.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.helpers import play.api.libs.json.{Json, Reads, Writes} import uk.gov.hmrc.http.cache.client.{CacheMap, SessionCache} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{ExecutionContext, Future} import scala.io.Source import uk.gov.hmrc.http.{HeaderCarrier, HttpDelete, HttpGet, HttpPut, UserId} object MockSessionCache extends SessionCache{ val cachedNinoAndUsername = TestAccountBuilder.cachedNino val cachedUserId = UserId(s"/auth/oid/$cachedNinoAndUsername") override def defaultSource: String = ??? override def baseUri: String = ??? override def domain: String = ??? override def http: HttpGet with HttpPut with HttpDelete = ??? private def loadObjectFromFile[T](filename: String)(implicit rds: Reads[T]): Option[T] = { val fileContents = Source.fromFile(filename).mkString Json.parse(fileContents).validate[T].fold(invalid => None, valid => Some(valid)) } private def loadObjectBasedOnKey[T](key: String)(implicit rds: Reads[T]): Option[T] = key match { case _ => None } override def fetchAndGetEntry[T](key: String)(implicit hc: HeaderCarrier, rds: Reads[T],ec:ExecutionContext): Future[Option[T]] = Future.successful(hc.userId.filter(_ == cachedUserId).flatMap(p => loadObjectBasedOnKey(key))) override def cache[A](formId: String, body: A)(implicit wts: Writes[A], hc: HeaderCarrier,ec:ExecutionContext): Future[CacheMap] = Future.successful(CacheMap("", Map())) }
Example 44
Source File: WireMockMethods.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.support import com.github.tomakehurst.wiremock.client.MappingBuilder import com.github.tomakehurst.wiremock.client.WireMock._ import com.github.tomakehurst.wiremock.matching.UrlPattern import com.github.tomakehurst.wiremock.stubbing.StubMapping import play.api.libs.json.Writes trait WireMockMethods { def when(method: HTTPMethod, uri: String, queryParams: Map[String, String] = Map.empty, headers: Map[String, String] = Map.empty): Mapping = { new Mapping(method, uri, queryParams, headers, None) } class Mapping(method: HTTPMethod, uri: String, queryParams: Map[String, String], headers: Map[String, String], body: Option[String]) { private val mapping = { val uriMapping = method.wireMockMapping(urlPathMatching(uri)) val uriMappingWithQueryParams = queryParams.foldLeft(uriMapping) { case (m, (key, value)) => m.withQueryParam(key, matching(value)) } val uriMappingWithHeaders = headers.foldLeft(uriMappingWithQueryParams) { case (m, (key, value)) => m.withHeader(key, equalTo(value)) } body match { case Some(extractedBody) => uriMappingWithHeaders.withRequestBody(equalTo(extractedBody)) case None => uriMappingWithHeaders } } def thenReturn[T](status: Int, body: T)(implicit writes: Writes[T]): StubMapping = { val stringBody = writes.writes(body).toString() thenReturnInternal(status, Map.empty, Some(stringBody)) } def thenReturn(status: Int, body: String): StubMapping = { thenReturnInternal(status, Map.empty, Some(body)) } def thenReturn(status: Int, headers: Map[String, String] = Map.empty): StubMapping = { thenReturnInternal(status, headers, None) } def thenReturnInternal(status: Int, headers: Map[String, String], body: Option[String]): StubMapping = { val response = { val statusResponse = aResponse().withStatus(status) val responseWithHeaders = headers.foldLeft(statusResponse) { case (res, (key, value)) => res.withHeader(key, value) } body match { case Some(extractedBody) => responseWithHeaders.withBody(extractedBody) case None => responseWithHeaders } } stubFor(mapping.willReturn(response)) } } sealed trait HTTPMethod { def wireMockMapping(pattern: UrlPattern): MappingBuilder } case object POST extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = post(pattern) } case object GET extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = get(pattern) } case object DELETE extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = delete(pattern) } }
Example 45
Source File: Http.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.support import play.api.libs.json.{JsValue, Json, Writes} import play.api.libs.ws.{EmptyBody, WSRequest, WSResponse} import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.http.ws.WSHttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.{Await, Future} object Http extends BaseFunctionalSpec { def get(url: String)(implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.get() } def post[A](url: String, body: A, headers: Seq[(String, String)] = Seq.empty)( implicit writes: Writes[A], hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.post(Json.toJson(body)) } def postString(url: String, body: String, headers: Seq[(String, String)] = Seq.empty)( implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.withHttpHeaders("Content-Type" -> "application/json").post[String](body) } def postJson(url: String, body: JsValue, headers: Seq[(String, String)] = Seq.empty)( implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.post(body) } def putJson(url: String, body: JsValue, headers: Seq[(String, String)] = Seq.empty)( implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.put(body) } def postEmpty(url: String)(implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.post(EmptyBody) } def delete(url: String)(implicit hc: HeaderCarrier, timeout: FiniteDuration): HttpResponse = perform(url) { request => request.delete() } def perform(url: String)(fun: WSRequest => Future[WSResponse])(implicit hc: HeaderCarrier, timeout: FiniteDuration): WSHttpResponse = await(fun(client.url(url).addHttpHeaders(hc.headers: _*).withRequestTimeout(timeout)).map(new WSHttpResponse(_))) override def await[A](future: Future[A])(implicit timeout: FiniteDuration) = Await.result(future, timeout) }
Example 46
Source File: WireMockMethods.scala From vat-api with Apache License 2.0 | 5 votes |
package support import com.github.tomakehurst.wiremock.client.MappingBuilder import com.github.tomakehurst.wiremock.client.WireMock._ import com.github.tomakehurst.wiremock.matching.UrlPattern import com.github.tomakehurst.wiremock.stubbing.StubMapping import play.api.libs.json.Writes trait WireMockMethods { def when(method: HTTPMethod, uri: String, queryParams: Map[String, String] = Map.empty, headers: Map[String, String] = Map.empty): Mapping = { new Mapping(method, uri, queryParams, headers, None) } class Mapping(method: HTTPMethod, uri: String, queryParams: Map[String, String], headers: Map[String, String], body: Option[String]) { private val mapping = { val uriMapping = method.wireMockMapping(urlPathMatching(uri)) val uriMappingWithQueryParams = queryParams.foldLeft(uriMapping) { case (m, (key, value)) => m.withQueryParam(key, matching(value)) } val uriMappingWithHeaders = headers.foldLeft(uriMappingWithQueryParams) { case (m, (key, value)) => m.withHeader(key, equalTo(value)) } body match { case Some(extractedBody) => uriMappingWithHeaders.withRequestBody(equalTo(extractedBody)) case None => uriMappingWithHeaders } } def thenReturn[T](status: Int, body: T)(implicit writes: Writes[T]): StubMapping = { val stringBody = writes.writes(body).toString() thenReturnInternal(status, Map.empty, Some(stringBody)) } def thenReturn(status: Int, body: String): StubMapping = { thenReturnInternal(status, Map.empty, Some(body)) } def thenReturn(status: Int, headers: Map[String, String] = Map.empty): StubMapping = { thenReturnInternal(status, headers, None) } def thenReturnWithHeaders[T](status: Int, headers: Map[String, String] = Map.empty, body: T)(implicit writes: Writes[T]): StubMapping = { val stringBody = writes.writes(body).toString() thenReturnInternal(status, headers, Some(stringBody)) } private def thenReturnInternal(status: Int, headers: Map[String, String], body: Option[String]): StubMapping = { val response = { val statusResponse = aResponse().withStatus(status) val responseWithHeaders = headers.foldLeft(statusResponse) { case (res, (key, value)) => res.withHeader(key, value) } body match { case Some(extractedBody) => responseWithHeaders.withBody(extractedBody) case None => responseWithHeaders } } stubFor(mapping.willReturn(response)) } } sealed trait HTTPMethod { def wireMockMapping(pattern: UrlPattern): MappingBuilder } case object POST extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = post(pattern) } case object GET extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = get(pattern) } case object DELETE extends HTTPMethod { override def wireMockMapping(pattern: UrlPattern): MappingBuilder = delete(pattern) } }
Example 47
Source File: NRSConnector.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.connectors import java.util.concurrent.TimeoutException import javax.inject.Inject import play.api.Logger import play.api.libs.json.{JsValue, Json, Writes} import play.api.libs.ws.WSClient import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.http._ import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient import uk.gov.hmrc.vatapi.config.AppContext import uk.gov.hmrc.vatapi.httpparsers.EmptyNrsData import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.{NrsSubmissionOutcome, NrsSubmissionOutcomeReads} import uk.gov.hmrc.vatapi.models.NRSSubmission import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} import scala.util.{Success, Try} class NRSConnector @Inject()( override val http: DefaultHttpClient, override val appContext: AppContext, ws: WSClient ) extends BaseConnector { val logger: Logger = Logger(this.getClass) val nrsSubmissionUrl: String => String = vrn => s"${appContext.nrsServiceUrl}/submission" val nrsMaxTimeout: Duration = appContext.nrsMaxTimeoutMillis.milliseconds private val xApiKeyHeader = "X-API-Key" def submit(vrn: Vrn, nrsSubmission: NRSSubmission)(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[NrsSubmissionOutcome] = { logger.debug(s"[NRSConnector][submit] - Submission to NRS for 9 box vat return for VRN: $vrn") val nrsResponse = { val submitUrl = nrsSubmissionUrl(vrn.toString) val headers = hc.withExtraHeaders(xApiKeyHeader -> s"${appContext.xApiKey}", "User-Agent" -> appContext.appName).headers implicit val nrsWrites = implicitly[Writes[NRSSubmission]] ws.url(submitUrl) .withHttpHeaders(headers: _*) .withRequestTimeout(nrsMaxTimeout) .post(Json.toJson(nrsSubmission)) } nrsResponse.map { res => val resJson = Try(res.json) match { case Success(json: JsValue) => Some(json) case _ => None } val httpResponse = HttpResponse( res.status, resJson, res.headers, None ) Logger.debug(s"[NRSConnector][submit] - NRS Call succeeded") NrsSubmissionOutcomeReads.read("", "", httpResponse) }.recover { case e: TimeoutException => { logger.warn(s"[NRSConnector][submit] - NRS Call timed out for VRN: $vrn - $e") Right(EmptyNrsData) } } } }
Example 48
Source File: NrsSubmissionHttpParser.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.httpparsers import play.api.Logger import play.api.http.Status._ import play.api.libs.json.{Json, Reads, Writes, _} import uk.gov.hmrc.http.{HttpReads, HttpResponse} object NrsSubmissionHttpParser { val logger: Logger = Logger(this.getClass) type NrsSubmissionOutcome = Either[NrsSubmissionFailure, NRSData] implicit object NrsSubmissionOutcomeReads extends HttpReads[NrsSubmissionOutcome] { override def read(method: String, url: String, response: HttpResponse): NrsSubmissionOutcome = { logger.debug(s"[NrsSubmissionHttpParser][#reads] - Reading NRS Response") response.status match { case BAD_REQUEST => logger.warn(s"[NrsSubmissionHttpParser][#reads] - BAD_REQUEST status from NRS Response") Left(NrsError) case ACCEPTED => response.json.validate[NRSData].fold( invalid => { logger.warn(s"[NrsSubmissionHttpParser][#reads] - Error reading NRS Response: $invalid") Left(NrsError) }, valid => { logger.debug(s"[NrsSubmissionHttpParser][#reads] - Retrieved NRS Data: $valid") Right(valid) } ) case e => logger.debug(s"[NrsSubmissionHttpParser][#reads] - Retrieved NRS status : $e") Right(EmptyNrsData) } } } } sealed trait NrsSubmissionFailure case class NRSData(nrSubmissionId: String, cadesTSignature: String, timestamp: String ) object EmptyNrsData extends NRSData("", "This has been deprecated - DO NOT USE", "") object NRSData { implicit val writes: Writes[NRSData] = Json.writes[NRSData] implicit val reads: Reads[NRSData] = { (__ \ "nrSubmissionId").read[String].map { id => NRSData.apply(id, "This has been deprecated - DO NOT USE", "") } } } case object NrsError extends NrsSubmissionFailure
Example 49
Source File: AuditService.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.services import javax.inject.Inject import org.joda.time.{DateTime, DateTimeZone} import play.api.Logger import play.api.libs.json.{Json, Writes} import play.api.mvc.Request import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.play.audit.AuditExtensions import uk.gov.hmrc.play.audit.http.connector.AuditConnector import uk.gov.hmrc.play.audit.model.ExtendedDataEvent import uk.gov.hmrc.vatapi.models.audit.AuditEvent import uk.gov.hmrc.vatapi.resources.BusinessResult import scala.concurrent.ExecutionContext class AuditService @Inject()(auditConnector: AuditConnector) { val logger: Logger = Logger(this.getClass) def audit[T](event: AuditEvent[T])( implicit hc: HeaderCarrier, fmt: Writes[T], request: Request[_], ec: ExecutionContext ): BusinessResult[Unit] = { logger.debug(s"[AuditService][audit] Generating ${event.auditType} audit event for vat-api.") val auditEvent = ExtendedDataEvent( auditSource = "vat-api", auditType = event.auditType, tags = AuditExtensions.auditHeaderCarrier(hc).toAuditTags(event.transactionName, request.path), detail = Json.toJson(event.detail), generatedAt = DateTime.now(DateTimeZone.UTC) ) BusinessResult.success(auditConnector.sendExtendedEvent(auditEvent)) } }
Example 50
Source File: BaseDesConnector.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.connectors import config.AppConfig import play.api.Logger import play.api.libs.json.Writes import uk.gov.hmrc.http.logging.Authorization import uk.gov.hmrc.http.{HeaderCarrier, HttpReads} import uk.gov.hmrc.play.bootstrap.http.HttpClient import scala.concurrent.{ExecutionContext, Future} trait BaseDesConnector { val http: HttpClient val appConfig: AppConfig val logger = Logger(this.getClass) private[connectors] def desHeaderCarrier(implicit hc: HeaderCarrier): HeaderCarrier = hc.copy(authorization = Some(Authorization(s"Bearer ${appConfig.desToken}"))) .withExtraHeaders("Environment" -> appConfig.desEnv) private[connectors] def desPostHeaderCarrier(implicit hc: HeaderCarrier): HeaderCarrier = hc.copy(authorization = Some(Authorization(s"Bearer ${appConfig.desToken}"))) .withExtraHeaders("Environment" -> appConfig.desEnv, "Accept" -> "application/json", "OriginatorID" -> "MDTP") def post[Body: Writes, Resp](body: Body, uri: DesUri[Resp])(implicit ec: ExecutionContext, hc: HeaderCarrier, httpReads: HttpReads[DesOutcome[Resp]]): Future[DesOutcome[Resp]] = { def doPost(implicit hc: HeaderCarrier): Future[DesOutcome[Resp]] = { http.POST(s"${appConfig.desBaseUrl}/${uri.value}", body) } doPost(desPostHeaderCarrier(hc)) } def get[Resp](uri: DesUri[Resp])(implicit ec: ExecutionContext, hc: HeaderCarrier, httpReads: HttpReads[DesOutcome[Resp]]): Future[DesOutcome[Resp]] = { def doGet(implicit hc: HeaderCarrier): Future[DesOutcome[Resp]] = http.GET(s"${appConfig.desBaseUrl}/${uri.value}") doGet(desHeaderCarrier(hc)) } def get[Resp](uri: DesUri[Resp], queryParams: Seq[(String, String)])(implicit ec: ExecutionContext, hc: HeaderCarrier, httpReads: HttpReads[DesOutcome[Resp]]): Future[DesOutcome[Resp]] = { def doGet(implicit hc: HeaderCarrier): Future[DesOutcome[Resp]] = { http.GET(s"${appConfig.desBaseUrl}/${uri.value}", queryParams) } doGet(desHeaderCarrier(hc)) } }
Example 51
Source File: BaseNrsConnector.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.connectors import java.util.concurrent.TimeoutException import config.AppConfig import play.api.Logger import play.api.libs.json.{Json, Writes} import play.api.libs.ws.WSClient import uk.gov.hmrc.http.HeaderCarrier import v1.connectors.httpparsers.WsReads import scala.concurrent.{ExecutionContext, Future} trait BaseNrsConnector { val ws: WSClient val appConfig: AppConfig val logger = Logger(this.getClass) private[connectors] def nrsHeaderCarrier(implicit hc: HeaderCarrier): HeaderCarrier = hc.withExtraHeaders( "X-API-Key" -> appConfig.nrsApiKey, "User-Agent" -> appConfig.appName ) def nrsPost[Body: Writes, Resp](body: Body, uri: NrsUri[Resp], defaultResult: NrsOutcome[Resp])(implicit ec: ExecutionContext, hc: HeaderCarrier, wsReads: WsReads[NrsOutcome[Resp]]): Future[NrsOutcome[Resp]] = { def doPost(implicit hc: HeaderCarrier): Future[NrsOutcome[Resp]] = { ws.url(s"${appConfig.nrsBaseUrl}/${uri.value}") .withHttpHeaders(hc.headers: _*) .withRequestTimeout(appConfig.nrsMaxTimeout) .post(Json.toJson(body)) .map(wsReads.wsRead(_, defaultResult)).recover { case e: TimeoutException => logger.warn(s"[NrsConnector][nrsPost] - NRS Call timed out - $e") defaultResult } } doPost(nrsHeaderCarrier(hc)) } }
Example 52
Source File: AuditService.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.services import javax.inject.{Inject, Singleton} import play.api.libs.json.{Json, Writes} import play.api.{Configuration, Logger} import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.play.audit.AuditExtensions import uk.gov.hmrc.play.audit.http.connector.{AuditConnector, AuditResult} import uk.gov.hmrc.play.audit.model.ExtendedDataEvent import uk.gov.hmrc.play.bootstrap.config.AppName import v1.models.audit.AuditEvent import scala.concurrent.{ExecutionContext, Future} @Singleton class AuditService @Inject()(auditConnector: AuditConnector, appNameConfiguration: Configuration) { val logger: Logger = Logger(this.getClass) def auditEvent[T](event: AuditEvent[T])(implicit hc: HeaderCarrier, ec: ExecutionContext, writer: Writes[T]): Future[AuditResult] = { val eventTags = AuditExtensions.auditHeaderCarrier(hc).toAuditTags() + ("transactionName" -> event.transactionName) val dataEvent = ExtendedDataEvent( auditSource = AppName.fromConfiguration(appNameConfiguration), auditType = event.auditType, detail = Json.toJson(event.detail), tags = eventTags ) logger.info(s"Audit event :- dataEvent.tags :: ${dataEvent.tags} -- auditSource:: ${dataEvent.auditSource}" + s" --- detail :: ${dataEvent.detail}") auditConnector.sendExtendedEvent(dataEvent) } }
Example 53
Source File: ErrorWrapper.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.models.errors import play.api.libs.json.{JsObject, JsValue, Json, Writes} import v1.models.audit.AuditError case class ErrorWrapper(correlationId: Option[String], error: MtdError, errors: Option[Seq[MtdError]] = None) { private def allErrors: Seq[MtdError] = errors match { case Some(seq) => seq case None => Seq(error) } def auditErrors: Seq[AuditError] = allErrors.map(error => AuditError(error.code)) } object ErrorWrapper { val allErrors: Seq[MtdError] => Seq[JsValue] = { case mtdError :: Nil => mtdErrors(mtdError) case mtdError :: rest => mtdErrors(mtdError) ++ allErrors(rest) } private val mtdErrors : MtdError => Seq[JsValue] = { case MtdError(_, _, Some(customJson)) => customJson.asOpt[MtdErrorWrapper] match { case Some(e) => mtdErrorWrapper(e) case _ => Seq(customJson) } case _@o => Seq(Json.toJson(o)) } private val mtdErrorWrapper: MtdErrorWrapper => Seq[JsValue]= wrapper => wrapper.errors match { case Some(errors) if errors.nonEmpty => errors.map(error => Json.toJson(error)) case _ => Seq(Json.toJson(wrapper)) } implicit val writes: Writes[ErrorWrapper] = (errorResponse: ErrorWrapper) => { val singleJson: JsObject = Json.toJson(errorResponse.error).as[JsObject] errorResponse.errors match { case Some(errors) if errors.nonEmpty => singleJson + ("errors" -> Json.toJson(allErrors(errors))) case _ => singleJson } } }
Example 54
Source File: MockAuditService.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.mocks.services import org.scalamock.handlers.CallHandler import org.scalamock.scalatest.MockFactory import play.api.libs.json.Writes import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.play.audit.http.connector.AuditResult import v1.models.audit.AuditEvent import v1.services.AuditService import scala.concurrent.{ExecutionContext, Future} trait MockAuditService extends MockFactory { val mockAuditService: AuditService = stub[AuditService] object MockedAuditService { def verifyAuditEvent[T](event: AuditEvent[T]): CallHandler[Future[AuditResult]] = { (mockAuditService.auditEvent(_: AuditEvent[T])(_: HeaderCarrier, _: ExecutionContext, _: Writes[T])) .verify(event, *, *, *) .returning(Future.successful(AuditResult.Success)) } } }
Example 55
Source File: StatePensionConnector.scala From nisp-frontend with Apache License 2.0 | 5 votes |
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 56
Source File: PublicKey.scala From matcher with MIT License | 5 votes |
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 57
Source File: KeyPair.scala From matcher with MIT License | 5 votes |
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 58
Source File: package.scala From matcher with MIT License | 5 votes |
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 59
Source File: HttpOrderStatus.scala From matcher with MIT License | 5 votes |
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 60
Source File: ExactCounterItem.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.rest.play.models import play.api.libs.json.{Json, Writes} case class ExactCounterItem(ts: Long, count: Long, score: Double) case class ExactCounterIntervalItem(interval: String, dimension: Map[String, String], counter: Seq[ExactCounterItem]) case class ExactCounterResultMeta(service: String, action: String, item: String) case class ExactCounterResult(meta: ExactCounterResultMeta, data: Seq[ExactCounterIntervalItem]) object ExactCounterItem { implicit val writes = new Writes[ExactCounterItem] { def writes(item: ExactCounterItem) = Json.obj( "ts" -> item.ts, "time" -> tsFormat.format(item.ts), "count" -> item.count, "score" -> item.score ) } implicit val reads = Json.reads[ExactCounterItem] } object ExactCounterIntervalItem { implicit val format = Json.format[ExactCounterIntervalItem] } object ExactCounterResultMeta { implicit val format = Json.format[ExactCounterResultMeta] } object ExactCounterResult { implicit val formats = Json.format[ExactCounterResult] }
Example 61
Source File: RankCounterItem.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.rest.play.models import play.api.libs.json.{Json, Writes} case class RankCounterItem(rank: Int, id: String, score: Double) case class RankCounterDimensionItem(interval: String, ts: Long, dimension: String, total: Double, ranks: Seq[RankCounterItem]) case class RankCounterResultMeta(service: String, action: String) case class RankCounterResult(meta: RankCounterResultMeta, data: Seq[RankCounterDimensionItem]) object RankCounterItem { implicit val format = Json.format[RankCounterItem] } object RankCounterDimensionItem { implicit val writes = new Writes[RankCounterDimensionItem] { def writes(item: RankCounterDimensionItem) = Json.obj( "interval" -> item.interval, "ts" -> item.ts, "time" -> tsFormat.format(item.ts), "dimension" -> item.dimension, "total" -> item.total, "ranks" -> item.ranks ) } implicit val reads = Json.reads[RankCounterDimensionItem] } object RankCounterResultMeta { implicit val format = Json.format[RankCounterResultMeta] } object RankCounterResult { implicit val format = Json.format[RankCounterResult] }
Example 62
Source File: AddressJourneyCachingHelper.scala From pertax-frontend with Apache License 2.0 | 5 votes |
package controllers.controllershelpers import com.google.inject.{Inject, Singleton} import controllers.bindable.AddrType import controllers.routes import models.{AddressFinderDtoId, AddressJourneyData, AddressPageVisitedDtoId, CacheIdentifier, SelectedAddressRecordId, SelectedRecordSetId, SubmittedAddressDtoId, SubmittedInternationalAddressChoiceId, SubmittedResidencyChoiceDtoId, SubmittedStartDateId, SubmittedTaxCreditsChoiceId} import models.addresslookup.{AddressRecord, RecordSet} import models.dto._ import play.api.libs.json.Writes import play.api.mvc.{Result, Results} import services.LocalSessionCache import uk.gov.hmrc.http.cache.client.CacheMap import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import scala.concurrent.{ExecutionContext, Future} @Singleton class AddressJourneyCachingHelper @Inject()(val sessionCache: LocalSessionCache)(implicit ec: ExecutionContext) extends Results { val addressLookupServiceDownKey = "addressLookupServiceDown" def addToCache[A: Writes](id: CacheIdentifier[A], record: A)(implicit hc: HeaderCarrier): Future[CacheMap] = sessionCache.cache(id.id, record) def cacheAddressLookupServiceDown()(implicit hc: HeaderCarrier): Future[CacheMap] = sessionCache.cache(addressLookupServiceDownKey, true) def clearCache()(implicit hc: HeaderCarrier): Future[HttpResponse] = sessionCache.remove() def gettingCachedAddressPageVisitedDto[T](block: Option[AddressPageVisitedDto] => Future[T])( implicit hc: HeaderCarrier): Future[T] = sessionCache.fetch() flatMap { case Some(cacheMap) => block(cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id)) case None => block(None) } def gettingCachedAddressLookupServiceDown[T](block: Option[Boolean] => T)(implicit hc: HeaderCarrier): Future[T] = sessionCache.fetch() map { cacheMap => { block(cacheMap.flatMap(_.getEntry[Boolean](addressLookupServiceDownKey))) } } def gettingCachedTaxCreditsChoiceDto[T](block: Option[TaxCreditsChoiceDto] => T)( implicit hc: HeaderCarrier): Future[T] = sessionCache.fetch() map { cacheMap => { block(cacheMap.flatMap(_.getEntry[TaxCreditsChoiceDto](SubmittedTaxCreditsChoiceId.id))) } } def gettingCachedJourneyData[T](typ: AddrType)(block: AddressJourneyData => Future[T])( implicit hc: HeaderCarrier): Future[T] = sessionCache.fetch() flatMap { case Some(cacheMap) => block( AddressJourneyData( cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id), cacheMap.getEntry[ResidencyChoiceDto](SubmittedResidencyChoiceDtoId(typ).id), cacheMap.getEntry[RecordSet](SelectedRecordSetId(typ).id), cacheMap.getEntry[AddressFinderDto](AddressFinderDtoId(typ).id), cacheMap.getEntry[AddressRecord](SelectedAddressRecordId(typ).id), cacheMap.getEntry[AddressDto](SubmittedAddressDtoId(typ).id), cacheMap.getEntry[InternationalAddressChoiceDto](SubmittedInternationalAddressChoiceId.id), cacheMap.getEntry[DateDto](SubmittedStartDateId(typ).id), cacheMap.getEntry[Boolean](addressLookupServiceDownKey).getOrElse(false) ) ) case None => block(AddressJourneyData(None, None, None, None, None, None, None, None, addressLookupServiceDown = false)) } def enforceDisplayAddressPageVisited(addressPageVisitedDto: Option[AddressPageVisitedDto])(block: => Future[Result])( implicit hc: HeaderCarrier): Future[Result] = addressPageVisitedDto match { case Some(_) => block case None => Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad())) } def enforceResidencyChoiceSubmitted(journeyData: AddressJourneyData)( block: AddressJourneyData => Future[Result]): Future[Result] = journeyData match { case AddressJourneyData(_, Some(_), _, _, _, _, _, _, _) => block(journeyData) case AddressJourneyData(_, None, _, _, _, _, _, _, _) => Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad())) } }
Example 63
Source File: SimpleHttp.scala From pertax-frontend with Apache License 2.0 | 5 votes |
package services.http import com.google.inject.{Inject, Singleton} import play.api.libs.json.Writes import uk.gov.hmrc.http.{HeaderCarrier, HttpReads, HttpResponse} import uk.gov.hmrc.play.bootstrap.http.HttpClient import scala.concurrent.{ExecutionContext, Future} @Singleton class SimpleHttp @Inject()(http: HttpClient)(implicit executionContext: ExecutionContext) { implicit val r = new HttpReads[HttpResponse] { override def read(method: String, url: String, response: HttpResponse): HttpResponse = response } def get[T](url: String)(onComplete: HttpResponse => T, onError: Exception => T)( implicit hc: HeaderCarrier): Future[T] = http.GET[HttpResponse](url) map { response => onComplete(response) } recover { case e: Exception => onError(e) } def post[I, T](url: String, body: I)(onComplete: HttpResponse => T, onError: Exception => T)( implicit hc: HeaderCarrier, w: Writes[I]): Future[T] = http.POST[I, HttpResponse](url, body) map { response => onComplete(response) } recover { case e: Exception => onError(e) } def put[I, T](url: String, body: I)(onComplete: HttpResponse => T, onError: Exception => T)( implicit hc: HeaderCarrier, w: Writes[I]): Future[T] = http.PUT[I, HttpResponse](url, body) map { response => onComplete(response) } recover { case e: Exception => onError(e) } }
Example 64
Source File: IsCompleteReply.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.{KernelMessageContent} import play.api.libs.json.{Json, Reads, Writes} case class IsCompleteReply ( status: String, indent: String ) extends KernelMessageContent { override def content : String = Json.toJson(this)(IsCompleteReply.isCompleteReplyWrites).toString } object IsCompleteReply extends TypeString { implicit val isCompleteReplyReads: Reads[IsCompleteReply] = Json.reads[IsCompleteReply] implicit val isCompleteReplyWrites: Writes[IsCompleteReply] = Json.writes[IsCompleteReply] override def toTypeString: String = "complete_reply" }
Example 65
Source File: WSPatch.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.http.ws.default import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.{CorePatch, HeaderCarrier, HttpResponse, PatchHttpTransport} import uk.gov.hmrc.play.http.ws.{WSExecute, WSHttpResponse, WSRequestBuilder} import scala.concurrent.{ExecutionContext, Future} trait WSPatch extends CorePatch with PatchHttpTransport with WSRequestBuilder with WSExecute { override def doPatch[A]( url: String, body: A, headers: Seq[(String, String)])( implicit rds: Writes[A], hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = execute(buildRequest(url, headers).withBody(Json.toJson(body)), "PATCH") .map(WSHttpResponse.apply) }
Example 66
Source File: HttpPut.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.HttpVerbs.{PUT => PUT_VERB} import uk.gov.hmrc.http.hooks.{HookData, HttpHooks} import uk.gov.hmrc.http.logging.ConnectionTracing import scala.concurrent.{ExecutionContext, Future} trait HttpPut extends CorePut with PutHttpTransport with HttpVerb with ConnectionTracing with HttpHooks with Retries { override def PUT[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(PUT_VERB, url) { val httpResponse = retry(PUT_VERB, url)(doPut(url, body, headers)) executeHooks(url, PUT_VERB, Option(HookData.FromString(Json.stringify(wts.writes(body)))), httpResponse) mapErrors(PUT_VERB, url, httpResponse).map(response => rds.read(PUT_VERB, url, response)) } override def PUTString[O]( url: String, body: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(PUT_VERB, url) { val httpResponse = retry(PUT_VERB, url)(doPutString(url, body, headers)) executeHooks(url, PUT_VERB, Option(HookData.FromString(body)), httpResponse) mapErrors(PUT_VERB, url, httpResponse).map(rds.read(PUT_VERB, url, _)) } }
Example 67
Source File: HttpPatch.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.HttpVerbs.{PATCH => PATCH_VERB} import uk.gov.hmrc.http.hooks.{HookData, HttpHooks} import uk.gov.hmrc.http.logging.ConnectionTracing import scala.concurrent.{ExecutionContext, Future} trait HttpPatch extends CorePatch with PatchHttpTransport with HttpVerb with ConnectionTracing with HttpHooks with Retries { override def PATCH[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(PATCH_VERB, url) { val httpResponse = retry(PATCH_VERB, url)(doPatch(url, body, headers)) executeHooks(url, PATCH_VERB, Option(HookData.FromString(Json.stringify(wts.writes(body)))), httpResponse) mapErrors(PATCH_VERB, url, httpResponse).map(response => rds.read(PATCH_VERB, url, response)) } }
Example 68
Source File: HttpPost.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http.HttpVerbs.{POST => POST_VERB} import uk.gov.hmrc.http.hooks.{HookData, HttpHooks} import uk.gov.hmrc.http.logging.ConnectionTracing import scala.concurrent.{ExecutionContext, Future} trait HttpPost extends CorePost with PostHttpTransport with HttpVerb with ConnectionTracing with HttpHooks with Retries { override def POST[I, O]( url: String, body: I, headers: Seq[(String, String)])( implicit wts: Writes[I], rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(POST_VERB, url) { val httpResponse = retry(POST_VERB, url)(doPost(url, body, headers)) executeHooks(url, POST_VERB, Option(HookData.FromString(Json.stringify(wts.writes(body)))), httpResponse) mapErrors(POST_VERB, url, httpResponse).map(rds.read(POST_VERB, url, _)) } override def POSTString[O]( url: String, body: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(POST_VERB, url) { val httpResponse = retry(POST_VERB, url)(doPostString(url, body, headers)) executeHooks(url, POST_VERB, Option(HookData.FromString(body)), httpResponse) mapErrors(POST_VERB, url, httpResponse).map(rds.read(POST_VERB, url, _)) } override def POSTForm[O]( url: String, body: Map[String, Seq[String]], headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(POST_VERB, url) { val httpResponse = retry(POST_VERB, url)(doFormPost(url, body, headers)) executeHooks(url, POST_VERB, Option(HookData.FromMap(body)), httpResponse) mapErrors(POST_VERB, url, httpResponse).map(rds.read(POST_VERB, url, _)) } override def POSTEmpty[O]( url: String, headers: Seq[(String, String)])( implicit rds: HttpReads[O], hc: HeaderCarrier, ec: ExecutionContext): Future[O] = withTracing(POST_VERB, url) { val httpResponse = retry(POST_VERB, url)(doEmptyPost(url, headers)) executeHooks(url, POST_VERB, None, httpResponse) mapErrors(POST_VERB, url, httpResponse).map(rds.read(POST_VERB, url, _)) } }
Example 69
Source File: AccessTokenResponse.scala From OAuth2-mock-play with MIT License | 5 votes |
package models import play.api.libs.json.{Json, Writes} import scala.concurrent.duration.FiniteDuration case class AccessTokenResponse(accessToken: String, expiresIn: FiniteDuration, scope: List[String], grantType: GrantType, realm: String, tokenType: TokenType) object AccessTokenResponse { implicit val accessTokenResponseWrites: Writes[AccessTokenResponse] = Writes( (accessTokenResponse: AccessTokenResponse) => Json.obj( "access_token" -> accessTokenResponse.accessToken, "expires_in" -> accessTokenResponse.expiresIn.toSeconds, "scope" -> accessTokenResponse.scope, "grant_type" -> accessTokenResponse.grantType.id, "token_type" -> accessTokenResponse.tokenType.id, "realm" -> accessTokenResponse.realm )) }
Example 70
Source File: TokeninfoResponse.scala From OAuth2-mock-play with MIT License | 5 votes |
package models import play.api.libs.json.{Json, Writes} import scala.concurrent.duration.FiniteDuration case class TokeninfoResponse(accessToken: String, grantType: GrantType, expiresIn: FiniteDuration, tokenType: TokenType, realm: String, uid: String, scope: List[String]) object TokeninfoResponse { implicit val tokeninfoResponseWrites: Writes[TokeninfoResponse] = Writes( (tokeninfoResponse: TokeninfoResponse) => Json.obj( "access_token" -> tokeninfoResponse.accessToken, "grant_type" -> tokeninfoResponse.grantType.id, "expires_in" -> tokeninfoResponse.expiresIn.toSeconds, "scope" -> tokeninfoResponse.scope, "realm" -> tokeninfoResponse.realm, "token_type" -> tokeninfoResponse.tokenType.id, "uid" -> tokeninfoResponse.uid ) ) }
Example 71
Source File: KafkaService.scala From ws_to_kafka with MIT License | 5 votes |
package com.pkinsky import akka.actor.ActorSystem import akka.stream.scaladsl.{Source, Flow, Sink} import com.softwaremill.react.kafka.{ConsumerProperties, ProducerProperties, ProducerMessage, ReactiveKafka} import org.apache.kafka.common.serialization.{Deserializer, Serializer} import play.api.libs.json.{Json, Reads, Writes} case class KafkaServiceConf(bootstrapServers: String) class KafkaService(kafkaClient: ReactiveKafka, conf: KafkaServiceConf) { def consume[T](topic: String, groupId: String)(implicit writes: Reads[T], actorSystem: ActorSystem): Source[T, Unit] = Source.fromPublisher(kafkaClient.consume( ConsumerProperties( bootstrapServers = conf.bootstrapServers, // IP and port of local Kafka instance topic = topic, // topic to consume messages from groupId = groupId, // consumer group valueDeserializer = KafkaService.deserializer[T] ) )).map(_.value()) } object KafkaService { def serializer[T: Writes] = new Serializer[T] { override def serialize(topic: String, data: T): Array[Byte] = { val js = Json.toJson(data) js.toString().getBytes("UTF-8") } override def configure(configs: java.util.Map[String, _], isKey: Boolean): Unit = () override def close(): Unit = () } def deserializer[T: Reads] = new Deserializer[T] { override def deserialize(topic: String, data: Array[Byte]): T = { val s = new String(data, "UTF-8") Json.fromJson(Json.parse(s)).get //throw exception on error ¯\_(ツ)_/¯ (consider returning JsResult[T]) } override def configure(configs: java.util.Map[String, _], isKey: Boolean): Unit = () override def close(): Unit = () } }
Example 72
Source File: MockHttp.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package mocks import org.mockito.stubbing.OngoingStubbing import org.scalatest.Suite import play.api.libs.json.Writes import uk.gov.hmrc.http.{HeaderCarrier, HttpReads} import uk.gov.hmrc.play.bootstrap.http.HttpClient import scala.concurrent.{ExecutionContext, Future} trait MockHttp extends Mock { _: Suite => val mockHttp: HttpClient = mock[HttpClient] override protected def beforeEach(): Unit = { super.beforeEach() reset(mockHttp) } object MockHttp { def GET[T](url: String): OngoingStubbing[Future[T]] = { when(mockHttp.GET[T](eqTo(url))(any[HttpReads[T]](), any[HeaderCarrier](), any[ExecutionContext]())) } def POST[I, O](url: String, body: I, headers: (String, String)*): OngoingStubbing[Future[O]] = { when(mockHttp.POST[I, O](eqTo(url), eqTo(body), eqTo(headers))(any[Writes[I]](), any[HttpReads[O]](), any[HeaderCarrier](), any[ExecutionContext]())) } def POSTEmpty[O](url: String, headers: (String, String)*): OngoingStubbing[Future[O]] = { when(mockHttp.POSTEmpty[O](eqTo(url), any[Seq[(String,String)]])(any[HttpReads[O]](), any[HeaderCarrier](), any[ExecutionContext]())) } def POST[I, O](url: String, body: I): OngoingStubbing[Future[O]] = { when(mockHttp.POST[I, O](eqTo(url), eqTo(body), any[Seq[(String,String)]]())(any[Writes[I]](), any[HttpReads[O]](), any[HeaderCarrier](), any[ExecutionContext]())) } def PUT[I, O](url: String, body: I): OngoingStubbing[Future[O]] = { when(mockHttp.PUT[I, O](eqTo(url), eqTo(body), any[Seq[(String,String)]])(any[Writes[I]](), any[HttpReads[O]](), any[HeaderCarrier](), any[ExecutionContext]())) } } }
Example 73
Source File: IsCompleteRequest.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.KernelMessageContent import play.api.libs.json.{Json, Reads, Writes} case class IsCompleteRequest( code: String ) extends KernelMessageContent { override def content : String = Json.toJson(this)(IsCompleteRequest.isCompleteRequestWrites).toString } object IsCompleteRequest extends TypeString { implicit val isCompleteRequestReads: Reads[IsCompleteRequest] = Json.reads[IsCompleteRequest] implicit val isCompleteRequestWrites: Writes[IsCompleteRequest] = Json.writes[IsCompleteRequest] override def toTypeString: String = "is_complete_request" }
Example 74
Source File: SelfAssessmentUserType.scala From pertax-frontend with Apache License 2.0 | 5 votes |
package models import play.api.libs.json.{JsDefined, JsError, JsResult, JsString, JsSuccess, JsValue, Json, Reads, Writes} import uk.gov.hmrc.domain.SaUtr sealed trait SelfAssessmentUserType sealed trait SelfAssessmentUser extends SelfAssessmentUserType { def saUtr: SaUtr } object SelfAssessmentUserType { val cacheId = "SelfAssessmentUser" val activatedSa = ActivatedOnlineFilerSelfAssessmentUser.toString val notActivatedSa = NotYetActivatedOnlineFilerSelfAssessmentUser.toString val wrongCredsSa = WrongCredentialsSelfAssessmentUser.toString val notEnrolledSa = NotEnrolledSelfAssessmentUser.toString val nonFilerSa = NonFilerSelfAssessmentUser.toString implicit val writes = new Writes[SelfAssessmentUserType] { override def writes(o: SelfAssessmentUserType): JsValue = o match { case ActivatedOnlineFilerSelfAssessmentUser(utr) => Json.obj("_type" -> JsString(activatedSa), "utr" -> JsString(utr.toString)) case NotYetActivatedOnlineFilerSelfAssessmentUser(utr) => Json.obj("_type" -> JsString(notActivatedSa), "utr" -> JsString(utr.toString)) case WrongCredentialsSelfAssessmentUser(utr) => Json.obj("_type" -> JsString(wrongCredsSa), "utr" -> JsString(utr.toString)) case NotEnrolledSelfAssessmentUser(utr) => Json.obj("_type" -> JsString(notEnrolledSa), "utr" -> JsString(utr.toString)) case NonFilerSelfAssessmentUser => Json.obj("_type" -> JsString(nonFilerSa)) } } implicit val reads = new Reads[SelfAssessmentUserType] { override def reads(json: JsValue): JsResult[SelfAssessmentUserType] = (json \ "_type", json \ "utr") match { case (JsDefined(JsString(`activatedSa`)), JsDefined(JsString(utr))) => JsSuccess(ActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr))) case (JsDefined(JsString(`notActivatedSa`)), JsDefined(JsString(utr))) => JsSuccess(NotYetActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr))) case (JsDefined(JsString(`wrongCredsSa`)), JsDefined(JsString(utr))) => JsSuccess(WrongCredentialsSelfAssessmentUser(SaUtr(utr))) case (JsDefined(JsString(`notEnrolledSa`)), JsDefined(JsString(utr))) => JsSuccess(NotEnrolledSelfAssessmentUser(SaUtr(utr))) case (JsDefined(JsString(`nonFilerSa`)), _) => JsSuccess(NonFilerSelfAssessmentUser) case _ => JsError("Could not read SelfAssessmentUserType") } } } case class ActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser case class NotYetActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser case class WrongCredentialsSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser case class NotEnrolledSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser case object NonFilerSelfAssessmentUser extends SelfAssessmentUserType
Example 75
Source File: package.scala From play-json-schema-validator with Apache License 2.0 | 5 votes |
package com.eclipsesource.schema.internal import com.eclipsesource.schema.SchemaType import com.osinka.i18n.Lang import play.api.libs.json.{JsValue, Json, JsonValidationError, Writes} package object refs { implicit class ResolveResultExtensionOps(resolvedResult: ResolvedResult) { def toJson(implicit writes: Writes[SchemaType]): JsValue = Json.toJson(resolvedResult.resolved) } implicit class SchemaRefResolverExtensionOps(resolver: SchemaRefResolver) { def resolveFromRoot(ref: String, scope: SchemaResolutionScope) (implicit lang: Lang = Lang.Default): Either[JsonValidationError, ResolvedResult] = { resolver.resolve(scope.documentRoot, Ref(ref), scope).toEither } } }
Example 76
Source File: SchemaWrites7.scala From play-json-schema-validator with Apache License 2.0 | 5 votes |
package com.eclipsesource.schema.internal.draft7 import com.eclipsesource.schema.internal.Keywords import com.eclipsesource.schema.internal.constraints.Constraints._ import com.eclipsesource.schema.internal.draft7.constraints._ import com.eclipsesource.schema.internal.serialization.SchemaWrites import com.eclipsesource.schema.{SchemaArray, SchemaInteger, SchemaNumber, SchemaObject, SchemaRoot, SchemaString, SchemaTuple, SchemaVersion} import play.api.libs.json.{Json, OWrites, Writes} trait SchemaWrites7 extends SchemaWrites { self: SchemaVersion => lazy val anyConstraintWrites: OWrites[AnyConstraints] = { case AnyConstraints7(schemaTypeAsString, allOf, anyOf, oneOf, definitions, enum, const, not, desc, id, _if, _then, _else) => asJsObject(Keywords.Any.Type, schemaTypeAsString) ++ asJsObject("$id", id) ++ asJsObject(Keywords.Any.AllOf, allOf) ++ asJsObject(Keywords.Any.AnyOf, anyOf) ++ asJsObject(Keywords.Any.OneOf, oneOf) ++ asJsObject(Keywords.Any.Definitions, definitions) ++ asJsObject(Keywords.Any.Enum, enum) ++ asJsObject("const", const) ++ asJsObject(Keywords.Any.Description, desc) ++ asJsObject(Keywords.Any.Not, not) ++ asJsObject(Keywords.Any.If, _if) ++ asJsObject(Keywords.Any.Then, _then) ++ asJsObject(Keywords.Any.Else, _else) } override lazy val rootWrites: Writes[SchemaRoot] = Default.rootWrites override lazy val objectWrites: OWrites[SchemaObject] = Default.objectWrites(objectConstraintWrites) override lazy val stringWrites: OWrites[SchemaString] = Default.stringWrites(stringConstraintWrites) override lazy val integerWrites: OWrites[SchemaInteger] = Default.integerWrites(numberConstraintWrites) override lazy val numberWrites: OWrites[SchemaNumber] = Default.numberWrites(numberConstraintWrites) override lazy val arrayWrites: OWrites[SchemaArray] = Default.arrayWrites(arrayConstraintWrites) override lazy val tupleWrites: OWrites[SchemaTuple] = Default.tupleWrites(arrayConstraintWrites) lazy val objectConstraintWrites: OWrites[ObjectConstraints] = OWrites[ObjectConstraints] { case ObjectConstraints7(additionalProps, dependencies, patternProps, required, minProperties, maxProperties, propertyNames, any) => asJsObject(Keywords.Object.AdditionalProperties, additionalProps) ++ asJsObject(Keywords.Object.Dependencies, dependencies) ++ asJsObject(Keywords.Object.MaxProperties,maxProperties) ++ asJsObject(Keywords.Object.MinProperties, minProperties) ++ asJsObject(Keywords.Object.PatternProperties, patternProps) ++ asJsObject(Keywords.Object.PropertyNames, propertyNames) ++ asJsObject(Keywords.Object.Required, required) ++ anyConstraintWrites.writes(any) } lazy val arrayConstraintWrites: OWrites[ArrayConstraints] = { case ArrayConstraints7(maxItems, minItems, additionalItems, contains, unique, any) => asJsObject(Keywords.Array.AdditionalItems, additionalItems) ++ asJsObject(Keywords.Array.MaxItems, maxItems) ++ asJsObject(Keywords.Array.MinItems, minItems) ++ asJsObject(Keywords.Array.Contains, contains) ++ asJsObject(Keywords.Array.UniqueItems, unique) ++ anyConstraintWrites.writes(any) } lazy val numberConstraintWrites: OWrites[NumberConstraints] = { case NumberConstraints7(min, max, multipleOf, format, any) => max.fold(emptyJsonObject)(max => max.isExclusive match { case Some(_) => Json.obj(Keywords.Number.ExclusiveMax -> max.max) case _ => Json.obj(Keywords.Number.Max -> max.max) }) ++ min.fold(emptyJsonObject)(min => min.isExclusive match { case Some(_) => Json.obj(Keywords.Number.ExclusiveMin -> min.min) case _ => Json.obj(Keywords.Number.Min -> min.min) }) ++ multipleOf.fold(emptyJsonObject)(multipleOf => Json.obj(Keywords.Number.MultipleOf -> multipleOf) ) ++ anyConstraintWrites.writes(any) ++ format.fold(emptyJsonObject)(formatName => Json.obj(Keywords.String.Format -> formatName) ) } lazy val stringConstraintWrites: OWrites[StringConstraints] = { case StringConstraints7(minLength, maxLength, pattern, format, any) => asJsObject(Keywords.String.MinLength, minLength) ++ asJsObject(Keywords.String.MaxLength, maxLength) ++ asJsObject(Keywords.String.Pattern, pattern) ++ asJsObject(Keywords.String.Format, format) ++ anyConstraintWrites.writes(any) } }
Example 77
Source File: SchemaWrites4.scala From play-json-schema-validator with Apache License 2.0 | 5 votes |
package com.eclipsesource.schema.internal.draft4 import com.eclipsesource.schema.{SchemaArray, SchemaInteger, SchemaNumber, SchemaObject, SchemaRoot, SchemaString, SchemaTuple, SchemaVersion} import com.eclipsesource.schema.internal.Keywords import com.eclipsesource.schema.internal.constraints.Constraints._ import com.eclipsesource.schema.internal.draft4.constraints._ import com.eclipsesource.schema.internal.serialization.SchemaWrites import play.api.libs.json.{Json, OWrites, Writes} trait SchemaWrites4 extends SchemaWrites { self: SchemaVersion => lazy val anyConstraintWrites: OWrites[AnyConstraints] = { case AnyConstraints4(schemaTypeAsString, allOf, anyOf, oneOf, definitions, enum, not, desc, id) => asJsObject(Keywords.Any.Type, schemaTypeAsString) ++ asJsObject("id", id) ++ asJsObject(Keywords.Any.AllOf, allOf) ++ asJsObject(Keywords.Any.AnyOf, anyOf) ++ asJsObject(Keywords.Any.OneOf, oneOf) ++ asJsObject(Keywords.Any.Definitions, definitions) ++ asJsObject(Keywords.Any.Enum, enum) ++ asJsObject(Keywords.Any.Description, desc) ++ asJsObject(Keywords.Any.Not, not) } override lazy val rootWrites: Writes[SchemaRoot] = Default.rootWrites override lazy val objectWrites: OWrites[SchemaObject] = Default.objectWrites(objectConstraintWrites) override lazy val stringWrites: OWrites[SchemaString] = Default.stringWrites(stringConstraintWrites) override lazy val integerWrites: OWrites[SchemaInteger] = Default.integerWrites(numberConstraintWrites) override lazy val numberWrites: OWrites[SchemaNumber] = Default.numberWrites(numberConstraintWrites) override lazy val arrayWrites: OWrites[SchemaArray] = Default.arrayWrites(arrayConstraintWrites) override lazy val tupleWrites: OWrites[SchemaTuple] = Default.tupleWrites(arrayConstraintWrites) lazy val objectConstraintWrites: OWrites[ObjectConstraints] = { case ObjectConstraints4(additionalProps, dependencies, maxProperties, minProperties, patternProps, required, any) => asJsObject(Keywords.Object.AdditionalProperties, additionalProps) ++ asJsObject(Keywords.Object.Dependencies, dependencies) ++ asJsObject(Keywords.Object.MaxProperties, maxProperties) ++ asJsObject(Keywords.Object.MinProperties, minProperties) ++ asJsObject(Keywords.Object.PatternProperties, patternProps) ++ asJsObject(Keywords.Object.Required, required) ++ anyConstraintWrites.writes(any) } lazy val arrayConstraintWrites: OWrites[ArrayConstraints] = { case ArrayConstraints4(maxItems, minItems, additionalItems, unique, any) => asJsObject(Keywords.Array.AdditionalItems, additionalItems) ++ asJsObject(Keywords.Array.MaxItems, maxItems) ++ asJsObject(Keywords.Array.MinItems, minItems) ++ asJsObject(Keywords.Array.UniqueItems, unique) ++ anyConstraintWrites.writes(any) } lazy val stringConstraintWrites: OWrites[StringConstraints] = { case StringConstraints4(minLength, maxLength, pattern, format, any) => asJsObject(Keywords.String.MinLength, minLength) ++ asJsObject(Keywords.String.MaxLength, maxLength) ++ asJsObject(Keywords.String.Pattern, pattern) ++ asJsObject(Keywords.String.Format, format) ++ anyConstraintWrites.writes(any) } lazy val numberConstraintWrites: OWrites[NumberConstraints] = { case NumberConstraints4(min, max, multipleOf, format, any) => Json.obj() max.fold(emptyJsonObject)(max => max.isExclusive match { case Some(isExclusive) => Json.obj(Keywords.Number.Max -> max.max, Keywords.Number.ExclusiveMax -> isExclusive) case _ => Json.obj(Keywords.Number.Max -> max.max) }) ++ min.fold(emptyJsonObject)(min => min.isExclusive match { case Some(isExclusive) => Json.obj(Keywords.Number.Min -> min.min, Keywords.Number.ExclusiveMin -> isExclusive) case _ => Json.obj(Keywords.Number.Min -> min.min) }) ++ multipleOf.fold(emptyJsonObject)(multipleOf => Json.obj(Keywords.Number.MultipleOf -> multipleOf) ) ++ anyConstraintWrites.writes(any) ++ format.fold(emptyJsonObject)(formatName => Json.obj(Keywords.String.Format -> formatName) ) } }
Example 78
Source File: PlayDefinitions.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
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 79
Source File: HelloWorldController.scala From playsonify with MIT License | 5 votes |
package controllers import javax.inject.Inject import com.alexitc.example.UserError import controllers.common.{MyJsonController, MyJsonControllerComponents} import org.scalactic.{Bad, Every, Good} import play.api.libs.json.{Json, Reads, Writes} import scala.concurrent.Future class HelloWorldController @Inject() (components: MyJsonControllerComponents) extends MyJsonController(components) { import Context._ def hello = publicInput { context: HasModel[Person] => val msg = s"Hello ${context.model.name}, you are ${context.model.age} years old" val helloMessage = HelloMessage(msg) val goodResult = Good(helloMessage) Future.successful(goodResult) } def authenticatedHello = authenticated { context: Authenticated => val msg = s"Hello user with id ${context.auth}" val helloMessage = HelloMessage(msg) val goodResult = Good(helloMessage) Future.successful(goodResult) } def failedHello = public[HelloMessage] { context: Context => val errors = Every( UserError.UserEmailIncorrect, UserError.UserAlreadyExist, UserError.UserNotFound) val badResult = Bad(errors) Future.successful(badResult) } def exceptionHello = public[HelloMessage] { context: Context => Future.failed(new RuntimeException("database unavailable")) } } case class Person(name: String, age: Int) object Person { implicit val reads: Reads[Person] = Json.reads[Person] } case class HelloMessage(message: String) object HelloMessage { implicit val writes: Writes[HelloMessage] = Json.writes[HelloMessage] }
Example 80
Source File: LaboratoryController.scala From Aton with GNU General Public License v3.0 | 5 votes |
package controllers.api import com.fasterxml.jackson.annotation.JsonValue import com.google.inject.Inject import dao.{LaboratoryDAO, UserDAO} import jp.t2v.lab.play2.auth.OptionalAuthElement import model._ import model.json.LoginJson import play.Logger import play.api.i18n.{I18nSupport, MessagesApi} import play.api.libs.json.{JsValue, Json, Writes} import play.api.mvc.{Action, AnyContent, Controller} import services.LaboratoryService import views.html._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{ExecutionContext, Future} class LaboratoryController @Inject()(userDAO: UserDAO, laboratoryService: LaboratoryService, val messagesApi: MessagesApi) extends Controller with I18nSupport { //override def resolveUser(id: LoginFormData)(implicit context: ExecutionContext): Future[Option[User]] = userDAO.get(id) def convertToJson(laboratoryObject: Laboratory, roomsWithComputers: Map[Room, Seq[(Computer, Option[(ComputerState, Seq[ConnectedUser])])]]): JsValue = { val roomsConverted = roomsWithComputers.toSeq val grouped = roomsConverted.groupBy(_._1) val resultRooms = grouped.map(filtered=>(filtered._1,filtered._2.map(_._2).head)).toSeq Json.toJson((laboratoryObject,resultRooms)) } def get(id: Long) = Action.async { implicit request => Logger.debug("Petición de listar el laboratory " + id + " [API] respondida.") implicit val username = Some("") laboratoryService.get(id).map { case Some((laboratoryObject, roomsWithComputers)) => Ok(convertToJson(laboratoryObject, roomsWithComputers)) case _ => NotFound(Json.parse( """ |{ | "answer"->"no encontrado" |} """)) } } }
Example 81
Source File: NRSConnectorSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.connectors import java.util.concurrent.TimeoutException import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.libs.json.{JsResultException, Json, Writes} import play.api.libs.ws.{WSClient, WSRequest, WSResponse} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.vatapi.UnitSpec import uk.gov.hmrc.vatapi.assets.TestConstants.NRSResponse._ import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.NrsSubmissionOutcome import uk.gov.hmrc.vatapi.httpparsers.{EmptyNrsData, NRSData} import uk.gov.hmrc.vatapi.mocks.MockHttp import uk.gov.hmrc.vatapi.mocks.config.MockAppContext import uk.gov.hmrc.vatapi.models.NRSSubmission import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class NRSConnectorSpec extends UnitSpec with GuiceOneAppPerSuite with MockHttp with MockAppContext { class Setup { val wsClient = mock[WSClient] val testNrsConnector = new NRSConnector(mockHttp, mockAppContext, wsClient) MockAppContext.nrsMaxTimeoutMilliseconds returns 5000 val testUrl: String = testNrsConnector.nrsSubmissionUrl(testVrn.vrn) def result(requestBody: NRSSubmission): Future[NrsSubmissionOutcome] = testNrsConnector.submit(testVrn, requestBody) } implicit val hc: HeaderCarrier = HeaderCarrier(nsStamp = 2L) val testVrn = Vrn("123456789") "NRSConnector.submit" should { "successful responses are returned from the connector" should { "return the correctly formatted NRS Data model" in new Setup { val request = mock[WSRequest] val response = mock[WSResponse] val expectedResponse = NRSData("2dd537bc-4244-4ebf-bac9-96321be13cdc","This has been deprecated - DO NOT USE","") implicit val nrsWrites = implicitly[Writes[NRSSubmission]] val meJson = Json.toJson(nrsSubmission) when(wsClient.url(testUrl)).thenReturn(request) when(request.withHttpHeaders(any())).thenReturn(request) when(request.withRequestTimeout(testNrsConnector.nrsMaxTimeout)).thenReturn(request) when(request.post(eqTo(meJson))(any())).thenReturn(Future.successful(response)) when(response.json).thenReturn(nrsResponseJson) when(response.status).thenReturn(202) await(result(nrsSubmission)) shouldBe Right(expectedResponse) } } "return EmptyNrsData" when { "the connection times out" in new Setup { val request = mock[WSRequest] implicit val nrsWrites = implicitly[Writes[NRSSubmission]] when(wsClient.url(testUrl)).thenReturn(request) when(request.withHttpHeaders(any())).thenReturn(request) when(request.withRequestTimeout(testNrsConnector.nrsMaxTimeout)).thenReturn(request) when(request.post(eqTo(Json.toJson(nrsSubmission)))(any())).thenReturn(Future.failed(new TimeoutException("Expected Error"))) await(result(nrsSubmission)) shouldBe Right(EmptyNrsData) } "the response JSON cannot be parsed" in new Setup { val request = mock[WSRequest] val response = mock[WSResponse] implicit val nrsWrites = implicitly[Writes[NRSSubmission]] when(wsClient.url(testUrl)).thenReturn(request) when(request.withHttpHeaders(any())).thenReturn(request) when(request.withRequestTimeout(testNrsConnector.nrsMaxTimeout)).thenReturn(request) when(request.post(eqTo(Json.toJson(nrsSubmission)))(any())).thenReturn(Future.successful(response)) when(response.json).thenThrow(JsResultException(Seq())) await(result(nrsSubmission)) shouldBe Right(EmptyNrsData) } } } }
Example 82
Source File: MockHttp.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.mocks import org.mockito.ArgumentCaptor import org.mockito.stubbing.OngoingStubbing import org.scalatest.Suite import play.api.libs.json.Writes import uk.gov.hmrc.http.{HeaderCarrier, HttpReads, HttpResponse} import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient import scala.concurrent.{ExecutionContext, Future} trait MockHttp extends Mock { _: Suite => val mockHttp: DefaultHttpClient = mock[DefaultHttpClient] override protected def beforeEach(): Unit = { super.beforeEach() reset(mockHttp) } private val headerCarrierCaptor = ArgumentCaptor.forClass(classOf[HeaderCarrier]) object MockHttp { def GET[T](url: String): OngoingStubbing[Future[T]] = { when(mockHttp.GET[T](eqTo(url))(any(), headerCarrierCaptor.capture(), any())) } def fetchHeaderCarrier: HeaderCarrier = headerCarrierCaptor.getValue } def setupMockHttpGet(url: String)(response: HttpResponse): OngoingStubbing[Future[HttpResponse]] = when(mockHttp.GET[HttpResponse](eqTo(url)) (any(), any(), any())).thenReturn(Future.successful(response)) def setupMockFailedHttpGet(url: String)(response: HttpResponse): OngoingStubbing[Future[HttpResponse]] = when(mockHttp.GET[HttpResponse](eqTo(url)) (any(), any(), any())).thenReturn(Future.failed(new Exception)) def setupMockHttpPost[T, R](url: String, elem: T)(response: R): OngoingStubbing[Future[R]] ={ when( mockHttp.POST[T, R](eqTo(url), eqTo[T](elem), any[Seq[(String, String)]]()) (any[Writes[T]](), any[HttpReads[R]](), any[HeaderCarrier](), any[ExecutionContext]()) ).thenReturn( Future.successful(response)) } def setupMockHttpPostString[R](url: String, elem: String)(response: R): OngoingStubbing[Future[R]] ={ when( mockHttp.POSTString[R](eqTo(url), eqTo[String](elem), any[Seq[(String, String)]]()) (any[HttpReads[R]](), headerCarrierCaptor.capture(), any[ExecutionContext]()) ).thenReturn( Future.successful(response)) } }
Example 83
Source File: MockHttpClient.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.mocks import org.scalamock.handlers.CallHandler import org.scalamock.scalatest.MockFactory import play.api.libs.json.Writes import uk.gov.hmrc.http.{HeaderCarrier, HttpReads} import uk.gov.hmrc.play.bootstrap.http.HttpClient import scala.concurrent.{ExecutionContext, Future} trait MockHttpClient extends MockFactory { val mockHttpClient: HttpClient = mock[HttpClient] object MockedHttpClient { def get[T](url: String, requiredHeaders: (String, String)*): CallHandler[Future[T]] = { (mockHttpClient .GET(_: String)(_: HttpReads[T], _: HeaderCarrier, _: ExecutionContext)) .expects(where { (actualUrl, _, hc, _) => url == actualUrl && requiredHeaders.forall(h => hc.headers.contains(h)) }) } def get[T](url: String, queryParams: Seq[(String, String)], requiredHeaders: (String, String)*): CallHandler[Future[T]] = { (mockHttpClient .GET(_: String, _: Seq[(String, String)])(_: HttpReads[T], _: HeaderCarrier, _: ExecutionContext)) .expects(where { (actualUrl, params, _, hc, _) => url == actualUrl && requiredHeaders.forall(h => hc.headers.contains(h)) && params == queryParams }) } def post[I, T](url: String, body: I, requiredHeaders: (String, String)*): CallHandler[Future[T]] = { (mockHttpClient .POST[I, T](_: String, _: I, _: Seq[(String, String)])(_: Writes[I], _: HttpReads[T], _: HeaderCarrier, _: ExecutionContext)) .expects(where { (actualUrl, actualBody, _, _, _, hc, _) => url == actualUrl && body == actualBody && requiredHeaders.forall(h => hc.headers.contains(h)) }) } } }