io.circe.Printer Scala Examples
The following examples show how to use io.circe.Printer.
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: XmlSpec.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema package swagger import syntax._ import SwaggerTypeable.deriveNamedTypeable import io.circe.syntax._ import cats.syntax.option._ import io.circe.Printer import SwaggerXMLOptions.{apply => xmlOpts} import shapeless.syntax.singleton._ import org.scalatest.wordspec.AnyWordSpec class XmlSpec extends AnyWordSpec { val swaggerJson = XmlSpec.swagger.make(OpenApiInfo()).asJson val top = swaggerJson.hcursor val method = top.downField("paths").downField("/xml").downField("get") val response = method.downField("responses").downField("200").downField("content") val bookType = top.downField("components").downField("schemas").downField("Book") "Swagger Json" should { "contain XML method" in assert(method.succeeded) "contain XML media type answer" in assert( response.downField("application/xml").downField("schema").downField("$ref").as[String] === Right( "#/components/schemas/Book" ) ) "contain only one media type" in assert( response.keys.toSeq.flatten.length === 1 ) "have Book type" in assert(bookType.succeeded) "have Book xml-name" in assert(bookType.downField("xml").downField("name").as[String] === Right("book")) "have id xml-attribute" in assert( bookType.downField("properties").downField("id").downField("xml").downField("attribute").as[Boolean] === Right( true ) ) "have tag wrapped array property" in assert( bookType.downField("properties").downField("tags").downField("xml").as[SwaggerXMLOptions] === Right( xmlOpts(name = "tag".some, wrapped = true) ) ) } } object XmlSpec { case class Book(id: Int, author: String, title: String, tags: List[String]) implicit val bookSwagger: SwaggerTypeable[Book] = deriveNamedTypeable[Book] .xmlFld(Symbol("id") ->> xmlOpts(attribute = true)) .xmlFields("tags" -> xmlOpts(name = "tag".some, wrapped = true)) .xml(name = "book".some) def api = prefix("xml") |> key("foo") |> get |> $$[Book] val swagger = MkSwagger(api) }
Example 2
Source File: package.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s import java.nio.charset.StandardCharsets import io.circe.{Decoder, Encoder, Json, Printer} import org.apache.pulsar.client.api.Schema import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType} import scala.annotation.implicitNotFound package object circe { @implicitNotFound( "No Encoder for type ${T} found. Use 'import io.circe.generic.auto._' or provide an implicit Encoder instance ") implicit def circeSchema[T: Manifest](implicit encoder: Encoder[T], decoder: Decoder[T], printer: Json => String = Printer.noSpaces.print): Schema[T] = new Schema[T] { override def clone(): Schema[T] = this override def encode(t: T): Array[Byte] = printer(encoder(t)).getBytes(StandardCharsets.UTF_8) override def decode(bytes: Array[Byte]): T = io.circe.jawn.decode[T](new String(bytes, StandardCharsets.UTF_8)).fold(throw _, identity) override def getSchemaInfo: SchemaInfo = new SchemaInfo() .setName(manifest[T].runtimeClass.getCanonicalName) .setType(SchemaType.JSON) .setSchema("""{"type":"any"}""".getBytes("UTF-8")) } }
Example 3
Source File: CirceStreamSupport.scala From akka-stream-json with Apache License 2.0 | 5 votes |
package de.knutwalker.akka.stream package support import akka.NotUsed import akka.stream.scaladsl.Flow import akka.util.ByteString import io.circe.CursorOp.DownField import io.circe.jawn.CirceSupportParser._ import io.circe.{ CursorOp, Decoder, DecodingFailure, Encoder, HCursor, Json, Printer } import jawn.AsyncParser object CirceStreamSupport extends CirceStreamSupport trait CirceStreamSupport { def decode[A: Decoder]: Flow[ByteString, A, NotUsed] = JsonStreamParser.flow[Json].map(decodeJson[A]) def decode[A: Decoder](mode: AsyncParser.Mode): Flow[ByteString, A, NotUsed] = JsonStreamParser.flow[Json](mode).map(decodeJson[A]) def encode[A](implicit A: Encoder[A], P: Printer = Printer.noSpaces): Flow[A, String, NotUsed] = Flow[A].map(a => P.pretty(A(a))) case class JsonParsingException(df: DecodingFailure, cursor: HCursor) extends Exception(errorMessage(df.history, cursor, df.message), df) private[knutwalker] def decodeJson[A](json: Json)(implicit decoder: Decoder[A]): A = { val cursor = json.hcursor decoder(cursor) match { case Right(e) => e case Left(f) => throw JsonParsingException(f, cursor) } } private[this] def errorMessage(hist: List[CursorOp], cursor: HCursor, typeHint: String) = { val ac = cursor.replay(hist) if (ac.failed && lastWasDownField(hist)) { s"The field [${CursorOp.opsToPath(hist)}] is missing." } else { s"Could not decode [${ac.focus.getOrElse(Json.Null)}] at [${CursorOp.opsToPath(hist)}] as [$typeHint]." } } private[this] def lastWasDownField(hist: List[CursorOp]) = hist.headOption match { case Some(DownField(_)) => true case _ => false } }
Example 4
Source File: SttpCirceApi.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.circe import sttp.client._ import sttp.client.internal.Utf8 import io.circe.{Decoder, Encoder, Printer} import io.circe.parser.decode import sttp.client.{IsOption, ResponseAs, ResponseError} import sttp.model.MediaType trait SttpCirceApi { implicit def circeBodySerializer[B](implicit encoder: Encoder[B], printer: Printer = Printer.noSpaces ): BodySerializer[B] = b => StringBody(encoder(b).pretty(printer), Utf8, Some(MediaType.ApplicationJson)) def asJsonAlwaysUnsafe[B: Decoder: IsOption]: ResponseAs[B, Nothing] = asStringAlways.map(ResponseAs.deserializeOrThrow(deserializeJson)) def deserializeJson[B: Decoder: IsOption]: String => Either[io.circe.Error, B] = JsonInput.sanitize[B].andThen(decode[B]) }
Example 5
Source File: IPythonFormat.scala From polynote with Apache License 2.0 | 5 votes |
package polynote.server.repository.format.ipynb import cats.syntax.either._ import io.circe.Printer import io.circe.parser.parse import io.circe.syntax._ import polynote.kernel.{BaseEnv, GlobalEnv} import polynote.messages.Notebook import polynote.server.repository.NotebookContent import polynote.server.repository.format.NotebookFormat import zio.{RIO, ZIO} class IPythonFormat extends NotebookFormat { override val extension: String = "ipynb" override val mime: String = "application/x-ipynb+json" override def decodeNotebook(noExtPath: String, rawContent: String): RIO[Any, Notebook] = for { parsed <- ZIO.fromEither(parse(rawContent)) staged <- ZIO.fromEither(parsed.as[JupyterNotebookStaged]) decoded <- ZIO.fromEither(if (staged.nbformat == 3) parsed.as[JupyterNotebookV3].map(JupyterNotebookV3.toV4) else parsed.as[JupyterNotebook]) } yield JupyterNotebook.toNotebook(decoded).toNotebook(s"$noExtPath.$extension") override def encodeNotebook(nb: NotebookContent): RIO[Any, String] = for { ipynb <- ZIO(JupyterNotebook.fromNotebook(nb)) } yield Printer.spaces2.copy(dropNullValues = true).pretty(ipynb.asJson) }
Example 6
Source File: JsonDiff.scala From Argus with MIT License | 5 votes |
package argus.json import io.circe.Json import io.circe.Printer object JsonDiff { def diff(j1: Json, j2: Json) = { val removeNulls = (t: (String, Json)) => { !t._2.isNull } def diffR(j1: Json, j2: Json): List[(String, String)] = { (j1.asObject, j2.asObject) match { case (Some(o1), Some(o2)) => { val o1m = o1.toMap.filter(removeNulls) val o2m = o2.toMap.filter(removeNulls) val sharedKeys = o1m.keySet intersect o2m.keySet // First record any missing fields val diffKeys = (o1m.keySet diff sharedKeys).map((_, "missing")) ++ (o2m.keySet diff sharedKeys).map(("missing", _)) // Now recurse on each field diffKeys.toList ++ sharedKeys.foldLeft(List[(String, String)]()) { case(accum, k) => accum ++ diffR(o1(k).get, o2(k).get) } } case _ => { (j1.asArray, j2.asArray) match { case (Some(a1), Some(a2)) => { a1.zip(a2).flatMap { case(jj1, jj2) => diffR(jj1,jj2) } toList } // Everything else case _ => if (j1 != j2) List((j1.toString, j2.toString)) else Nil } } } } diffR(j1, j2) } val NoNullPrinter = Printer.spaces2.copy(dropNullValues = true) }
Example 7
Source File: CirceSupport.scala From kafka-serde-scala with Apache License 2.0 | 5 votes |
package io.github.azhur.kafkaserdecirce import java.nio.charset.StandardCharsets.UTF_8 import java.util import io.circe.{ Decoder, Encoder, Printer } import org.apache.kafka.common.errors.SerializationException import org.apache.kafka.common.serialization.{ Deserializer, Serde, Serializer } import scala.language.implicitConversions import scala.util.control.NonFatal trait CirceSupport { implicit def toSerializer[T >: Null](implicit encoder: Encoder[T], printer: Printer = Printer.noSpaces): Serializer[T] = new Serializer[T] { import io.circe.syntax._ 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.pretty(data.asJson).getBytes(UTF_8) catch { case NonFatal(e) => throw new SerializationException(e) } } implicit def toDeserializer[T >: Null](implicit decoder: Decoder[T]): Deserializer[T] = new Deserializer[T] { import io.circe._ import cats.syntax.either._ 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 parser .parse(new String(data, UTF_8)) .valueOr(e => throw new SerializationException(e)) .as[T] .valueOr(e => throw new SerializationException(e)) } implicit def toSerde[T >: Null](implicit encoder: Encoder[T], printer: Printer = Printer.noSpaces, decoder: Decoder[T]): 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 CirceSupport extends CirceSupport
Example 8
Source File: EventCommonRoutes.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import java.util.UUID import akka.NotUsed import akka.actor.ActorSystem import akka.http.javadsl.server.Rejections.validationRejection import akka.http.scaladsl.model.headers.`Last-Event-ID` import akka.http.scaladsl.model.sse.ServerSentEvent import akka.http.scaladsl.server.Directive1 import akka.http.scaladsl.server.Directives.{optionalHeaderValueByName, provide, reject} import akka.persistence.query._ import akka.persistence.query.scaladsl.EventsByTagQuery import akka.stream.scaladsl.Source import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.kg.config.AppConfig import ch.epfl.bluebrain.nexus.kg.resources.Event import io.circe.syntax._ import io.circe.{Encoder, Printer} import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} protected def lastEventId: Directive1[Offset] = optionalHeaderValueByName(`Last-Event-ID`.name) .map(_.map(id => `Last-Event-ID`(id))) .flatMap { case Some(header) => Try[Offset](TimeBasedUUID(UUID.fromString(header.id))) orElse Try(Sequence(header.id.toLong)) match { case Success(value) => provide(value) case Failure(_) => reject(validationRejection("The value of the `Last-Event-ID` header is not valid.")) } case None => provide(NoOffset) } private def aToSse[A: Encoder](a: A, offset: Offset): ServerSentEvent = { val json = a.asJson.sortKeys(AppConfig.orderedKeys) ServerSentEvent( data = json.printWith(printer), eventType = json.hcursor.get[String]("@type").toOption, id = offset match { case NoOffset => None case Sequence(value) => Some(value.toString) case TimeBasedUUID(uuid) => Some(uuid.toString) } ) } protected def eventToSse(envelope: EventEnvelope)(implicit enc: Encoder[Event]): Option[ServerSentEvent] = envelope.event match { case value: Event => Some(aToSse(value, envelope.offset)) case _ => None } }
Example 9
Source File: StatisticsSpec.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.indexing import java.util.regex.Pattern.quote import ch.epfl.bluebrain.nexus.commons.test.Resources import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.config.AppConfig import ch.epfl.bluebrain.nexus.kg.config.Vocabulary.nxv import ch.epfl.bluebrain.nexus.kg.indexing.Statistics.{CompositeViewStatistics, ViewStatistics} import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import io.circe.Printer import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import org.scalatest.{Inspectors, OptionValues} class StatisticsSpec extends AnyWordSpecLike with Matchers with OptionValues with TestHelper with Resources with Inspectors { "Statistics" should { val sourceId = genIri val projectionId = nxv.defaultElasticSearchIndex.value val single: Statistics = ViewStatistics(10L, 1L, 2L, 12L, None, None, None) val singleJson = jsonContentOf("/view/statistics.json").removeKeys("projectionId") val composite: Statistics = CompositeViewStatistics(IdentifiedProgress(sourceId, projectionId, single.asInstanceOf[ViewStatistics])) val compositeJson = jsonContentOf("/view/composite_statistics.json", Map(quote("{sourceId}") -> sourceId.asString)) val printer: Printer = Printer.noSpaces.copy(dropNullValues = true) "be encoded" in { forAll(List(single -> singleJson, composite -> compositeJson)) { case (model, json) => printer.print(model.asJson.sortKeys(AppConfig.orderedKeys)) shouldEqual printer.print(json) } } } }
Example 10
Source File: MagnoliaSpec.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.swagger import io.circe.Printer import ru.tinkoff.tschema.swagger.testDomain.{LotOfVariants, TopStuff, WeirdThing} import shapeless.test.illTyped import org.scalatest.flatspec.AnyFlatSpec class MagnoliaSpec extends AnyFlatSpec { import MagnoliaSwagger.{derive => magnoliaDerive} "magnolia" should "derive known types" in { implicit lazy val weirdThingSwaggerTypeable: SwaggerTypeable[WeirdThing] = SwaggerTypeable.make(SwaggerPrimitive.boolean).as[WeirdThing] implicit lazy val lots: SwaggerTypeable[LotOfVariants] = MagnoliaSwagger.derivedInstance lazy val testSwagger: SwaggerTypeable[TopStuff] = magnoliaDerive } it should "not derive unknown types" in { illTyped("""lazy val testSwagger: SwaggerTypeable[TopStuff] = magnoliaDerive""") } } object MagnoliaSpec { implicit val cfg: SwaggerTypeable.Config = SwaggerTypeable.defaultConfig.snakeCaseProps.snakeCaseAlts.withDiscriminator("type") implicit val printer = Printer.spaces4.copy(dropNullValues = true) }
Example 11
Source File: ResourceFSpec.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import java.time.{Clock, Instant, ZoneId} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Resources} import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig import ch.epfl.bluebrain.nexus.iam.config.Vocabulary._ import ch.epfl.bluebrain.nexus.iam.testsyntax._ import ch.epfl.bluebrain.nexus.iam.types.Identity.User import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Printer import io.circe.syntax._ import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike //noinspection TypeAnnotation class ResourceFSpec extends AnyWordSpecLike with Matchers with Inspectors with EitherValues with Resources { "A ResourceMetadata" should { val user = User("mysubject", "myrealm") val user2 = User("mysubject2", "myrealm") implicit val http = HttpConfig("some", 8080, "v1", "http://nexus.example.com") val clock: Clock = Clock.fixed(Instant.ofEpochSecond(3600), ZoneId.systemDefault()) val instant = clock.instant() val id = url"http://example.com/id" val printer = Printer.spaces2.copy(dropNullValues = true) "be converted to Json correctly" when { "using multiple types" in { val json = jsonContentOf("/resources/write-response.json") val model = ResourceMetadata(id, 1L, Set(nxv.AccessControlList, nxv.Realm), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } "using a single type" in { val json = jsonContentOf("/resources/write-response-singletype.json") val model = ResourceMetadata(id, 1L, Set(nxv.AccessControlList), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } "using no types" in { val json = jsonContentOf("/resources/write-response-notypes.json") val model = ResourceMetadata(id, 1L, Set(), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } } } }
Example 12
Source File: PathDescriptionSpec.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.swagger import java.util.ResourceBundle import org.scalatest.flatspec.AnyFlatSpec import ru.tinkoff.tschema.typeDSL.Complete import ru.tinkoff.tschema.syntax._ import PathDescriptionSpec.api import io.circe.Printer import io.circe.syntax._ import ru.tinkoff.tschema.swagger.OpenApi.Method class PathDescriptionSpec extends AnyFlatSpec { val bundle = ResourceBundle.getBundle("swagger") val swagger = MkSwagger(api).describe(PathDescription.i18n(bundle)).make() "description" should "read descriptions from bundle" in { val path = swagger.paths("/test/check")(Method.get) assert(path.responses.codes(200).description.get == "Good") assert(path.responses.codes(400).description.get == "Bad") assert(path.responses.codes(500).description.get == "Ugly") } } object PathDescriptionSpec { class GoodBadUgly[X] def gbu[A]: Complete[GoodBadUgly[A]] = new Complete implicit def gbuSwagger[X: Swagger]: MkSwagger[Complete[GoodBadUgly[X]]] = MkSwagger .summon[Complete[X]] .addResponse(400) .addResponse(500) .as val api = tagPrefix("test") |> operation("check") |> get |> gbu[String] }
Example 13
Source File: circeInstances.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.finagle import cats.{Applicative, Functor, Monad} import io.circe.parser._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Printer} import ru.tinkoff.tschema.finagle.util.message import ru.tinkoff.tschema.finagle.util.message.{jsonBodyParse, jsonComplete} object circeInstances { private[this] val defaultPrinter = Printer.noSpaces.copy(dropNullValues = true) implicit def circeEncodeComplete[F[_]: Applicative, A: Encoder](implicit printer: Printer = defaultPrinter ): Completing[F, A, A] = jsonComplete(_.asJson.printWith(printer)) implicit def circeEncodeCompleteF[F[_], G[_]: Functor, A: Encoder](implicit lift: LiftHttp[F, G], printer: Printer = defaultPrinter ): Completing[F, A, G[A]] = message.fjsonComplete(_.asJson.printWith(printer)) implicit def circeDecodeParseBody[F[_]: Routed: Monad, A: Decoder]: ParseBody[F, A] = jsonBodyParse(decode[A]) }
Example 14
Source File: ExampleSwagger.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.example import java.util.Locale import com.twitter.finagle.http.Response import ru.tinkoff.tschema.example.Server.{getClass, modules} import ru.tinkoff.tschema.examples.SwaggerIndex import ru.tinkoff.tschema.finagle.{Rejection, Routed} import ru.tinkoff.tschema.finagle.util.message import ru.tinkoff.tschema.finagle.zioRouting.Fail.Rejected import ru.tinkoff.tschema.swagger.{OpenApiInfo, PathDescription} import zio.ZIO import zio.blocking.blocking import io.circe.syntax._ import cats.instances.list._ import cats.syntax.foldable._ import cats.syntax.semigroupk._ import io.circe.Printer object ExampleSwagger { private implicit val printer: Printer = Printer.spaces2.copy(dropNullValues = true) private val swaggerHttp: Http[Response] = { val response = message.stringResponse(SwaggerIndex.index.render) response.setContentType("text/html(UTF-8)") Routed.checkPath[Http, Response]("/swagger.php", ZIO.succeed(response)) } private def resource(name: String): Http[Response] = blocking(ZIO { val BufSize = 1024 val response = Response() val stream = getClass.getResourceAsStream(name) val arr = Array.ofDim[Byte](BufSize) def readAll(): Unit = stream.read(arr) match { case BufSize => response.write(arr) readAll() case size if size > 0 => response.write(arr.slice(0, size)) readAll() case _ => } readAll() response }).catchAll(_ => ZIO.fail(Rejected(Rejection.notFound))) private val swaggerResources: Http[Response] = Routed.path[Http].map(_.toString).flatMap { case s if s.startsWith("/webjars") => resource("/META-INF/resources" + s) case _ => Routed.reject[Http, Response](Rejection.notFound) } private val swaggerJson: Http[Response] = { val swagger = modules.foldMap(_.swag) val descriptions = PathDescription.utf8I18n("swagger", Locale.forLanguageTag("ru")) val json = swagger.describe(descriptions).make(OpenApiInfo()).asJson.pretty(printer) val response = message.jsonResponse(json) Routed.checkPath[Http, Response]("/swagger", ZIO.succeed(response)) } val route: Http[Response] = swaggerResources <+> swaggerHttp <+> swaggerJson }
Example 15
Source File: TestServer.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.examples import java.util.Locale import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse} import akka.http.scaladsl.server.Directives.{complete, get, pathPrefix, _} import akka.stream.ActorMaterializer import cats.instances.list._ import cats.syntax.foldable._ import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._ import io.circe.Printer import ru.tinkoff.tschema.swagger.{OpenApiInfo, PathDescription} object TestServer { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() import system.dispatcher val descriptions = PathDescription.utf8I18n("swagger", Locale.forLanguageTag("ru")) val modules = List[ExampleModule]( TestModule, VersionModule, FiltersModule, FormFieldsModule, Authorize, CustomAuth, MultiParameters, ProxyModule ).combineAll private[this] implicit val printer: Printer = Printer.noSpaces.copy(dropNullValues = true) val route = pathPrefix("api") { modules.route } ~ path("swagger")( get( complete( modules.swag .describe(descriptions) .make(OpenApiInfo()) .addServer("/api") ) ) ) ~ pathPrefix("webjars")( getFromResourceDirectory("META-INF/resources/webjars") ) ~ path("swagger.php")( complete( HttpResponse( entity = HttpEntity( contentType = ContentTypes.`text/html(UTF-8)`, string = SwaggerIndex.index.render ) ) ) ) def main(args: Array[String]): Unit = { for (_ <- Http().bindAndHandle(route, "localhost", 8081)) println("server started at http://localhost:8081/swagger.php") } }
Example 16
Source File: Swagger.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.example import java.util.Locale import cats.Monad import com.twitter.finagle.http.Response import ru.tinkoff.tschema.example.Server.{getClass, modules} import ru.tinkoff.tschema.examples.SwaggerIndex import ru.tinkoff.tschema.finagle.{Rejection, Routed, RoutedPlus} import ru.tinkoff.tschema.finagle.util.message import ru.tinkoff.tschema.finagle.routing.Rejected import ru.tinkoff.tschema.swagger.{OpenApiInfo, PathDescription} import io.circe.syntax._ import cats.implicits._ import io.circe.Printer import monix.eval.Task import tofu.env.Env final case class Swagger[H[_]: RoutedPlus: Monad] { private implicit val printer: Printer = Printer.spaces2.copy(dropNullValues = true) private val swaggerHttp: H[Response] = { val response = message.stringResponse(SwaggerIndex.index.render) response.setContentType("text/html(UTF-8)") Routed.checkPath[H, Response]("/swagger.php", response.pure[H]) } private def resource(name: String): H[Response] = Env.fromTask( Task.delay { val BufSize = 1024 val response = Response() val stream = getClass.getResourceAsStream(name) val arr = Array.ofDim[Byte](BufSize) def readAll(): Unit = stream.read(arr) match { case BufSize => response.write(arr) readAll() case size if size > 0 => response.write(arr.slice(0, size)) readAll() case _ => } readAll() response }.executeOn(resources) .onErrorHandleWith(_ => Task.raiseError(Rejected(Rejection.notFound)))) private val swaggerResources: H[Response] = Routed.path[H].map(_.toString).flatMap { case s if s.startsWith("/webjars") => resource("/META-INF/resources" + s) case _ => Routed.reject[H, Response](Rejection.notFound) } private val swaggerJson: H[Response] = { val swagger = modules.foldMap(_.swag) val descriptions = PathDescription.utf8I18n("swagger", Locale.forLanguageTag("ru")) val json = swagger.describe(descriptions).make(OpenApiInfo()).asJson.pretty(printer) val response = message.jsonResponse(json) Routed.checkPath[H, Response]("/swagger", response.pure[H]) } val route: H[Response] = swaggerResources <+> swaggerHttp <+> swaggerJson }
Example 17
Source File: ExampleSwagger.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.example import java.util.Locale import com.twitter.finagle.http.Response import ru.tinkoff.tschema.example.Server.{getClass, modules} import ru.tinkoff.tschema.examples.SwaggerIndex import ru.tinkoff.tschema.finagle.{Rejection, Routed} import ru.tinkoff.tschema.finagle.util.message import ru.tinkoff.tschema.finagle.envRouting.Rejected import ru.tinkoff.tschema.swagger.{OpenApiInfo, PathDescription} import io.circe.syntax._ import cats.instances.list._ import cats.syntax.foldable._ import cats.syntax.semigroupk._ import io.circe.Printer import monix.eval.Task import tofu.env.Env object ExampleSwagger { private implicit val printer: Printer = Printer.spaces2.copy(dropNullValues = true) private val swaggerHttp: Http[Response] = { val response = message.stringResponse(SwaggerIndex.index.render) response.setContentType("text/html(UTF-8)") Routed.checkPath[Http, Response]("/swagger.php", Http.pure(response)) } private def resource(name: String): Http[Response] = Env.fromTask( Task.delay { val BufSize = 1024 val response = Response() val stream = getClass.getResourceAsStream(name) val arr = Array.ofDim[Byte](BufSize) def readAll(): Unit = stream.read(arr) match { case BufSize => response.write(arr) readAll() case size if size > 0 => response.write(arr.slice(0, size)) readAll() case _ => } readAll() response }.executeOn(resources) .onErrorHandleWith(_ => Task.raiseError(Rejected(Rejection.notFound)))) private val swaggerResources: Http[Response] = Routed.path[Http].map(_.toString).flatMap { case s if s.startsWith("/webjars") => resource("/META-INF/resources" + s) case _ => Routed.reject[Http, Response](Rejection.notFound) } private val swaggerJson: Http[Response] = { val swagger = modules.foldMap(_.swag) val descriptions = PathDescription.utf8I18n("swagger", Locale.forLanguageTag("ru")) val json = swagger.describe(descriptions).make(OpenApiInfo()).asJson.pretty(printer) val response = message.jsonResponse(json) Routed.checkPath[Http, Response]("/swagger", Env.pure(response)) } val route: Http[Response] = swaggerResources <+> swaggerHttp <+> swaggerJson }
Example 18
Source File: JsonIO.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.extra.json import com.spotify.scio.ScioContext import com.spotify.scio.io.{ScioIO, Tap, TapOf, TextIO} import com.spotify.scio.util.ScioUtil import com.spotify.scio.values.SCollection import com.spotify.scio.coders.Coder import io.circe.Printer import io.circe.parser._ import io.circe.syntax._ import org.apache.beam.sdk.{io => beam} final case class JsonIO[T: Encoder: Decoder: Coder](path: String) extends ScioIO[T] { override type ReadP = JsonIO.ReadParam override type WriteP = JsonIO.WriteParam final override val tapT = TapOf[T] override protected def read(sc: ScioContext, params: ReadP): SCollection[T] = sc.read(TextIO(path))(TextIO.ReadParam(params.compression)).map(decodeJson) override protected def write(data: SCollection[T], params: WriteP): Tap[T] = { data .map(x => params.printer.print(x.asJson)) .write(TextIO(path))(TextIO.WriteParam(params.suffix, params.numShards, params.compression)) tap(JsonIO.ReadParam(params.compression)) } override def tap(params: ReadP): Tap[T] = new Tap[T] { override def value: Iterator[T] = TextIO.textFile(ScioUtil.addPartSuffix(path)).map(decodeJson) override def open(sc: ScioContext): SCollection[T] = JsonIO(ScioUtil.addPartSuffix(path)).read(sc, params) } private def decodeJson(json: String): T = decode[T](json).fold(throw _, identity) } object JsonIO { final case class ReadParam(compression: beam.Compression = beam.Compression.AUTO) final case class WriteParam( suffix: String = ".json", numShards: Int = 0, compression: beam.Compression = beam.Compression.UNCOMPRESSED, printer: Printer = Printer.noSpaces ) }
Example 19
Source File: package.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.extra import com.spotify.scio.ScioContext import com.spotify.scio.annotations.experimental import com.spotify.scio.io.ClosedTap import com.spotify.scio.values.SCollection import com.spotify.scio.coders.Coder import io.circe.Printer import io.circe.generic.AutoDerivation import org.apache.beam.sdk.io.Compression implicit final class JsonSCollection[T: Encoder: Decoder: Coder](private val self: SCollection[T]) extends Serializable { @experimental def saveAsJsonFile( path: String, suffix: String = ".json", numShards: Int = 0, compression: Compression = Compression.UNCOMPRESSED, printer: Printer = Printer.noSpaces ): ClosedTap[T] = self.write(JsonIO[T](path))(JsonIO.WriteParam(suffix, numShards, compression, printer)) } }
Example 20
Source File: JsonIOTest.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.extra.json import java.nio.file.Files import io.circe.Printer import com.spotify.scio._ import com.spotify.scio.io.TapSpec import com.spotify.scio.testing._ import com.spotify.scio.util.ScioUtil import org.apache.beam.sdk.Pipeline.PipelineExecutionException import org.apache.commons.io.FileUtils import scala.jdk.CollectionConverters._ import scala.io.Source object JsonIOTest { case class Record(i: Int, s: String, o: Option[Int]) } class JsonIOTest extends ScioIOSpec with TapSpec { import JsonIOTest._ private val xs = (1 to 100).map(x => Record(x, x.toString, if (x % 2 == 0) Some(x) else None)) "JsonIO" should "work" in { testTap(xs)(_.saveAsJsonFile(_))(".json") testJobTest(xs)(JsonIO(_))(_.jsonFile(_))(_.saveAsJsonFile(_)) } it should "support custom printer" in { val dir = tmpDir val t = runWithFileFuture { _.parallelize(xs) .saveAsJsonFile(dir.getPath, printer = Printer.noSpaces.copy(dropNullValues = true)) } verifyTap(t, xs.toSet) val result = Files .list(dir.toPath) .iterator() .asScala .flatMap(p => Source.fromFile(p.toFile).getLines()) .toSeq val expected = (1 to 100).map { x => s"""{"i":$x,"s":"$x"${if (x % 2 == 0) s""","o":$x""" else ""}}""" } result should contain theSameElementsAs expected FileUtils.deleteDirectory(dir) } it should "handle invalid JSON" in { val badData = Seq( """{"i":1, "s":hello}""", """{"i":1}""", """{"s":"hello"}""", """{"i":1, "s":1}""", """{"i":"hello", "s":1}""" ) val dir = tmpDir runWithFileFuture { _.parallelize(badData).saveAsTextFile(dir.getPath) } val sc = ScioContext() sc.jsonFile[Record](ScioUtil.addPartSuffix(dir.getPath)) a[PipelineExecutionException] should be thrownBy { sc.run() } FileUtils.deleteDirectory(dir) } }
Example 21
Source File: ErrorDirectives.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.http.directives import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller} import akka.http.scaladsl.model._ import ch.epfl.bluebrain.nexus.commons.circe.ContextUri import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport.OrderedKeys import ch.epfl.bluebrain.nexus.commons.http.RdfMediaTypes import io.circe.{Encoder, Printer} implicit final def jsonLdMarshallerFromStatusAndEncoder[A](implicit statusFrom: StatusFrom[A], encoder: Encoder[A], context: ContextUri, orderedKeys: OrderedKeys = OrderedKeys(List("@context", "code", "message", "details", "")), printer: Printer = Printer.noSpaces.copy(dropNullValues = true) ): ToResponseMarshaller[A] = Marshaller.withFixedContentType(RdfMediaTypes.`application/ld+json`) { value => HttpResponse( status = statusFrom(value), entity = HttpEntity( RdfMediaTypes.`application/ld+json`, printer.print(encoder.mapJson(_.addContext(context)).apply(value).sortKeys) ) ) } }
Example 22
Source File: GoldenCodecLaws.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden import cats.instances.list._, cats.instances.try_._ import cats.syntax.traverse._ import cats.laws._ import io.circe.{ Json, Printer } import io.circe.testing.CodecLaws import scala.util.{ Failure, Success, Try } trait GoldenCodecLaws[A] extends CodecLaws[A] { protected def goldenExamples: Try[List[(A, String)]] final def goldenDecoding: Try[List[IsEq[A]]] = goldenExamples.flatMap { _.traverse { case (value, encoded) => io.circe.parser.decode[A](encoded)(decode) match { case Left(error) => Failure(error) case Right(decoded) => Success(decoded <-> value) } } } final def goldenEncoding: Try[List[IsEq[String]]] = goldenExamples.map { _.map { case (value, encoded) => printJson(encode(value)) <-> encoded } } }
Example 23
Source File: ResourceFileGoldenCodecLaws.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden import cats.instances.list._, cats.instances.try_._ import cats.syntax.apply._, cats.syntax.traverse._ import io.circe.{ Decoder, Encoder, Printer } import java.io.{ File, PrintWriter } import org.scalacheck.{ Arbitrary, Gen } import scala.reflect.runtime.universe.TypeTag import scala.util.{ Failure, Try } import scala.util.matching.Regex abstract class ResourceFileGoldenCodecLaws[A]( name: String, resourceRootDir: File, resourcePackage: List[String], val size: Int, count: Int, override protected val printer: Printer ) extends GoldenCodecLaws[A] with ExampleGeneration[A] { private[this] val resourceRootPath: String = "/" + resourcePackage.mkString("/") + "/" private[this] val resourceDir: File = resourcePackage.foldLeft(resourceRootDir) { case (acc, p) => new File(acc, p) } private[this] val GoldenFilePattern: Regex = "^-(.{44})\\.json$".r private[this] lazy val loadGoldenFiles: Try[List[(A, String)]] = Resources.open(resourceRootPath).flatMap { dirSource => val files = dirSource.getLines.flatMap { case fileName if fileName.startsWith(name) => fileName.drop(name.length) match { case GoldenFilePattern(seed) => Some((seed, fileName)) case _ => None } case _ => None }.toList.traverse[Try, (A, String)] { case (seed, name) => val contents = Resources.open(resourceRootPath + name).map { source => val lines = source.getLines.mkString("\n") source.close() lines } (getValueFromBase64Seed(seed), contents).tupled } dirSource.close() // Fail if we don't have either zero golden files or the required number. files.flatMap { values => if (values.size == 0 || values.size == count) files else Failure(new IllegalStateException(s"Expected 0 or $count golden files, got ${values.size}")) } } private[this] def generateGoldenFiles: Try[List[(A, String)]] = generateRandomGoldenExamples(count).traverse { case (seed, value, encoded) => Try { resourceDir.mkdirs() val file = new File(resourceDir, s"$name-${seed.toBase64}.json") val writer = new PrintWriter(file) writer.print(encoded) writer.close() (value, encoded) } } protected lazy val goldenExamples: Try[List[(A, String)]] = loadGoldenFiles.flatMap(fs => if (fs.isEmpty) generateGoldenFiles else loadGoldenFiles) } object ResourceFileGoldenCodecLaws { def apply[A]( name: String, resourceRootDir: File, resourcePackage: List[String], size: Int, count: Int, printer: Printer )(implicit decodeA: Decoder[A], encodeA: Encoder[A], arbitraryA: Arbitrary[A]): GoldenCodecLaws[A] = new ResourceFileGoldenCodecLaws[A](name, resourceRootDir, resourcePackage, size, count, printer) { val decode: Decoder[A] = decodeA val encode: Encoder[A] = encodeA val gen: Gen[A] = arbitraryA.arbitrary } def apply[A]( size: Int = 100, count: Int = 1, printer: Printer = Printer.spaces2 )( implicit decodeA: Decoder[A], encodeA: Encoder[A], arbitraryA: Arbitrary[A], typeTagA: TypeTag[A] ): GoldenCodecLaws[A] = apply[A](Resources.inferName[A], Resources.inferRootDir, Resources.inferPackage[A], size, count, printer) }
Example 24
Source File: GoldenCodecTests.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden import cats.instances.string._ import cats.kernel.Eq import cats.laws.IsEq import cats.laws.discipline.catsLawsIsEqToProp import io.circe.{ Decoder, Encoder, Json, Printer } import io.circe.testing.CodecTests import org.scalacheck.{ Arbitrary, Prop, Shrink } import scala.reflect.runtime.universe.TypeTag import scala.util.{ Failure, Success, Try } trait GoldenCodecTests[A] extends CodecTests[A] { def laws: GoldenCodecLaws[A] private[this] def tryListToProp[A: Eq](result: Try[List[IsEq[A]]]): Prop = result match { case Failure(error) => Prop.exception(error) case Success(equalities) => Prop.all(equalities.map(catsLawsIsEqToProp(_)): _*) } def goldenCodec( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A], eqA: Eq[A], arbitraryJson: Arbitrary[Json], shrinkJson: Shrink[Json] ): RuleSet = new DefaultRuleSet( name = "goldenCodec", parent = Some(codec), "decoding golden files" -> tryListToProp(laws.goldenDecoding), "encoding golden files" -> tryListToProp(laws.goldenEncoding) ) def unserializableGoldenCodec( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A], eqA: Eq[A], arbitraryJson: Arbitrary[Json], shrinkJson: Shrink[Json] ): RuleSet = new DefaultRuleSet( name = "goldenCodec", parent = Some(unserializableCodec), "decoding golden files" -> tryListToProp(laws.goldenDecoding), "encoding golden files" -> tryListToProp(laws.goldenEncoding) ) } object GoldenCodecTests { def apply[A: Decoder: Encoder: Arbitrary: TypeTag]: GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A]()) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](printer: Printer): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](printer = printer)) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](count = count)) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int, printer: Printer): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](count = count, printer = printer)) def apply[A: Decoder: Encoder: Arbitrary](laws0: GoldenCodecLaws[A]): GoldenCodecTests[A] = new GoldenCodecTests[A] { val laws: GoldenCodecLaws[A] = laws0 } }
Example 25
Source File: VisitRepositorySuite.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden.example import io.circe.{ Codec, Printer } import io.circe.generic.semiauto.deriveCodec import java.time.Instant case class VisitRepository(visits: Map[String, Visit]) object VisitRepository { implicit val codecForVisitRepository: Codec[VisitRepository] = deriveCodec } import cats.kernel.Eq import io.circe.testing.{ ArbitraryInstances, CodecTests } import org.scalacheck.Arbitrary import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.Configuration import org.typelevel.discipline.scalatest.FlatSpecDiscipline trait VisitRepositoryTestInstances extends VisitTestInstances with ArbitraryInstances { implicit val eqVisitRepository: Eq[VisitRepository] = Eq.fromUniversalEquals implicit val arbitraryVisitRepository: Arbitrary[VisitRepository] = Arbitrary( for { visits <- Arbitrary.arbitrary[Map[String, Visit]] } yield VisitRepository(visits) ) } class OldVisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances { checkAll("Codec[VisitRepository]", CodecTests[VisitRepository].codec) val good = """{"visits":{"1":{"id":12345,"page":"/index.html","ts":"2019-10-22T14:54:13Z"}}}""" val value = VisitRepository(Map("1" -> Visit(12345L, "/index.html", Instant.parse("2019-10-22T14:54:13Z")))) "codecForVisitRepository" should "decode JSON that's known to be good" in { assert(io.circe.jawn.decode[VisitRepository](good) === Right(value)) } it should "produce the expected results" in { import io.circe.syntax._ assert(value.asJson.noSpaces === good) } } import io.circe.testing.golden.GoldenCodecTests class VisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances { checkAll("GoldenCodec[VisitRepository]", GoldenCodecTests[VisitRepository](Printer.spaces2SortKeys).goldenCodec) }
Example 26
Source File: Metadata.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala import java.nio.file.Paths import java.nio.file.StandardOpenOption import cats.data.NonEmptyChain import cats.effect.Blocker import cats.effect.ExitCode import cats.effect.IO import cats.effect.IOApp import cats.instances.string._ import com.mwz.sonar.scala.metadata._ import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRules import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRulesRepository import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRules import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRulesRepository import fs2.Stream import fs2.io.file._ import fs2.text import io.circe.Printer import io.circe.generic.JsonCodec import io.circe.syntax._ @JsonCodec final case class SonarScalaMetadata( rules: Rules, repositories: Map[String, RulesRepository] ) @JsonCodec final case class Rules( scalastyle: NonEmptyChain[Rule], scapegoat: NonEmptyChain[Rule] ) object Metadata extends IOApp { private val metadata: SonarScalaMetadata = SonarScalaMetadata( rules = Rules(sort(ScalastyleRules.rules), sort(ScapegoatRules.rules)), repositories = Map( ScalastyleRulesRepository.RepositoryKey -> ScalastyleRulesRepository.rulesRepository .copy(rules = sort(ScalastyleRulesRepository.rulesRepository.rules)), ScapegoatRulesRepository.RepositoryKey -> ScapegoatRulesRepository.rulesRepository .copy(rules = sort(ScapegoatRulesRepository.rulesRepository.rules)) ) ) private val printer: Printer = Printer.spaces2SortKeys.copy( colonLeft = "", lbraceLeft = "", rbraceRight = "", lbracketLeft = "", lrbracketsEmpty = "", rbracketRight = "", arrayCommaLeft = "", objectCommaLeft = "" ) // Chain is missing sortBy, which should be added in 2.2.0. private def sort(rules: NonEmptyChain[Rule]): NonEmptyChain[Rule] = NonEmptyChain.fromNonEmptyList(rules.toNonEmptyList.sortBy(_.name)) def run(args: List[String]): IO[ExitCode] = { val write: Stream[IO, Unit] = Stream.resource(Blocker[IO]).flatMap { blocker => Stream[IO, String](metadata.asJson.printWith(printer)) .through(text.utf8Encode) .through( writeAll( Paths.get("sonar-scala-metadata.json"), blocker, List(StandardOpenOption.TRUNCATE_EXISTING) ) ) } write.compile.drain.as(ExitCode.Success) } }
Example 27
Source File: package.scala From tsec with MIT License | 5 votes |
package tsec import io.circe.{Printer, _} import io.circe.syntax._ import cats.implicits._ import io.circe.Decoder.Result package object jwt { val JWTPrinter = Printer(true, "") sealed trait JWTAudience { def toList: List[String] } case class JWTSingleAudience(value: String) extends JWTAudience { def toList = List(value) } case class JWTListAudience(values: List[String]) extends JWTAudience { def toList = values } implicit val audienceDecoder: Decoder[JWTAudience] = new Decoder[JWTAudience] { def apply(c: HCursor): Result[JWTAudience] = c.as[String] match { case Right(a) => Right(JWTSingleAudience(a)) case _ => c.as[List[String]].map(JWTListAudience(_)) } } implicit val audienceEncoder: Encoder[JWTAudience] = new Encoder[JWTAudience] { def apply(a: JWTAudience): Json = a match { case JWTSingleAudience(value) => value.asJson case JWTListAudience(values) => values.asJson } } }
Example 28
Source File: Http4sCirceInstances.scala From pure-movie-server with Apache License 2.0 | 5 votes |
package pms.http import fs2.Chunk import io.circe.Printer import pms.effects._ import pms.json._ import org.http4s._ import org.http4s.headers.`Content-Type` import org.http4s.{EntityDecoder, EntityEncoder} import org.http4s.circe.CirceInstances implicit def syncEntityJsonEncoder[F[_]: Applicative, T: Encoder]: EntityEncoder[F, T] = EntityEncoder[F, Chunk[Byte]] .contramap[Json] { json => val bytes = printer.printToByteBuffer(json) Chunk.byteBuffer(bytes) } .withContentType(`Content-Type`(MediaType.application.json)) .contramap(t => Encoder.apply[T].apply(t)) implicit def syncEntityJsonDecoder[F[_]: Sync, T: Decoder]: EntityDecoder[F, T] = circeInstances.jsonOf[F, T] } object Http4sCirceInstances { private val printer: Printer = Printer.noSpaces.copy(dropNullValues = true) private val circeInstances: CirceInstances = CirceInstances.withPrinter(printer).build }
Example 29
Source File: IssuesReportSerializer.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.serializer import java.nio.file.Path import com.codacy.analysis.core.model.IssuesAnalysis.FileResults import com.codacy.analysis.core.model.{Issue, IssuesAnalysis, Location, ToolResult, ToolResults} import com.codacy.plugins.api.results import io.circe.{Encoder, Printer} import io.circe.generic.semiauto.deriveEncoder import io.circe.syntax._ object IssuesReportSerializer { private[IssuesReportSerializer] implicit val levelEncoder: Encoder[results.Result.Level.Value] = Encoder.encodeEnumeration(results.Result.Level) private[IssuesReportSerializer] implicit val categoryEncoder: Encoder[results.Pattern.Category.Value] = Encoder.encodeEnumeration(results.Pattern.Category) private[IssuesReportSerializer] implicit val pathEncoder: Encoder[Path] = Encoder.encodeString.contramap(_.toString) private[IssuesReportSerializer] implicit val toolResultsEncoder: Encoder[ToolResults] = deriveEncoder private[IssuesReportSerializer] implicit val issuesAnalysisEncoder: Encoder[IssuesAnalysis] = deriveEncoder private[IssuesReportSerializer] implicit val issueResultEncoder: Encoder[Issue] = deriveEncoder private[IssuesReportSerializer] implicit val patternIdEncoder: Encoder[results.Pattern.Id] = deriveEncoder private[IssuesReportSerializer] implicit val issueMessageEncoder: Encoder[Issue.Message] = deriveEncoder private[IssuesReportSerializer] implicit val issueLocationEncoder: Encoder[Location] = deriveEncoder private[IssuesReportSerializer] implicit val resultEncoder: Encoder[ToolResult] = deriveEncoder private[IssuesReportSerializer] implicit val fileResultsEncoder: Encoder[FileResults] = deriveEncoder def toJsonString(toolResults: Set[ToolResults]): String = toolResults.asJson.printWith(Printer.noSpaces.copy(dropNullValues = true)) }
Example 30
Source File: Fs2JsonEncoderSpec.scala From fs2-rabbit with Apache License 2.0 | 5 votes |
package dev.profunktor.fs2rabbit.json import dev.profunktor.fs2rabbit.model.{AmqpMessage, AmqpProperties} import io.circe.Printer import io.circe.generic.auto._ import io.circe.syntax._ import org.scalatest.flatspec.AnyFlatSpecLike import org.scalatest.matchers.should.Matchers class Fs2JsonEncoderSpec extends AnyFlatSpecLike with Matchers { case class Address(number: Int, streetName: String) case class Person(name: String, address: Address) private val fs2JsonEncoder = new Fs2JsonEncoder import fs2JsonEncoder.jsonEncode it should "encode a simple case class" in { val payload = Address(212, "Baker St") val encode = jsonEncode[Address] encode(AmqpMessage(payload, AmqpProperties.empty)) should be( AmqpMessage(payload.asJson.noSpaces, AmqpProperties.empty)) } it should "encode a nested case class" in { val payload = Person("Sherlock", Address(212, "Baker St")) val encode = jsonEncode[Person] encode(AmqpMessage(payload, AmqpProperties.empty)) should be( AmqpMessage(payload.asJson.noSpaces, AmqpProperties.empty)) } it should "encode a simple case class according to a custom printer" in { val payload = Address(212, "Baker St") val customEncode = new Fs2JsonEncoder(Printer.spaces4).jsonEncode[Address] customEncode(AmqpMessage(payload, AmqpProperties.empty)) should be( AmqpMessage(payload.asJson.printWith(Printer.spaces4), AmqpProperties.empty)) } }
Example 31
Source File: CirceController.scala From play-circe with Apache License 2.0 | 5 votes |
package play.api.libs.circe import akka.actor._ import akka.stream._ import io.circe.Printer import io.circe.generic.auto._ import io.circe.syntax._ import play.api.mvc._ class CirceController(val controllerComponents: ControllerComponents) extends BaseController with Circe { implicit val customPrinter = Printer.spaces2.copy(dropNullValues = true) def get = Action { Ok(Data.foo.asJson) } def post = Action(circe.json[Foo]) { implicit request => val isEqual = request.body == Data.foo Ok(isEqual.toString) } def postJson = Action(circe.json) { implicit request => val isEqual = request.body == Data.foo.asJson Ok(isEqual.toString) } def postTolerant = Action(circe.tolerantJson[Foo]) { implicit request => val isEqual = request.body == Data.foo Ok(isEqual.toString) } def postTolerantJson = Action(circe.tolerantJson) { implicit request => val isEqual = request.body == Data.foo.asJson Ok(isEqual.toString) } } object CirceController { implicit val actorSystem = ActorSystem() implicit val ec = actorSystem.dispatcher implicit val materializer = ActorMaterializer() }
Example 32
Source File: EventCommonRoutes.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import java.util.UUID import akka.NotUsed import akka.actor.ActorSystem import akka.http.javadsl.server.Rejections.validationRejection import akka.http.scaladsl.model.headers.`Last-Event-ID` import akka.http.scaladsl.model.sse.ServerSentEvent import akka.http.scaladsl.server.Directive1 import akka.http.scaladsl.server.Directives.{optionalHeaderValueByName, provide, reject} import akka.persistence.query._ import akka.persistence.query.scaladsl.EventsByTagQuery import akka.stream.scaladsl.Source import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.kg.resources.Event import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import io.circe.syntax._ import io.circe.{Encoder, Printer} import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} protected def lastEventId: Directive1[Offset] = optionalHeaderValueByName(`Last-Event-ID`.name) .map(_.map(id => `Last-Event-ID`(id))) .flatMap { case Some(header) => Try[Offset](TimeBasedUUID(UUID.fromString(header.id))) orElse Try(Sequence(header.id.toLong)) match { case Success(value) => provide(value) case Failure(_) => reject(validationRejection("The value of the `Last-Event-ID` header is not valid.")) } case None => provide(NoOffset) } private def aToSse[A: Encoder](a: A, offset: Offset): ServerSentEvent = { val json = a.asJson.sortKeys(ServiceConfig.orderedKeys) ServerSentEvent( data = json.printWith(printer), eventType = json.hcursor.get[String]("@type").toOption, id = offset match { case NoOffset => None case Sequence(value) => Some(value.toString) case TimeBasedUUID(uuid) => Some(uuid.toString) } ) } protected def eventToSse(envelope: EventEnvelope)(implicit enc: Encoder[Event]): Option[ServerSentEvent] = envelope.event match { case value: Event => Some(aToSse(value, envelope.offset)) case _ => None } }
Example 33
Source File: EventSerializer.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.io import java.nio.charset.Charset import akka.actor.ExtendedActorSystem import akka.serialization.SerializerWithStringManifest import ch.epfl.bluebrain.nexus.iam.acls.AclEvent import ch.epfl.bluebrain.nexus.iam.permissions.PermissionsEvent import ch.epfl.bluebrain.nexus.iam.realms.RealmEvent import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._ import ch.epfl.bluebrain.nexus.rdf.Iri.Url import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import ch.epfl.bluebrain.nexus.service.config.Settings import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto._ import io.circe.parser._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Printer} class EventSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { private val utf8 = Charset.forName("UTF-8") private val printer = Printer.noSpaces.copy(dropNullValues = true) implicit private[io] val http: HttpConfig = Settings(system).serviceConfig.http implicit private[io] val config: Configuration = Configuration.default.withDiscriminator("@type") implicit private[io] val urlEncoder: Encoder[Url] = Encoder.encodeString.contramap(_.asUri) implicit private[io] val urlDecoder: Decoder[Url] = Decoder.decodeString.emap(Url.apply) implicit private[io] val permissionEventEncoder: Encoder[PermissionsEvent] = deriveConfiguredEncoder[PermissionsEvent] implicit private[io] val permissionEventDecoder: Decoder[PermissionsEvent] = deriveConfiguredDecoder[PermissionsEvent] implicit private[io] val aclEventEncoder: Encoder[AclEvent] = deriveConfiguredEncoder[AclEvent] implicit private[io] val aclEventDecoder: Decoder[AclEvent] = deriveConfiguredDecoder[AclEvent] implicit private[io] val realmEventEncoder: Encoder[RealmEvent] = deriveConfiguredEncoder[RealmEvent] implicit private[io] val realmEventDecoder: Decoder[RealmEvent] = deriveConfiguredDecoder[RealmEvent] override val identifier: Int = 1225 override def manifest(o: AnyRef): String = o match { case _: PermissionsEvent => "permissions-event" case _: AclEvent => "acl-event" case _: RealmEvent => "realm-event" case other => throw new IllegalArgumentException( s"Cannot determine manifest for unknown type: '${other.getClass.getCanonicalName}'" ) } override def toBinary(o: AnyRef): Array[Byte] = o match { case ev: PermissionsEvent => ev.asJson.printWith(printer).getBytes(utf8) case ev: AclEvent => ev.asJson.printWith(printer).getBytes(utf8) case ev: RealmEvent => ev.asJson.printWith(printer).getBytes(utf8) case other => throw new IllegalArgumentException(s"Cannot serialize unknown type: '${other.getClass.getCanonicalName}'") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { case "permissions-event" => val str = new String(bytes, utf8) decode[PermissionsEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'PermissionsEvent'")) case "acl-event" => val str = new String(bytes, utf8) decode[AclEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'AclEvent'")) case "realm-event" => val str = new String(bytes, utf8) decode[RealmEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'RealmEvent'")) case other => throw new IllegalArgumentException(s"Cannot deserialize type with unknown manifest: '$other'") } }
Example 34
Source File: RejectionHandlingSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.http import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Rejection import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.util.EitherValues import com.typesafe.config.{Config, ConfigFactory} import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._ import io.circe.{Json, Printer} import io.circe.parser._ import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class RejectionHandlingSpec extends AnyWordSpecLike with Matchers with Inspectors with ScalatestRouteTest with EitherValues { class Custom extends Rejection override def testConfig: Config = ConfigFactory.empty() implicit private val printer: Printer = Printer.spaces2.copy(dropNullValues = true) "A default rejection handler" should { val handler = RejectionHandling { _: Custom => StatusCodes.InternalServerError -> Json.obj("reason" -> Json.fromString("custom")) }.withFallback(RejectionHandling.notFound) "handle not found" in { val route = handleRejections(handler)(pathEnd(complete("ok"))) Get("/a") ~> route ~> check { val expected = s"""{ | "@context": "https://bluebrain.github.io/nexus/contexts/error.json", | "@type": "NotFound", | "reason": "The requested resource could not be found." |}""".stripMargin status shouldEqual StatusCodes.NotFound responseAs[Json] shouldEqual parse(expected).rightValue } } "handle missing query param" in { val route = handleRejections(handler)(parameter("rev".as[Long])(_ => complete("ok"))) Get("/a") ~> route ~> check { val expected = s"""{ | "@context": "https://bluebrain.github.io/nexus/contexts/error.json", | "@type": "MissingQueryParam", | "reason": "Request is missing required query parameter 'rev'." |}""".stripMargin status shouldEqual StatusCodes.BadRequest responseAs[Json] shouldEqual parse(expected).rightValue } } "handle custom" in { val route = handleRejections(handler)(reject(new Custom)) Get("/a") ~> route ~> check { val expected = s"""{ | "reason": "custom" |}""".stripMargin status shouldEqual StatusCodes.InternalServerError responseAs[Json] shouldEqual parse(expected).rightValue } } } }
Example 35
Source File: StatisticsSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.indexing import java.util.regex.Pattern.quote import ch.epfl.bluebrain.nexus.commons.test.Resources import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.indexing.Statistics.{CompositeViewStatistics, ViewStatistics} import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.Printer import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import org.scalatest.{Inspectors, OptionValues} class StatisticsSpec extends AnyWordSpecLike with Matchers with OptionValues with TestHelper with Resources with Inspectors { "Statistics" should { val sourceId = genIri val projectionId = nxv.defaultElasticSearchIndex.value val single: Statistics = ViewStatistics(10L, 1L, 2L, 12L, None, None, None) val singleJson = jsonContentOf("/view/statistics.json").removeKeys("projectionId") val composite: Statistics = CompositeViewStatistics(IdentifiedProgress(sourceId, projectionId, single.asInstanceOf[ViewStatistics])) val compositeJson = jsonContentOf("/view/composite_statistics.json", Map(quote("{sourceId}") -> sourceId.asString)) val printer: Printer = Printer.noSpaces.copy(dropNullValues = true) "be encoded" in { forAll(List(single -> singleJson, composite -> compositeJson)) { case (model, json) => printer.print(model.asJson.sortKeys(ServiceConfig.orderedKeys)) shouldEqual printer.print(json) } } } }
Example 36
Source File: ResourceFSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import java.time.{Clock, Instant, ZoneId} import ch.epfl.bluebrain.nexus.util.{EitherValues, Resources} import ch.epfl.bluebrain.nexus.iam.testsyntax._ import ch.epfl.bluebrain.nexus.iam.types.Identity.User import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.Printer import io.circe.syntax._ import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike //noinspection TypeAnnotation class ResourceFSpec extends AnyWordSpecLike with Matchers with Inspectors with EitherValues with Resources { "A ResourceMetadata" should { val user = User("mysubject", "myrealm") val user2 = User("mysubject2", "myrealm") implicit val http = HttpConfig("some", 8080, "v1", "http://nexus.example.com") val clock: Clock = Clock.fixed(Instant.ofEpochSecond(3600), ZoneId.systemDefault()) val instant = clock.instant() val id = url"http://example.com/id" val printer = Printer.spaces2.copy(dropNullValues = true) "be converted to Json correctly" when { "using multiple types" in { val json = jsonContentOf("/resources/write-response.json") val model = ResourceMetadata(id, 1L, Set(nxv.AccessControlList.value, nxv.Realm.value), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } "using a single type" in { val json = jsonContentOf("/resources/write-response-singletype.json") val model = ResourceMetadata(id, 1L, Set(nxv.AccessControlList.value), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } "using no types" in { val json = jsonContentOf("/resources/write-response-notypes.json") val model = ResourceMetadata(id, 1L, Set(), instant, user, instant, user2) model.asJson.sort.printWith(printer) shouldEqual json.printWith(printer) } } } }
Example 37
Source File: JsonLdCirceSupport.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.model.{ContentTypeRange, HttpEntity} import ch.epfl.bluebrain.nexus.commons.http.RdfMediaTypes import ch.epfl.bluebrain.nexus.storage.JsonLdCirceSupport.{sortKeys, OrderedKeys} import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport import io.circe.syntax._ import io.circe.{Encoder, Json, JsonObject, Printer} import scala.collection.immutable.Seq def sortKeys(json: Json)(implicit keys: OrderedKeys): Json = { implicit val customStringOrdering: Ordering[String] = new Ordering[String] { private val middlePos = keys.withPosition("") private def position(key: String): Int = keys.withPosition.getOrElse(key, middlePos) override def compare(x: String, y: String): Int = { val posX = position(x) val posY = position(y) if (posX == middlePos && posY == middlePos) x compareTo y else posX compareTo posY } } def canonicalJson(json: Json): Json = json.arrayOrObject[Json](json, arr => Json.fromValues(arr.map(canonicalJson)), obj => sorted(obj).asJson) def sorted(jObj: JsonObject): JsonObject = JsonObject.fromIterable(jObj.toVector.sortBy(_._1).map { case (k, v) => k -> canonicalJson(v) }) canonicalJson(json) } }
Example 38
Source File: Chrome.scala From scala-js-chrome with MIT License | 5 votes |
package net.lullabyte import chrome.Manifest import io.circe.Printer import io.circe.syntax._ import sbt._ object Chrome { val manifestFileName = "manifest.json" def i18n(msg: String): String = s"__MSG_${msg}__" def icons(base: String, name: String, sizes: Set[Int]): Map[Int, String] = { sizes.map{ size => size -> s"$base/$size/$name" }.toMap } def buildUnpackedDirectory(unpacked: File)(manifest: File, jsLib: File, jsDeps: File, resources: Seq[File]): File = { val libsAndDependencies = List( jsLib -> unpacked / jsLib.getName, jsDeps -> unpacked / jsDeps.getName ) val sourceMaps = List(jsLib, jsDeps) map { sourceFile => val fileName = sourceFile.getName + ".map" val originalSourceMap = sourceFile.getParentFile / fileName originalSourceMap -> unpacked / fileName } filter (_._1.exists()) val chromeSpecific = List( manifest -> unpacked / manifestFileName ) IO.createDirectory(unpacked) resources.foreach { resource => IO.copyDirectory(resource, unpacked, overwrite = true, preserveLastModified = true) } IO.copy( libsAndDependencies ::: sourceMaps ::: chromeSpecific, overwrite = true, preserveLastModified = true, preserveExecutable = true ) unpacked } val printer = Printer.noSpaces.copy(dropNullValues = true) def generateManifest(out: File)(manifest: Manifest): File = { import JsonCodecs._ val content = printer.pretty(manifest.asJson) IO.write(out, content) out } }
Example 39
Source File: EventSerializer.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.io import java.nio.charset.Charset import akka.actor.ExtendedActorSystem import akka.serialization.SerializerWithStringManifest import ch.epfl.bluebrain.nexus.iam.acls.AclEvent import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig import ch.epfl.bluebrain.nexus.iam.config.Settings import ch.epfl.bluebrain.nexus.iam.permissions.PermissionsEvent import ch.epfl.bluebrain.nexus.iam.realms.RealmEvent import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._ import ch.epfl.bluebrain.nexus.rdf.Iri.Url import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto._ import io.circe.parser._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Printer} class EventSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { private val utf8 = Charset.forName("UTF-8") private val printer = Printer.noSpaces.copy(dropNullValues = true) private[io] implicit val http: HttpConfig = Settings(system).appConfig.http private[io] implicit val config: Configuration = Configuration.default.withDiscriminator("@type") private[io] implicit val urlEncoder: Encoder[Url] = Encoder.encodeString.contramap(_.asUri) private[io] implicit val urlDecoder: Decoder[Url] = Decoder.decodeString.emap(Url.apply) private[io] implicit val permissionEventEncoder: Encoder[PermissionsEvent] = deriveConfiguredEncoder[PermissionsEvent] private[io] implicit val permissionEventDecoder: Decoder[PermissionsEvent] = deriveConfiguredDecoder[PermissionsEvent] private[io] implicit val aclEventEncoder: Encoder[AclEvent] = deriveConfiguredEncoder[AclEvent] private[io] implicit val aclEventDecoder: Decoder[AclEvent] = deriveConfiguredDecoder[AclEvent] private[io] implicit val realmEventEncoder: Encoder[RealmEvent] = deriveConfiguredEncoder[RealmEvent] private[io] implicit val realmEventDecoder: Decoder[RealmEvent] = deriveConfiguredDecoder[RealmEvent] override val identifier: Int = 1225 override def manifest(o: AnyRef): String = o match { case _: PermissionsEvent => "permissions-event" case _: AclEvent => "acl-event" case _: RealmEvent => "realm-event" case other => throw new IllegalArgumentException( s"Cannot determine manifest for unknown type: '${other.getClass.getCanonicalName}'" ) } override def toBinary(o: AnyRef): Array[Byte] = o match { case ev: PermissionsEvent => ev.asJson.printWith(printer).getBytes(utf8) case ev: AclEvent => ev.asJson.printWith(printer).getBytes(utf8) case ev: RealmEvent => ev.asJson.printWith(printer).getBytes(utf8) case other => throw new IllegalArgumentException(s"Cannot serialize unknown type: '${other.getClass.getCanonicalName}'") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { case "permissions-event" => val str = new String(bytes, utf8) decode[PermissionsEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'PermissionsEvent'")) case "acl-event" => val str = new String(bytes, utf8) decode[AclEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'AclEvent'")) case "realm-event" => val str = new String(bytes, utf8) decode[RealmEvent](str) .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'RealmEvent'")) case other => throw new IllegalArgumentException(s"Cannot deserialize type with unknown manifest: '$other'") } }