akka.http.scaladsl.marshalling.Marshaller Scala Examples
The following examples show how to use akka.http.scaladsl.marshalling.Marshaller.
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: JacksonSupport.scala From asura with MIT License | 5 votes |
package asura.core.util import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes._ import akka.http.scaladsl.model.{HttpEntity, HttpRequest} import akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller import akka.stream.Materializer import asura.common.util.JsonUtils import com.sksamuel.elastic4s.Indexable import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} import scala.reflect.ClassTag object JacksonSupport extends JsonUtils { val mapper = JsonUtils.mapper implicit def JacksonMarshaller: ToEntityMarshaller[AnyRef] = { Marshaller.withFixedContentType(`application/json`) { obj => HttpEntity(`application/json`, mapper.writeValueAsString(obj).getBytes("UTF-8")) } } implicit def jacksonUnmarshaller[T <: AnyRef](implicit c: ClassTag[T]): FromRequestUnmarshaller[T] = { new FromRequestUnmarshaller[T] { override def apply(request: HttpRequest)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] = { request.entity.toStrict(5 seconds).map(_.data.decodeString("UTF-8")).map { str => mapper.readValue(str, c.runtimeClass).asInstanceOf[T] } } } } implicit def jacksonJsonIndexable[T]: Indexable[T] = { new Indexable[T] { override def json(t: T): String = mapper.writeValueAsString(t) } } }
Example 2
Source File: SealedOneofSupport.scala From ForestFlow with Apache License 2.0 | 5 votes |
package ai.forestflow.scalapb import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{ContentTypeRange, MediaRanges, MediaType} import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import scalapb.GeneratedSealedOneof import scala.reflect.ClassTag // application/octet-stream trait SealedOneofSupport { private val applicableMediaTypes: List[ContentTypeRange] = List( MediaRanges.`*/*`, MediaType.applicationBinary("octet-stream", MediaType.NotCompressible) ) implicit def GeneratedSealedOneofBinaryUnmarshaller[T <: GeneratedSealedOneof]: FromEntityUnmarshaller[GeneratedSealedOneof] = { Unmarshaller.byteArrayUnmarshaller.forContentTypes(applicableMediaTypes: _*).map(b => b.asInstanceOf[GeneratedSealedOneof].asMessage.companion.parseFrom(b).asInstanceOf[T]) } implicit def GeneratedSealedOneofBinaryMarshaller[T <: GeneratedSealedOneof](implicit tag: ClassTag[T]): ToEntityMarshaller[T] = { val result = Marshaller.ByteArrayMarshaller.compose((c: T) => c.asMessage.toByteArray) result } }
Example 3
Source File: FlatBuffersSupport.scala From ForestFlow with Apache License 2.0 | 5 votes |
package ai.forestflow.akka.flatbuffers import java.nio.ByteBuffer import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{ContentTypeRange, MediaRange, MediaRanges, MediaType} import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import com.google.flatbuffers.Table import scala.collection.mutable import scala.reflect.ClassTag // application/octet-stream trait FlatBuffersSupport { var myMap : mutable.Map[ClassTag[_], AnyRef => AnyRef] = mutable.Map.empty[ClassTag[_], AnyRef => AnyRef] private val applicableMediaTypes: List[ContentTypeRange] = List( MediaRanges.`* Unmarshaller.byteArrayUnmarshaller.forContentTypes(applicableMediaTypes: _*).map(b => fn(java.nio.ByteBuffer.wrap(b)).asInstanceOf[T]) } implicit def flatBufferBinaryMarshaller[T <: Table](implicit tag: ClassTag[T]): ToEntityMarshaller[T] = { println("marshalling something") val result = Marshaller.ByteArrayMarshaller.compose((c: T) => c.getByteBuffer.array()) println("done") result } }
Example 4
Source File: AkkaHttpLambdaHandlerSpec.scala From scala-server-lambda with MIT License | 5 votes |
package io.github.howardjohn.lambda.akka import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.model.headers.RawHeader import akka.http.scaladsl.model.{HttpEntity, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.stream.ActorMaterializer import io.circe.parser.decode import io.circe.syntax._ import io.circe.{Decoder, Encoder} import io.github.howardjohn.lambda.LambdaHandlerBehavior import io.github.howardjohn.lambda.LambdaHandlerBehavior._ import org.scalatest.{BeforeAndAfterAll, FeatureSpec, GivenWhenThen} import scala.concurrent.Future class AkkaHttpLambdaHandlerSpec extends FeatureSpec with LambdaHandlerBehavior with GivenWhenThen with BeforeAndAfterAll { implicit val system: ActorSystem = ActorSystem("test") implicit val materializer: ActorMaterializer = ActorMaterializer() implicit val ec = scala.concurrent.ExecutionContext.Implicits.global val route: Route = path("hello") { (get & parameter("times".as[Int] ? 1)) { times => complete { Seq .fill(times)("Hello World!") .mkString(" ") } } } ~ path("long") { get { Thread.sleep(1000) complete("") } } ~ path("post") { post { entity(as[String]) { body => complete(body) } } } ~ path("json") { post { import CirceJsonMarshalling._ import io.circe.generic.auto._ entity(as[JsonBody]) { entity => complete(LambdaHandlerBehavior.jsonReturn.asJson) } } } ~ path("exception") { get { throw RouteException() } } ~ path("error") { get { complete(StatusCodes.InternalServerError) } } ~ path("header") { get { headerValueByName(inputHeader) { header => respondWithHeaders(RawHeader(outputHeader, outputHeaderValue)) { complete(header) } } } } val handler = new AkkaHttpLambdaHandler(route) scenariosFor(behavior(handler)) override def afterAll(): Unit = { materializer.shutdown() system.terminate() } } object CirceJsonMarshalling { implicit final def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A] = Unmarshaller.stringUnmarshaller .forContentTypes(`application/json`) .flatMap { ctx => mat => json => decode[A](json).fold(Future.failed, Future.successful) } implicit final def marshaller[A: Encoder]: ToEntityMarshaller[A] = Marshaller.withFixedContentType(`application/json`) { a => HttpEntity(`application/json`, a.asJson.noSpaces) } }
Example 5
Source File: AkkaHttpHelpers.scala From akka-viz with MIT License | 5 votes |
package akkaviz.server import akka.http.scaladsl.marshalling.{Marshal, Marshaller} import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart import akka.http.scaladsl.model.{HttpEntity, HttpResponse, MediaTypes} import akka.http.scaladsl.server.{Directives, StandardRoute} import akka.stream.scaladsl.{Flow, Source} import scala.concurrent.ExecutionContext trait AkkaHttpHelpers { def asJsonArray[T](implicit m: Marshaller[T, String], ec: ExecutionContext): Flow[T, HttpEntity.ChunkStreamPart, _] = { Flow.apply[T] .mapAsync[String](4)(t => Marshal(t).to[String]) .scan[Option[ChunkStreamPart]](None) { case (None, s: String) => Some(ChunkStreamPart(s)) case (_, s: String) => Some(ChunkStreamPart(s",${s}")) }.mapConcat(_.toList) .prepend(Source.single(ChunkStreamPart("["))) .concat(Source.single(ChunkStreamPart("]"))) } def completeAsJson[T](source: Source[T, _])(implicit m: Marshaller[T, String], ec: ExecutionContext): StandardRoute = { Directives.complete(HttpResponse( entity = HttpEntity.Chunked(MediaTypes.`application/json`, source.via(asJsonArray)) )) } } object AkkaHttpHelpers extends AkkaHttpHelpers
Example 6
Source File: ArchiveSupport.scala From akka-viz with MIT License | 5 votes |
package akkaviz.server import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.marshalling.Marshalling.WithFixedContentType import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.stream.scaladsl.{Flow, Source} import akkaviz.config.Config import akkaviz.persistence.{PersistenceSources, ReceivedRecord} import akkaviz.rest import com.datastax.driver.core.utils.UUIDs import org.reactivestreams.Publisher import scala.concurrent.ExecutionContext.Implicits.global trait ArchiveSupport { def isArchiveEnabled: Boolean def receivedOf(ref: String): Source[ReceivedRecord, _] def receivedBetween(ref: String, ref2: String): Source[ReceivedRecord, _] def archiveRouting: Route = get { pathPrefix("messages") { if (isArchiveEnabled) { path("of" / Segment) { ref => AkkaHttpHelpers.completeAsJson(receivedOf(ref).via(receivedRecordToRestReceived)) } ~ path("between" / Segment / Segment) { (ref, ref2) => AkkaHttpHelpers.completeAsJson(receivedBetween(ref, ref2).via(receivedRecordToRestReceived)) } } else { reject } } } private[this] implicit val receivedRecordMarshaller: Marshaller[rest.Received, String] = Marshaller.strict { received => WithFixedContentType(MediaTypes.`application/json`, () => upickle.default.write(received)) } private[this] def receivedRecordToRestReceived = Flow[ReceivedRecord].map { rr => rest.Received(rr.millis, rr.direction, rr.first, rr.second, rr.data) } }
Example 7
Source File: AkkaHttpHelpersTest.scala From akka-viz with MIT License | 5 votes |
package akkaviz.server import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.marshalling.Marshalling.WithFixedContentType import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.testkit.ScalatestRouteTest import akka.stream.ActorMaterializer import akka.stream.scaladsl._ import akka.stream.testkit.scaladsl._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.{FunSuite, Matchers} import scala.concurrent.duration._ class AkkaHttpHelpersTest extends FunSuite with Matchers with ScalaFutures with ScalatestRouteTest { import AkkaHttpHelpers._ override implicit val patienceConfig: PatienceConfig = PatienceConfig(10.seconds) private[this] implicit val system: ActorSystem = ActorSystem() private[this] implicit val materializer = ActorMaterializer()(system) private[this] implicit val marshaller = Marshaller.strict[Int, String] { received => WithFixedContentType(MediaTypes.`application/json`, () => String.valueOf(received)) } test("Should work for empty Source") { whenReady(Source.empty[Int].via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[]" } } test("Should work for single element in Source") { whenReady(Source.single(1).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[1]" } } test("Should work for multiple elements element in Source") { whenReady(Source(List(1, 2, 3)).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[1,2,3]" } } test("asJsonArray is incremental") { val (pub, sub) = TestSource.probe[Int] .via(asJsonArray) .map(_.data().utf8String) .toMat(TestSink.probe[String])(Keep.both) .run() pub.sendNext(1) sub.request(10) sub.expectNext("[") pub.sendNext(2) sub.expectNext("1") pub.sendNext(3) sub.expectNext(",2") pub.sendComplete() sub.expectNext(",3") sub.expectNext("]") sub.expectComplete() } test("completeAsJson works properly") { val source = Source(List(1, 2, 3)) Get() ~> completeAsJson(source) ~> check { chunks should have size (5) responseAs[String] shouldEqual "[1,2,3]" } } }
Example 8
Source File: SprayJsonSupport.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.interfaces import scala.language.implicitConversions import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, Marshaller } import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshaller } import akka.http.scaladsl.model.{ MediaTypes, HttpCharsets } import spray.json._ trait SprayJsonSupport { implicit def sprayJsonUnmarshallerConverter[T](reader: RootJsonReader[T]): FromEntityUnmarshaller[T] = sprayJsonUnmarshaller(reader) implicit def sprayJsonUnmarshaller[T](implicit reader: RootJsonReader[T]): FromEntityUnmarshaller[T] = sprayJsValueUnmarshaller.map(jsonReader[T].read) implicit def sprayJsValueUnmarshaller: FromEntityUnmarshaller[JsValue] = Unmarshaller.byteStringUnmarshaller.mapWithCharset { (data, charset) ⇒ val input = if (charset == HttpCharsets.`UTF-8`) ParserInput(data.toArray) else ParserInput(data.decodeString(charset.nioCharset.name)) // FIXME: identify charset by instance, not by name! JsonParser(input) } implicit def sprayJsonMarshallerConverter[T](writer: RootJsonWriter[T])(implicit printer: JsonPrinter = PrettyPrinter): ToEntityMarshaller[T] = sprayJsonMarshaller[T](writer, printer) implicit def sprayJsonMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = PrettyPrinter): ToEntityMarshaller[T] = sprayJsValueMarshaller compose writer.write implicit def sprayJsValueMarshaller(implicit printer: JsonPrinter = PrettyPrinter): ToEntityMarshaller[JsValue] = Marshaller.StringMarshaller.wrap(MediaTypes.`application/json`)(printer) } object SprayJsonSupport extends SprayJsonSupport
Example 9
Source File: GraphQLRequestUnmarshaller.scala From graphql-gateway with Apache License 2.0 | 5 votes |
package sangria.gateway.http import java.nio.charset.Charset import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model._ import akka.http.scaladsl.model.headers.Accept import akka.http.scaladsl.server.Directive0 import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.util.ByteString import sangria.ast.Document import sangria.parser.QueryParser import sangria.renderer.{QueryRenderer, QueryRendererConfig} import scala.collection.immutable.Seq object GraphQLRequestUnmarshaller { val `application/graphql` = MediaType.applicationWithFixedCharset("graphql", HttpCharsets.`UTF-8`, "graphql") def explicitlyAccepts(mediaType: MediaType): Directive0 = headerValuePF { case Accept(ranges) if ranges.exists(range ⇒ !range.isWildcard && range.matches(mediaType)) ⇒ ranges }.flatMap(_ ⇒ pass) def includeIf(include: Boolean): Directive0 = if (include) pass else reject def unmarshallerContentTypes: Seq[ContentTypeRange] = mediaTypes.map(ContentTypeRange.apply) def mediaTypes: Seq[MediaType.WithFixedCharset] = List(`application/graphql`) implicit final def documentMarshaller(implicit config: QueryRendererConfig = QueryRenderer.Compact): ToEntityMarshaller[Document] = Marshaller.oneOf(mediaTypes: _*) { mediaType ⇒ Marshaller.withFixedContentType(ContentType(mediaType)) { json ⇒ HttpEntity(mediaType, QueryRenderer.render(json, config)) } } implicit final val documentUnmarshaller: FromEntityUnmarshaller[Document] = Unmarshaller.byteStringUnmarshaller .forContentTypes(unmarshallerContentTypes: _*) .map { case ByteString.empty ⇒ throw Unmarshaller.NoContentException case data ⇒ import sangria.parser.DeliveryScheme.Throw QueryParser.parse(data.decodeString(Charset.forName("UTF-8"))) } }
Example 10
Source File: MetricFamilySamplesEntity.scala From prometheus-akka-http with MIT License | 5 votes |
package com.lonelyplanet.prometheus.api import java.io.{StringWriter, Writer} import java.util import akka.http.scaladsl.marshalling.{ToEntityMarshaller, Marshaller} import akka.http.scaladsl.model._ import io.prometheus.client.Collector.MetricFamilySamples import io.prometheus.client.CollectorRegistry import io.prometheus.client.exporter.common.TextFormat case class MetricFamilySamplesEntity(samples: util.Enumeration[MetricFamilySamples]) object MetricFamilySamplesEntity { private val mediaTypeParams = Map("version" -> "0.0.4") private val mediaType = MediaType.customWithFixedCharset("text", "plain", HttpCharsets.`UTF-8`, params = mediaTypeParams) def fromRegistry(collectorRegistry: CollectorRegistry): MetricFamilySamplesEntity = { MetricFamilySamplesEntity(collectorRegistry.metricFamilySamples()) } def toPrometheusTextFormat(e: MetricFamilySamplesEntity): String = { val writer: Writer = new StringWriter() TextFormat.write004(writer, e.samples) writer.toString } implicit val metricsFamilySamplesMarshaller: ToEntityMarshaller[MetricFamilySamplesEntity] = { Marshaller.withFixedContentType(mediaType) { s => HttpEntity(mediaType, toPrometheusTextFormat(s)) } } }
Example 11
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 12
Source File: Json4sSupport.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.http.json import java.lang.reflect.InvocationTargetException import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.util.ByteString import org.json4s.JsonAST.JValue import org.json4s.{Formats, MappingException, Serialization} implicit def json4sMarshaller[A <: AnyRef]( implicit serialization: Serialization, formats: Formats, shouldWritePretty: ShouldWritePretty = ShouldWritePretty.False ): ToEntityMarshaller[A] = { shouldWritePretty match { case ShouldWritePretty.False => jsonStringMarshaller.compose(serialization.write[A]) case ShouldWritePretty.True => jsonStringMarshaller.compose(serialization.writePretty[A]) } } implicit def json4sJValueMarshaller[A <: JValue]( implicit serialization: Serialization, formats: Formats, shouldWritePretty: ShouldWritePretty = ShouldWritePretty.False ): ToEntityMarshaller[A] = { shouldWritePretty match { case ShouldWritePretty.False => jsonStringMarshaller.compose(serialization.write[A]) case ShouldWritePretty.True => jsonStringMarshaller.compose(serialization.writePretty[A]) } } }
Example 13
Source File: GenCodecSupport.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpavsystemgencodec import akka.http.scaladsl.marshalling.{ Marshaller, ToEntityMarshaller } import akka.http.scaladsl.model.ContentTypeRange import akka.http.scaladsl.model.MediaType import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshaller } import akka.util.ByteString import com.avsystem.commons.serialization.GenCodec import com.avsystem.commons.serialization.json.{ JsonStringInput, JsonStringOutput } import scala.collection.immutable.Seq object GenCodecSupport extends GenCodecSupport {} trait GenCodecSupport { def unmarshallerContentTypes: Seq[ContentTypeRange] = mediaTypes.map(ContentTypeRange.apply) def mediaTypes: Seq[MediaType.WithFixedCharset] = List(`application/json`) private val jsonStringUnmarshaller = Unmarshaller.byteStringUnmarshaller .forContentTypes(unmarshallerContentTypes: _*) .mapWithCharset { case (ByteString.empty, _) => throw Unmarshaller.NoContentException case (data, charset) => data.decodeString(charset.nioCharset.name) } private val jsonStringMarshaller = Marshaller.oneOf(mediaTypes: _*)(Marshaller.stringMarshaller) implicit def marshaller[A: GenCodec]: ToEntityMarshaller[A] = jsonStringMarshaller.compose(JsonStringOutput.write(_)) }
Example 14
Source File: UpickleCustomizationSupport.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpupickle import akka.http.javadsl.common.JsonEntityStreamingSupport import akka.http.scaladsl.common.EntityStreamingSupport import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling, ToEntityMarshaller } import akka.http.scaladsl.model.{ ContentTypeRange, HttpEntity, MediaType, MessageEntity } import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshal, Unmarshaller } import akka.http.scaladsl.util.FastFuture import akka.stream.scaladsl.{ Flow, Source } import akka.util.ByteString import UpickleCustomizationSupport._ import scala.collection.immutable.Seq import scala.concurrent.Future import scala.util.Try import scala.util.control.NonFatal // This companion object only exists for binary compatibility as adding methods with default implementations // (including val's as they create synthetic methods) is not compatible. private object UpickleCustomizationSupport { private def jsonStringUnmarshaller(support: UpickleCustomizationSupport) = Unmarshaller.byteStringUnmarshaller .forContentTypes(support.unmarshallerContentTypes: _*) .mapWithCharset { case (ByteString.empty, _) => throw Unmarshaller.NoContentException case (data, charset) => data.decodeString(charset.nioCharset.name) } private def jsonSourceStringMarshaller(support: UpickleCustomizationSupport) = Marshaller.oneOf(support.mediaTypes: _*)(support.sourceByteStringMarshaller) private def jsonStringMarshaller(support: UpickleCustomizationSupport) = Marshaller.oneOf(support.mediaTypes: _*)(Marshaller.stringMarshaller) } implicit def sourceMarshaller[A](implicit writes: apiInstance.Writer[A], support: JsonEntityStreamingSupport = EntityStreamingSupport.json() ): ToEntityMarshaller[SourceOf[A]] = jsonSourceStringMarshaller(this).compose(jsonSource[A]) }
Example 15
Source File: CirceSupport.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.utils.json import akka.http.scaladsl.marshalling.{Marshaller, _} import akka.http.scaladsl.model.MediaTypes._ import akka.http.scaladsl.model.{HttpEntity, HttpRequest} import akka.http.scaladsl.unmarshalling.{Unmarshaller, _} import io.circe._ import io.circe.parser._ import io.circe.syntax._ import cats.syntax.either._ import scala.concurrent.Future object CirceSupport { val printer = Printer.noSpaces.copy(dropNullValues = true) def marshallResponse[T: Encoder]: ToResponseMarshaller[T] = Marshaller.fromToEntityMarshaller[T]()(marshallEntity) def unmarshallRequest[T: Decoder]: FromRequestUnmarshaller[T] = Unmarshaller .identityUnmarshaller[HttpRequest] .map(_.entity) .flatMap[T](unmarshallEntity[T]: Unmarshaller[HttpEntity, T]) .asScala def marshallEntity[T: Encoder]: ToEntityMarshaller[T] = Marshaller.stringMarshaller(`application/json`).compose((_: T).asJson.printWith(printer)) def unmarshallEntity[T: Decoder]: FromEntityUnmarshaller[T] = Unmarshaller.stringUnmarshaller .forContentTypes(`application/json`) .flatMap(implicit ec => _ => s => Future.fromTry(parse(s).toTry.flatMap(_.as[T].toTry))) object implicits { implicit def marshallResponseCirce[T: Encoder]: ToResponseMarshaller[T] = marshallResponse[T] implicit def unmarshallRequestCirce[T: Decoder]: FromRequestUnmarshaller[T] = unmarshallRequest[T] implicit def marshallEntityCirce[T: Encoder]: ToEntityMarshaller[T] = marshallEntity[T] implicit def unmarshallEntityCirce[T: Decoder]: FromEntityUnmarshaller[T] = unmarshallEntity[T] } }
Example 16
Source File: InnerSuite.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.akkaHttp import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToResponseMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.testkit.ScalatestRouteTest import ru.tinkoff.tschema.syntax._ import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers import scala.language.reflectiveCalls class InnerSuite extends AsyncFlatSpec with ScalatestRouteTest with Matchers { object impl { object first { def get: String = "first" def post(message: String) = s"first $message" } val second = new { def get: String = "second" def post(message: String) = s"second $message" } } implicit val unitAsPlainText: ToResponseMarshaller[Unit] = Marshaller.strict(_ => Marshalling.WithFixedContentType(ContentTypes.NoContentType, () => HttpResponse())) def api = ( groupPrefix("first") |> (( opGet |> $$[String] ) <> ( opPost |> queryParam[String]("message") |> $$[String] )) ) <> ( groupPrefix("second") |> (( opGet |> $$[String] ) <> ( opPost |> body[String]("message") |> $$[String] )) ) val route = MkRoute(api)(impl) "first group" should "handle get" in Get("/first") ~> route ~> check { responseAs[String] shouldBe "first" } it should "handle post" in Post("/first?message=hello+oleg") ~> route ~> check { responseAs[String] shouldBe "first hello oleg" } "second group" should "handle get" in Get("/second") ~> route ~> check { responseAs[String] shouldBe "second" } it should "handle post" in Post("/second", "hello oleg") ~> route ~> check { responseAs[String] shouldBe "second hello oleg" } }
Example 17
Source File: ZIODirectives.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.server.{ Directive, Directive1, Route, RouteResult } import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.server.directives.RouteDirectives import akka.http.scaladsl.util.FastFuture._ import zio.{ DefaultRuntime, Task, ZIO } import scala.concurrent.{ Future, Promise } import scala.util.{ Failure, Success } def zioCompleteOrRecoverWith(magnet: ZIOCompleteOrRecoverWithMagnet): Directive1[Throwable] = magnet.directive } object ZIODirectives extends ZIODirectives trait ZIOCompleteOrRecoverWithMagnet { def directive: Directive1[Throwable] } object ZIOCompleteOrRecoverWithMagnet extends ZIODirectives { implicit def apply[T]( task: => Task[T] )(implicit m: ToResponseMarshaller[T]): ZIOCompleteOrRecoverWithMagnet = new ZIOCompleteOrRecoverWithMagnet { override val directive: Directive1[Throwable] = Directive[Tuple1[Throwable]] { inner => ctx => val future = unsafeRunToFuture(task) import ctx.executionContext future.fast.transformWith { case Success(res) => ctx.complete(res) case Failure(error) => inner(Tuple1(error))(ctx) } } } }
Example 18
Source File: application.scala From phobos with Apache License 2.0 | 5 votes |
package ru.tinkoff.phobos.akka_http.marshalling import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{HttpCharsets, HttpEntity, MediaTypes} import akka.http.scaladsl.unmarshalling.{FromResponseUnmarshaller, Unmarshaller} import ru.tinkoff.phobos.decoding.XmlDecoder import ru.tinkoff.phobos.encoding.XmlEncoder object application { implicit def soapApplicationXmlMarshaller[T](implicit encoder: XmlEncoder[T]): ToEntityMarshaller[T] = Marshaller.withFixedContentType(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) { body => HttpEntity(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`, encoder.encode(body)) } implicit def soapApplicationXmlUnmarshaller[T](implicit decoder: XmlDecoder[T]): FromResponseUnmarshaller[T] = Unmarshaller.messageUnmarshallerFromEntityUnmarshaller(Unmarshaller.stringUnmarshaller.map { str => decoder.decode(str).fold(err => throw err, identity) }) }
Example 19
Source File: text.scala From phobos with Apache License 2.0 | 5 votes |
package ru.tinkoff.phobos.akka_http.marshalling import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.ContentTypes.`text/xml(UTF-8)` import akka.http.scaladsl.model.HttpEntity import akka.http.scaladsl.unmarshalling.{FromResponseUnmarshaller, Unmarshaller} import ru.tinkoff.phobos.decoding.XmlDecoder import ru.tinkoff.phobos.encoding.XmlEncoder object text { implicit def soapTextXmlMarshaller[T](implicit encoder: XmlEncoder[T]): ToEntityMarshaller[T] = Marshaller.withFixedContentType(`text/xml(UTF-8)`) { body => HttpEntity(`text/xml(UTF-8)`, encoder.encode(body)) } implicit def soapTextXmlUnmarshaller[T](implicit decoder: XmlDecoder[T]): FromResponseUnmarshaller[T] = Unmarshaller.messageUnmarshallerFromEntityUnmarshaller(Unmarshaller.stringUnmarshaller.map { str => decoder.decode(str).fold(err => throw err, identity) }) }
Example 20
Source File: PlayJsonSupport.scala From akka-cluster-manager with MIT License | 5 votes |
package io.orkestra.cluster.management import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.HttpCharsets import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.stream.Materializer import play.api.libs.json._ import scala.concurrent.ExecutionContext import scala.language.implicitConversions trait PlayJsonSupport { type Printer = (JsValue ⇒ String) def read[T](jsValue: JsValue)(implicit reads: Reads[T]): T = { reads.reads(jsValue) match { case s: JsSuccess[T] ⇒ s.get case e: JsError ⇒ throw JsResultException(e.errors) } } implicit def playJsonUnmarshallerConverter[T](reads: Reads[T])(implicit ec: ExecutionContext, mat: Materializer): FromEntityUnmarshaller[T] = playJsonUnmarshaller(reads, ec, mat) implicit def playJsonUnmarshaller[T](implicit reads: Reads[T], ec: ExecutionContext, mat: Materializer): FromEntityUnmarshaller[T] = playJsValueUnmarshaller.map(read[T]) implicit def playJsValueUnmarshaller(implicit ec: ExecutionContext, mat: Materializer): FromEntityUnmarshaller[JsValue] = Unmarshaller.byteStringUnmarshaller.forContentTypes(`application/json`).mapWithCharset { (data, charset) ⇒ if (charset == HttpCharsets.`UTF-8`) Json.parse(data.toArray) else Json.parse(data.decodeString(charset.nioCharset.name)) // FIXME: identify charset by instance, not by name! } implicit def playJsonMarshallerConverter[T](writes: Writes[T])(implicit printer: Printer = Json.prettyPrint, ec: ExecutionContext): ToEntityMarshaller[T] = playJsonMarshaller[T](writes, printer, ec) implicit def playJsonMarshaller[T](implicit writes: Writes[T], printer: Printer = Json.prettyPrint, ec: ExecutionContext): ToEntityMarshaller[T] = playJsValueMarshaller[T].compose(writes.writes) implicit def playJsValueMarshaller[T](implicit writes: Writes[T], printer: Printer = Json.prettyPrint, ec: ExecutionContext): ToEntityMarshaller[JsValue] = Marshaller.StringMarshaller.wrap(`application/json`)(printer) } object PlayJsonSupport extends PlayJsonSupport
Example 21
Source File: DisjunctionMarshaller.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.marshaller import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller } import akka.http.scaladsl.model.{ HttpEntity, _ } import com.github.dnvriend.component.simpleserver.marshaller.DisjunctionMarshaller.{ ErrorMessage, FatalError } import spray.json.JsonWriter import scalaz.Scalaz._ import scalaz._ object DisjunctionMarshaller { trait ErrorMessage { def description: String } trait FatalError extends ErrorMessage trait NonFatalError extends ErrorMessage } trait DisjunctionMarshaller { type DisjunctionNel[A, +B] = Disjunction[NonEmptyList[A], B] implicit def disjunctionMarshaller[A1, A2, B](implicit m1: Marshaller[A1, B], m2: Marshaller[A2, B]): Marshaller[Disjunction[A1, A2], B] = Marshaller { implicit ec => { case -\/(a1) => m1(a1) case \/-(a2) => m2(a2) } } implicit def errorDisjunctionMarshaller[A](implicit w1: JsonWriter[A], w2: JsonWriter[List[String]]): ToResponseMarshaller[DisjunctionNel[String, A]] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { case -\/(errors) => HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.toList).compactPrint) ) case \/-(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } implicit def errorMessageDisjunctionMarshaller[A <: ErrorMessage, B](implicit w1: JsonWriter[B], w2: JsonWriter[List[String]]): ToResponseMarshaller[DisjunctionNel[A, B]] = { def createResponseWithStatusCode(code: StatusCode, errors: List[ErrorMessage]) = HttpResponse( status = code, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.map(_.description)).compactPrint) ) Marshaller.withFixedContentType(MediaTypes.`application/json`) { case -\/(errors) if errors.toList.exists(_.isInstanceOf[FatalError]) => createResponseWithStatusCode(StatusCodes.InternalServerError, errors.toList) case -\/(errors) => createResponseWithStatusCode(StatusCodes.BadRequest, errors.toList) case \/-(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } } } trait ValidationMarshaller { implicit def validationMarshaller[A1, A2, B](implicit m1: Marshaller[A1, B], m2: Marshaller[A2, B]): Marshaller[Validation[A1, A2], B] = Marshaller { implicit ec => { case Failure(a1) => m1(a1) case Success(a2) => m2(a2) } } implicit def errorValidationMarshaller[A](implicit w1: JsonWriter[A], w2: JsonWriter[List[String]]): ToResponseMarshaller[ValidationNel[String, A]] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { case Failure(errors) => HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.toList).compactPrint) ) case Success(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } implicit def errorMessageValidationMarshaller[A <: ErrorMessage, B](implicit w1: JsonWriter[B], w2: JsonWriter[List[String]]): ToResponseMarshaller[ValidationNel[A, B]] = { def createResponseWithStatusCode(code: StatusCode, errors: List[ErrorMessage]) = HttpResponse( status = code, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.map(_.description)).compactPrint) ) Marshaller.withFixedContentType(MediaTypes.`application/json`) { case Failure(errors) if errors.toList.exists(_.isInstanceOf[FatalError]) => createResponseWithStatusCode(StatusCodes.InternalServerError, errors.toList) case Failure(errors) => createResponseWithStatusCode(StatusCodes.BadRequest, errors.toList) case Success(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } } }
Example 22
Source File: PlayJsonSupport.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.http import java.nio.charset.Charset import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.util.ByteString import play.api.libs.json._ trait PlayJsonSupport { private val mediaTypes: Seq[MediaType.WithFixedCharset] = Seq(MediaType.applicationWithFixedCharset("json", HttpCharsets.`UTF-8`, "js")) private val unmarshallerContentTypes: Seq[ContentTypeRange] = mediaTypes.map(ContentTypeRange.apply) implicit val playJsonMarshaller: ToEntityMarshaller[JsValue] = { Marshaller.oneOf(mediaTypes: _*) { mediaType => Marshaller.withFixedContentType(ContentType(mediaType)) { json => HttpEntity(mediaType, json.toString) } } } implicit val playJsonUnmarshaller: FromEntityUnmarshaller[JsValue] = { Unmarshaller.byteStringUnmarshaller .forContentTypes(unmarshallerContentTypes: _*) .map { case ByteString.empty => throw Unmarshaller.NoContentException case data => Json.parse(data.decodeString(Charset.forName("UTF-8"))) } } trait ToPlayJson[T] { def toJson(msg: T): JsValue } import scala.language.reflectiveCalls object ToPlayJson { type ToPlayJsonReflective = { def toJson: JsValue } implicit def forToJson[A <: ToPlayJsonReflective] = new ToPlayJson[A] { def toJson(js: A) = js.toJson } implicit def forPlayJson[A <: JsValue] = new ToPlayJson[A] { def toJson(js: A) = js } } implicit object JsErrorJsonWriter extends Writes[JsError] { def writes(o: JsError): JsValue = Json.obj( "errors" -> JsArray( o.errors.map { case (path, validationErrors) => Json.obj( "path" -> Json.toJson(path.toString()), "validationErrors" -> JsArray(validationErrors.map(validationError => Json.obj( "message" -> JsString(validationError.message), "args" -> JsArray(validationError.args.map { case x: Int => JsNumber(x) case x => JsString(x.toString) }) ))) ) } ) ) } }
Example 23
Source File: SangriaGraphQLSupport.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.http import java.nio.charset.Charset import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.util.ByteString import sangria.ast.Document import sangria.parser.QueryParser import sangria.renderer.{QueryRenderer, QueryRendererConfig} trait SangriaGraphQLSupport { private val mediaTypes: Seq[MediaType.WithFixedCharset] = Seq(MediaType.applicationWithFixedCharset("graphql", HttpCharsets.`UTF-8`, "graphql")) private val unmarshallerContentTypes: Seq[ContentTypeRange] = mediaTypes.map(ContentTypeRange.apply) implicit def documentMarshaller(implicit config: QueryRendererConfig = QueryRenderer.Compact): ToEntityMarshaller[Document] = { Marshaller.oneOf(mediaTypes: _*) { mediaType ⇒ Marshaller.withFixedContentType(ContentType(mediaType)) { json ⇒ HttpEntity(mediaType, QueryRenderer.render(json, config)) } } } implicit val documentUnmarshaller: FromEntityUnmarshaller[Document] = { Unmarshaller.byteStringUnmarshaller .forContentTypes(unmarshallerContentTypes: _*) .map { case ByteString.empty ⇒ throw Unmarshaller.NoContentException case data ⇒ import sangria.parser.DeliveryScheme.Throw QueryParser.parse(data.decodeString(Charset.forName("UTF-8"))) } } }
Example 24
Source File: MatcherResponse.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http.entities import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller} import akka.http.scaladsl.model.{StatusCodes => C, _} import akka.util.ByteString import com.wavesplatform.dex.domain.bytes.ByteStr.byteStrFormat import com.wavesplatform.dex.domain.order.Order import com.wavesplatform.dex.error import com.wavesplatform.dex.error.MatcherError import com.wavesplatform.dex.meta.getSimpleName import play.api.libs.json._ sealed class MatcherResponse(val statusCode: StatusCode, val content: MatcherResponseContent) { def this(code: StatusCode, error: MatcherError) = this(code, MatcherResponseContent.Single(Json.toJsObject(error))) def this(code: StatusCode, error: JsObject) = this(code, MatcherResponseContent.Single(error)) def status: String = getSimpleName(this) } object MatcherResponse { val toResponseMarshaller: ToResponseMarshaller[MatcherResponse] = Marshaller.opaque(toHttpResponse) implicit val matcherResponseWrites: Writes[MatcherResponse] = Writes(toJson) def toHttpResponse(x: MatcherResponse): HttpResponse = HttpResponse( x.statusCode, entity = HttpEntity.Strict(ContentTypes.`application/json`, ByteString(Json.stringify(toJson(x)))) ) def toJson(x: MatcherResponse): JsValue = backwardCompatibleWrapper( x.status, x.statusCode, x.content match { case MatcherResponseContent.Single(r) => r case MatcherResponseContent.Multiple(xs) => Json.obj("message" -> Json.arr(xs.map(toJson))) } ) private def backwardCompatibleWrapper(status: String, code: StatusCode, json: JsObject): JsValue = { Json .obj( "success" -> ( code match { case _: C.Success => true case _ => false } ), "status" -> status ) .deepMerge( code match { case _: C.Success => JsObject.empty case _ => Json.obj("result" -> JsNull) // For a backward compatibility } ) .deepMerge(json) } } sealed trait MatcherResponseContent object MatcherResponseContent { case class Single(content: JsObject) extends MatcherResponseContent case class Multiple(content: List[MatcherResponse]) extends MatcherResponseContent } case class SimpleResponse(code: StatusCode, js: JsObject) extends MatcherResponse(code, MatcherResponseContent.Single(js)) object SimpleResponse { def apply(code: StatusCode, message: String): SimpleResponse = new SimpleResponse(code, Json.toJsObject(HttpMessage(message))) def apply[T](response: T, code: StatusCode = C.OK)(implicit writes: OWrites[T]): SimpleResponse = new SimpleResponse(code, writes.writes(response)) } case class OrderCanceled(orderId: Order.Id) extends MatcherResponse(C.OK, Json.obj("orderId" -> orderId)) case class OrderDeleted(orderId: Order.Id) extends MatcherResponse(C.OK, Json.obj("orderId" -> orderId)) case class SimpleErrorResponse(code: StatusCode, error: MatcherError) extends MatcherResponse(code, error) case class InvalidJsonResponse(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case class OrderRejected(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case class OrderCancelRejected(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case object InvalidSignature extends MatcherResponse(C.BadRequest, error.RequestInvalidSignature) case class NotImplemented(error: MatcherError) extends MatcherResponse(C.NotImplemented, error) case class CanNotPersist(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case class OrderBookUnavailable(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case object DuringStart extends MatcherResponse(C.ServiceUnavailable, error.MatcherIsStarting) case object DuringShutdown extends MatcherResponse(C.ServiceUnavailable, error.MatcherIsStopping) case object TimedOut extends MatcherResponse(C.InternalServerError, error.RequestTimeout) case class InfoNotFound(error: MatcherError) extends MatcherResponse(C.NotFound, error) case class WavesNodeUnavailable(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case class RateError(error: MatcherError, code: StatusCode = C.BadRequest) extends MatcherResponse(code, error) case object InternalError extends MatcherResponse(C.ServiceUnavailable, MatcherResponseContent.Single(Json.obj("message" -> "Internal server error"))) case class InvalidAddress(reason: String) extends MatcherResponse(C.BadRequest, error.InvalidAddress(reason))
Example 25
Source File: ApiMarshallers.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http import akka.http.scaladsl.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.{`application/json`, `text/plain`} import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller} import akka.util.ByteString import com.wavesplatform.dex.api.http.json.CustomJson import com.wavesplatform.dex.domain.transaction.ExchangeTransaction import play.api.libs.json._ import scala.util.control.Exception.nonFatalCatch import scala.util.control.NoStackTrace case class PlayJsonException(cause: Option[Throwable] = None, errors: Seq[(JsPath, Seq[JsonValidationError])] = Seq.empty) extends IllegalArgumentException(s"JSON parsing errors:\n${errors.mkString("\n")}", cause.orNull) with NoStackTrace trait ApiMarshallers { implicit lazy val ExchangeTransactionJsonWrites: Writes[ExchangeTransaction] = Writes(_.json()) private[this] lazy val jsonStringUnmarshaller = Unmarshaller.byteStringUnmarshaller .forContentTypes(`application/json`) .mapWithCharset { case (ByteString.empty, _) => throw Unmarshaller.NoContentException case (data, charset) => data.decodeString(charset.nioCharset.name) } private[this] lazy val jsonStringMarshaller = Marshaller.stringMarshaller(`application/json`) private[this] lazy val customJsonStringMarshaller = Marshaller.stringMarshaller(CustomJson.jsonWithNumbersAsStrings) implicit def playJsonUnmarshaller[A](implicit reads: Reads[A]): FromEntityUnmarshaller[A] = jsonStringUnmarshaller.map { data => val json = nonFatalCatch.withApply(t => throw PlayJsonException(cause = Some(t)))(Json.parse(data)) json.validate[A] match { case JsSuccess(value, _) => value case JsError(errors) => throw PlayJsonException(errors = errors) } } // preserve support for extracting plain strings from requests implicit val stringUnmarshaller: FromEntityUnmarshaller[String] = PredefinedFromEntityUnmarshallers.stringUnmarshaller implicit val intUnmarshaller: FromEntityUnmarshaller[Int] = stringUnmarshaller.map(_.toInt) implicit def playJsonMarshaller[A](implicit writes: Writes[A], jsValueToString: JsValue => String = Json.stringify): ToEntityMarshaller[A] = Marshaller.oneOf( jsonStringMarshaller .compose(jsValueToString) .compose(writes.writes), customJsonStringMarshaller .compose(CustomJson.writeValueAsString) .compose(writes.writes) ) // preserve support for using plain strings as request entities implicit val stringMarshaller = PredefinedToEntityMarshallers.stringMarshaller(`text/plain`) } object ApiMarshallers extends ApiMarshallers
Example 26
Source File: HydraKafkaJsonSupport.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.kafka.marshallers import akka.http.scaladsl.marshalling.{Marshaller, Marshalling} import akka.http.scaladsl.model.ContentTypes import akka.util.ByteString import hydra.core.marshallers.HydraJsonSupport import org.apache.kafka.common.{Node, PartitionInfo} import spray.json.{JsNumber, JsObject, JsString, JsValue, JsonFormat} import scala.concurrent.Future trait HydraKafkaJsonSupport extends HydraJsonSupport { implicit object NodeJsonFormat extends JsonFormat[Node] { override def write(node: Node): JsValue = { JsObject( "id" -> JsNumber(node.idString), "host" -> JsString(node.host), "port" -> JsNumber(node.port) ) } override def read(json: JsValue): Node = { json.asJsObject.getFields("id", "host", "port") match { case Seq(id, host, port) => new Node( id.convertTo[Int], host.convertTo[String], port.convertTo[Int] ) case other => spray.json.deserializationError( "Cannot deserialize Node. Invalid input: " + other ) } } } implicit object PartitionInfoJsonFormat extends JsonFormat[PartitionInfo] { import spray.json._ override def write(p: PartitionInfo): JsValue = { JsObject( "partition" -> JsNumber(p.partition()), "leader" -> p.leader().toJson, "isr" -> JsArray(p.inSyncReplicas().toJson) ) } override def read(json: JsValue): PartitionInfo = ??? } implicit val stringFormat = Marshaller[String, ByteString] { ec ⇒ s => Future.successful { List( Marshalling.WithFixedContentType( ContentTypes.`application/json`, () => ByteString(s) ) ) } } }
Example 27
Source File: DropwizardMarshallers.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.dropwizard.marshalling import java.io.StringWriter import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import com.fasterxml.jackson.databind.ObjectMapper import fr.davit.akka.http.metrics.dropwizard.DropwizardRegistry trait DropwizardMarshallers { implicit val registryToEntityMarshaller: ToEntityMarshaller[DropwizardRegistry] = { val writer = new ObjectMapper().writer() Marshaller.opaque { registry => val output = new StringWriter() try { writer.writeValue(output, registry.underlying) HttpEntity(output.toString).withContentType(ContentTypes.`application/json`) } finally { output.close() } } } } object DropwizardMarshallers extends DropwizardMarshallers
Example 28
Source File: PrometheusMarshallers.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.prometheus.marshalling import java.io.StringWriter import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{ContentType, HttpCharsets, HttpEntity, MediaTypes} import fr.davit.akka.http.metrics.prometheus.PrometheusRegistry import io.prometheus.client.exporter.common.TextFormat trait PrometheusMarshallers { val PrometheusContentType: ContentType = { MediaTypes.`text/plain` withParams Map("version" -> "0.0.4") withCharset HttpCharsets.`UTF-8` } implicit val marshaller: ToEntityMarshaller[PrometheusRegistry] = { Marshaller.opaque { registry => val output = new StringWriter() try { TextFormat.write004(output, registry.underlying.metricFamilySamples) HttpEntity(output.toString).withContentType(PrometheusContentType) } finally { output.close() } } } } object PrometheusMarshallers extends PrometheusMarshallers
Example 29
Source File: TestRegistry.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.core import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.HttpEntity import scala.collection.mutable import scala.concurrent.duration.FiniteDuration object TestRegistry { implicit val marshaller: ToEntityMarshaller[TestRegistry] = Marshaller.opaque(_ => HttpEntity.Empty) private def keyer(dimensions: Seq[Dimension]): String = dimensions.mkString(":") class TestCounter extends Counter { protected val acc = mutable.Map[String, Long]() override def inc(dimensions: Seq[Dimension] = Seq.empty): Unit = { val key = keyer(dimensions) acc.get(key) match { case Some(v) => acc += (key -> (v + 1)) case None => acc += (key -> 1) } } def value(dimensions: Seq[Dimension] = Seq.empty): Long = acc.getOrElse(keyer(dimensions), 0) } class TestGauge extends TestCounter with Gauge { override def dec(dimensions: Seq[Dimension] = Seq.empty): Unit = { val key = keyer(dimensions) acc.get(key) match { case Some(v) => acc += (key -> (v - 1)) case None => acc += (key -> -1) } } } class TestTimer extends Timer { protected val acc = mutable.Map[String, List[FiniteDuration]]() override def observe(duration: FiniteDuration, dimensions: Seq[Dimension] = Seq.empty): Unit = { val key = keyer(dimensions) acc.get(key) match { case Some(vs) => acc += (key -> (duration :: vs)) case None => acc += (key -> (duration :: Nil)) } } def values(dimensions: Seq[Dimension] = Seq.empty): List[FiniteDuration] = acc.getOrElse(keyer(dimensions), Nil) } final class TestHistogram extends Histogram { protected val acc = mutable.Map[String, List[Long]]() override def update[T](value: T, dimensions: Seq[Dimension] = Seq.empty)(implicit numeric: Numeric[T]): Unit = { val key = keyer(dimensions) acc.get(key) match { case Some(vs) => acc += (key -> (numeric.toLong(value) :: vs)) case None => acc += (key -> (numeric.toLong(value) :: Nil)) } } def values(dimensions: Seq[Dimension] = Seq.empty): List[Long] = acc.getOrElse(keyer(dimensions), Nil) } } final class TestRegistry(settings: HttpMetricsSettings = HttpMetricsSettings.default) extends HttpMetricsRegistry(settings) { import TestRegistry._ override val active = new TestGauge override val requests = new TestCounter override val receivedBytes = new TestHistogram override val responses = new TestCounter override val errors = new TestCounter override val duration = new TestTimer override val sentBytes = new TestHistogram override val connected = new TestGauge override val connections = new TestCounter }
Example 30
Source File: AkkaHttpCirceSupport.scala From scalanda-v20 with MIT License | 5 votes |
package com.msilb.scalandav20.common import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import akka.util.ByteString import io.circe._ object AkkaHttpCirceSupport extends AkkaHttpCirceSupport trait AkkaHttpCirceSupport { private val jsonStringUnmarshaller = Unmarshaller.byteStringUnmarshaller .forContentTypes(`application/json`) .mapWithCharset { case (ByteString.empty, _) => throw Unmarshaller.NoContentException case (data, charset) => data.decodeString(charset.nioCharset.name) } private val jsonStringMarshaller = Marshaller.stringMarshaller(`application/json`) implicit def circeUnmarshaller[A](implicit decoder: Decoder[A]): FromEntityUnmarshaller[A] = jsonStringUnmarshaller.map(jawn.decode(_).fold(throw _, identity)) implicit def circeToEntityMarshaller[A](implicit encoder: Encoder[A], printer: Json => String = Printer.noSpaces.copy(dropNullValues = true).pretty): ToEntityMarshaller[A] = jsonStringMarshaller.compose(printer).compose(encoder.apply) }
Example 31
Source File: HttpCodec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http.json import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.ExceptionHandler import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import com.daml.util.ExceptionOps._ import scalaz.std.stream.unfold import scalaz.{@@, Tag} import spray.json._ import scala.concurrent.{ExecutionContext, Future} object HttpCodec { sealed trait JsonApi val JsonApi = Tag.of[JsonApi] implicit val jsonExceptionHandler: ExceptionHandler = ExceptionHandler { case e: DeserializationException => complete( ( StatusCodes.BadRequest, ResponseFormats.errorsJsObject( StatusCodes.BadRequest, s"JSON parser error: ${e.msg}" +: unfoldCauses(e.cause).map(_.description): _*))) } private[this] def unfoldCauses(t: Throwable): Seq[Throwable] = unfold(t)(tnq => Option(tnq) map (tnn => (tnn, tnn.getCause))) private[this] val simpleJsValueUnmarshaller = Unmarshaller[String, JsValue] { implicit ec: ExecutionContext => value => Future(value.parseJson) } implicit val jsValueUnmarshaller: FromEntityUnmarshaller[JsValue] = (implicitly[FromEntityUnmarshaller[String]] andThen simpleJsValueUnmarshaller forContentTypes `application/json`) implicit val jsValueMarshaller: ToEntityMarshaller[JsValue] = Marshaller.combined((_: JsValue).compactPrint)(Marshaller.stringMarshaller(`application/json`)) implicit def jsonCodecUnmarshaller[A: RootJsonReader]: FromEntityUnmarshaller[A @@ JsonApi] = JsonApi.subst[FromEntityUnmarshaller, A](jsValueUnmarshaller map (_.convertTo[A])) implicit def jsonCodecMarshaller[A: RootJsonWriter]: ToEntityMarshaller[A @@ JsonApi] = JsonApi.subst[ToEntityMarshaller, A](Marshaller.combined((_: A).toJson)) }
Example 32
Source File: CsvStreamingRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.common.{ CsvEntityStreamingSupport, EntityStreamingSupport } import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.ContentTypes import akka.http.scaladsl.server.{ Directives, Route } import akka.util.ByteString import com.github.dnvriend.component.repository.PersonRepository import com.github.dnvriend.component.simpleserver.dto.http.Person import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport object CsvStreamingRoute extends Directives with PlayJsonSupport { implicit val personAsCsv = Marshaller.strict[Person, ByteString] { person => Marshalling.WithFixedContentType(ContentTypes.`text/csv(UTF-8)`, () => { ByteString(List(person.name.replace(",", "."), person.age, person.married).mkString(",")) }) } implicit val csvStreamingSupport: CsvEntityStreamingSupport = EntityStreamingSupport.csv() def route(dao: PersonRepository): Route = path("stream" / IntNumber) { numberOfPeople => pathEnd { get { complete(dao.people(numberOfPeople)) } } } }
Example 33
Source File: XmlMarshallerTest.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.marshaller import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.marshalling.{ Marshal, Marshaller } import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling._ import com.github.dnvriend.TestSpec import scala.concurrent.Future import scala.xml._ // see: http://doc.akka.io/docs/akka-http/current/scala/http/client-side/host-level.html#host-level-api // see: http://doc.akka.io/docs/akka-http/current/scala/http/implications-of-streaming-http-entity.html#implications-of-streaming-http-entities // see: http://doc.akka.io/docs/akka/2.4.9/scala/http/routing-dsl/directives/marshalling-directives/entity.html#entity // see: http://doc.akka.io/docs/akka-http/current/scala/http/common/http-model.html#httpresponse // see: http://doc.akka.io/docs/akka-http/current/scala/http/common/marshalling.html#http-marshalling-scala // see: http://doc.akka.io/docs/akka-http/current/scala/http/common/xml-support.html trait NodeSeqUnmarshaller { implicit def responseToAUnmarshaller[A](implicit resp: FromResponseUnmarshaller[NodeSeq], toA: Unmarshaller[NodeSeq, A]): Unmarshaller[HttpResponse, A] = { resp.flatMap(toA).asScala } } case class Person(name: String, age: Int) object Person extends NodeSeqUnmarshaller { implicit val unmarshaller: Unmarshaller[NodeSeq, Person] = Unmarshaller.strict[NodeSeq, Person] { xml => val name: String = (xml \ "name").text val age: Int = (xml \ "age").text.toInt Person(name, age) } implicit val marshaller: Marshaller[Person, NodeSeq] = Marshaller.opaque[Person, NodeSeq] { person => <person> <name>{ person.name }</name> <age>{ person.age }</age> </person> } } class XmlMarshallerTest extends TestSpec { it should "unmarshal to a person" in { val resp = HttpResponse( entity = HttpEntity(contentType = ContentType(MediaTypes.`application/xml`, HttpCharsets.`UTF-8`), "<person><name>dennis</name><age>42</age></person>") ) Unmarshal[HttpResponse](resp).to[Person].futureValue shouldBe Person("dennis", 42) } it should "marshal to NodeSeq" in { Marshal[Person](Person("dennis", 42)).to[NodeSeq].futureValue shouldBe a[NodeSeq] } it should "marshal to a RequestEntity" in { val result: Future[RequestEntity] = for { xml <- Marshal[Person](Person("dennis", 42)).to[NodeSeq] ent <- Marshal[NodeSeq](xml).to[RequestEntity] } yield ent result.futureValue shouldBe "" } it should "" in { import WsClientUnmarshallers._ withClient { client => client.url("").get().map { resp => resp.xml.as[Person] } } } } object WsClientUnmarshallers { implicit class ElemOps(val xml: NodeSeq) extends AnyVal { def as[A](implicit unmarshaller: XmlUnmarshaller[A]): A = { unmarshaller.fromXml(xml) } } } trait XmlUnmarshaller[A] { def fromXml(xml: NodeSeq): A }
Example 34
Source File: ChunkedEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, HttpRequest, MessageEntity} import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshaller import akka.stream.scaladsl.Source import akka.util.ByteString import endpoints4s.algebra import scala.concurrent.Future trait ChunkedJsonEntities extends algebra.ChunkedJsonEntities with ChunkedEntities with JsonEntitiesFromCodecs { def jsonChunksRequest[A](implicit codec: JsonCodec[A] ): RequestEntity[Chunks[A]] = { val decoder = stringCodec(codec) chunkedRequestEntity { byteString => val string = byteString.utf8String decoder .decode(string) .toEither .left .map(errors => new Throwable(errors.mkString(". "))) } } def jsonChunksResponse[A](implicit codec: JsonCodec[A] ): ResponseEntity[Chunks[A]] = { val encoder = stringCodec(codec) chunkedResponseEntity( ContentTypes.`application/json`, a => ByteString(encoder.encode(a)) ) } }
Example 35
Source File: BuiltInErrors.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.model.{HttpEntity, MediaTypes} import endpoints4s.{Invalid, algebra} trait BuiltInErrors extends algebra.BuiltInErrors { this: EndpointsWithCustomErrors => def clientErrorsResponseEntity: ResponseEntity[Invalid] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { invalid => HttpEntity( MediaTypes.`application/json`, endpoints4s.ujson.codecs.invalidCodec.encode(invalid) ) } def serverErrorResponseEntity: ResponseEntity[Throwable] = clientErrorsResponseEntity.compose(throwable => Invalid(throwable.getMessage)) }
Example 36
Source File: JsonEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{HttpEntity, MediaTypes} import akka.http.scaladsl.server.{Directive1, Directives} import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, FromRequestUnmarshaller, Unmarshaller } import endpoints4s.{Codec, Decoder, Encoder, Invalid, Valid, Validated, algebra} trait JsonEntitiesFromEncodersAndDecoders extends algebra.JsonEntities with EndpointsWithCustomErrors { type JsonRequest[A] = Decoder[String, A] type JsonResponse[A] = Encoder[A, String] def jsonRequest[A](implicit decoder: Decoder[String, A]): RequestEntity[A] = JsonEntities.decodeJsonRequest(this)(decoder) def jsonResponse[A](implicit encoder: Encoder[A, String]): ResponseEntity[A] = JsonEntities.encodeJsonResponse(encoder) } private object JsonEntities { def decodeJsonRequest[A]( endpoints: EndpointsWithCustomErrors )(decoder: Decoder[String, A]): Directive1[A] = { implicit val fromEntityUnmarshaller: FromEntityUnmarshaller[Validated[A]] = Unmarshaller.stringUnmarshaller .forContentTypes(MediaTypes.`application/json`) .map(data => decoder.decode(data)) Directives.entity[Validated[A]](implicitly).flatMap { case Valid(a) => Directives.provide(a) case inv: Invalid => endpoints.handleClientErrors(inv) } } def encodeJsonResponse[A]( encoder: Encoder[A, String] ): ToEntityMarshaller[A] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { value => HttpEntity(MediaTypes.`application/json`, encoder.encode(value)) } }
Example 37
Source File: LogEntityMarshaller.scala From 006877 with MIT License | 5 votes |
package aia.stream import akka.NotUsed import akka.stream.scaladsl.Framing import akka.stream.scaladsl.JsonFraming import akka.http.scaladsl.model.HttpCharsets._ import akka.http.scaladsl.model.MediaTypes._ import akka.http.scaladsl.model.headers.Accept import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.model._ import akka.stream.scaladsl.Source import akka.util.ByteString import spray.json._ import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.marshalling.ToEntityMarshaller object LogEntityMarshaller extends EventMarshalling { type LEM = ToEntityMarshaller[Source[ByteString, _]] def create(maxJsonObject: Int): LEM = { val js = ContentTypes.`application/json` val txt = ContentTypes.`text/plain(UTF-8)` val jsMarshaller = Marshaller.withFixedContentType(js) { src:Source[ByteString, _] => HttpEntity(js, src) } val txtMarshaller = Marshaller.withFixedContentType(txt) { src:Source[ByteString, _] => HttpEntity(txt, toText(src, maxJsonObject)) } Marshaller.oneOf(jsMarshaller, txtMarshaller) } def toText(src: Source[ByteString, _], maxJsonObject: Int): Source[ByteString, _] = { src.via(LogJson.jsonToLogFlow(maxJsonObject)) } }
Example 38
Source File: SpeedMeasurement.scala From Akka-Cookbook with MIT License | 5 votes |
package com.packt.chapter9 import akka.http.scaladsl.marshalling.{Marshaller, _} import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.{Unmarshaller, _} object SpeedMeasurement { def unmarshall(str: String) = { str.split("\\s") match { case Array(timestamp, latitude, longitude, value) => SpeedMeasurement(timestamp.toLong, latitude.toDouble, longitude.toDouble, value.toDouble) } } } case class SpeedMeasurement(timestamp: Long, latitude: Double, longitude: Double, value: Double) { val marshall = s"$timestamp $latitude $longitude $value" } trait SpeedMeasurementMarshallingHelper { val contentType = ContentType(MediaTypes.`text/tab-separated-values`, HttpCharsets.`UTF-8`) implicit val utf8TextSpaceMarshaller: ToEntityMarshaller[SpeedMeasurement] = Marshaller.withFixedContentType(contentType) { speedMeasurement ⇒ HttpEntity(contentType, speedMeasurement.marshall) } implicit val utf8TextSpaceUnmarshaller: FromEntityUnmarshaller[SpeedMeasurement] = Unmarshaller.stringUnmarshaller.map(SpeedMeasurement.unmarshall) }
Example 39
Source File: AkkaHttpMarshalling.scala From telegram with Apache License 2.0 | 5 votes |
package com.bot4s.telegram.marshalling import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToEntityMarshaller} import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} import com.bot4s.telegram.marshalling import com.bot4s.telegram.methods.{JsonRequest, MultipartRequest, Request} import com.bot4s.telegram.models.{AkkaInputFile, InputFile} import io.circe.{Decoder, Encoder} object AkkaHttpMarshalling { implicit def camelCaseJsonUnmarshaller[R](implicit decR: Decoder[R]): FromEntityUnmarshaller[R] = { Unmarshaller .stringUnmarshaller .forContentTypes(ContentTypes.`application/json`) .map(marshalling.fromJson[R]) } implicit def underscore_case_marshaller[T <: Request[_]](implicit encT: Encoder[T]): ToEntityMarshaller[T] = { Marshaller.strict { request => request match { // JSON-only request case r: JsonRequest[_] => Marshalling.Opaque(() => HttpEntity(ContentTypes.`application/json`, marshalling.toJson(request))) // Request with multipart payload case r: MultipartRequest[_] => val files = r.getFiles val parts = files.map { case (camelKey, inputFile) => val key = CaseConversions.snakenize(camelKey) inputFile match { case InputFile.FileId(id) => Multipart.FormData.BodyPart(key, HttpEntity(id)) case InputFile.Contents(filename, contents) => Multipart.FormData.BodyPart(key, HttpEntity(ContentTypes.`application/octet-stream`, contents), Map("filename" -> filename)) case InputFile.Path(path) => Multipart.FormData.BodyPart.fromPath(key, MediaTypes.`application/octet-stream`, path) case AkkaInputFile.ByteString(filename, bytes) => Multipart.FormData.BodyPart(key, HttpEntity(MediaTypes.`application/octet-stream`, bytes), Map("filename" -> filename)) case other => throw new RuntimeException(s"InputFile $other not supported") } } val fields = io.circe.parser.parse(marshalling.toJson(request)).fold(throw _, _.asObject.map { _.toMap.mapValues { json => json.asString.getOrElse(marshalling.printer.pretty(json)) } }) val params = fields.getOrElse(Map()) val paramParts = params.map { case (key, value) => Multipart.FormData.BodyPart(key, HttpEntity(value)) } Marshalling.Opaque(() => Multipart.FormData((parts ++ paramParts): _*).toEntity()) } } } }
Example 40
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) ) ) } }