本文整理汇总了Scala中akka.http.scaladsl.marshalling.Marshaller类的典型用法代码示例。如果您正苦于以下问题:Scala Marshaller类的具体用法?Scala Marshaller怎么用?Scala Marshaller使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Marshaller类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: deleteAll
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.store.impl
import java.time.OffsetDateTime
import akka.Done
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStore }
import mesosphere.marathon.state.StateMetrics
import scala.concurrent.Future
trait TimedPersistenceStore[K, Category, Serialized] extends StateMetrics {
self: PersistenceStore[K, Category, Serialized] =>
override def deleteAll[Id, V](k: Id)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
timedWrite(self.deleteAll(k))
override def get[Id, V](id: Id)(implicit
ir: IdResolver[Id, V, Category, K],
um: Unmarshaller[Serialized, V]): Future[Option[V]] =
timedRead(self.get(id))
override def get[Id, V](
id: Id,
version: OffsetDateTime)(implicit
ir: IdResolver[Id, V, Category, K],
um: Unmarshaller[Serialized, V]): Future[Option[V]] =
timedRead(self.get(id, version))
override def store[Id, V](id: Id, v: V)(implicit
ir: IdResolver[Id, V, Category, K],
m: Marshaller[V, Serialized]): Future[Done] =
timedWrite(self.store(id, v))
override def store[Id, V](id: Id, v: V,
version: OffsetDateTime)(implicit
ir: IdResolver[Id, V, Category, K],
m: Marshaller[V, Serialized]): Future[Done] =
timedWrite(self.store(id, v, version))
override def deleteCurrent[Id, V](k: Id)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
timedWrite(self.deleteCurrent(k))
override def deleteVersion[Id, V](
k: Id,
version: OffsetDateTime)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
timedWrite(self.deleteVersion(k, version))
}
示例2: PersistenceStoreVersionedRepository
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.repository.impl
import java.time.OffsetDateTime
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Source
import akka.{ Done, NotUsed }
import mesosphere.marathon.core.storage.repository.{ Repository, VersionedRepository }
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStore }
import scala.concurrent.Future
class PersistenceStoreVersionedRepository[Id, V, K, C, S](
persistenceStore: PersistenceStore[K, C, S],
extractId: V => Id,
extractVersion: V => OffsetDateTime)(implicit
ir: IdResolver[Id, V, C, K],
marshaller: Marshaller[V, S],
unmarshaller: Unmarshaller[S, V]) extends PersistenceStoreRepository[Id, V, K, C, S](
persistenceStore,
extractId) with VersionedRepository[Id, V] {
override def versions(id: Id): Source[OffsetDateTime, NotUsed] = persistenceStore.versions(id)
override def getVersion(id: Id, version: OffsetDateTime): Future[Option[V]] =
persistenceStore.get(id, version)
override def storeVersion(v: V): Future[Done] =
persistenceStore.store(extractId(v), v, extractVersion(v))
override def deleteCurrent(id: Id): Future[Done] =
persistenceStore.deleteCurrent(id)
}
示例3: StreamingRoute
//设置package包名称以及导入依赖的类
package routes
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import akka.{ NotUsed }
import akka.actor.ActorSystem
import scala.concurrent.duration._
import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
class StreamingRoute()(implicit
system: ActorSystem,
materializer: ActorMaterializer
) {
val source: Source[Int, NotUsed] = Source(1 to 100)
val factorials: Source[BigInt, NotUsed] = source.scan(BigInt(1))((acc, next) => acc * next)
def toNewLineFlow[A]: Flow[A, String, NotUsed] = Flow[A].map(_.toString + "\n")
implicit val toResponseMarshaller: ToResponseMarshaller[Source[String, Any]] =
Marshaller.opaque { items =>
val data = items.map(item => ChunkStreamPart(item))
HttpResponse(entity = HttpEntity.Chunked(MediaTypes.`application/json`, data))
}
def throttler[A](duration: FiniteDuration): Flow[A, A, NotUsed] =
Flow[A].throttle(1, duration, 1, ThrottleMode.shaping)
def routes =
path("factorials") { complete(factorialsSource) } ~
get {
path(IntNumber) { i => complete(intSource(toMilliseconds(i))) } ~
pathEnd { complete(intSource(1.second)) }
}
private def toMilliseconds(i: Int): FiniteDuration = if (i > 0) i.milliseconds else 1.second
private def factorialsSource: Source[String, NotUsed] = source
.scan(BigInt(1))((acc, next) => acc * next)
.via(toNewLineFlow)
.throttle(1, 0.5.second, 1, ThrottleMode.shaping)
private def intSource(duration: FiniteDuration): Source[String, NotUsed] = source
.via(toNewLineFlow)
.via(throttler(duration))
}
示例4: ShakespeareRoute
//设置package包名称以及导入依赖的类
package routes
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import akka.{ NotUsed }
import akka.actor.ActorSystem
import scala.concurrent.duration._
import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import spray.json.DefaultJsonProtocol._
import models.Character
import repositories.ShakespeareRepository
import akka.http.scaladsl.model.ws.{ TextMessage, Message }
import spray.json._
class ShakespeareRoute(workingDirectory: String)(implicit
system: ActorSystem,
materializer: ActorMaterializer
) {
val repository = new ShakespeareRepository()
val source: Source[Character, NotUsed] = Source(repository.romeoEtJuliette)
val romeoEtJulietteIterable = repository.romeoEtJuliette.toIterator
def toNewLineFlow[A]: Flow[A, String, NotUsed] = Flow[A].map(_.toString + "\n")
implicit val characterFormat = jsonFormat2(Character)
implicit val toResponseMarshaller: ToResponseMarshaller[Source[String, Any]] =
Marshaller.opaque { items =>
val data = items.map(item => ChunkStreamPart(item))
HttpResponse(entity = HttpEntity.Chunked(MediaTypes.`application/json`, data))
}
def throttler[A](duration: FiniteDuration): Flow[A, A, NotUsed] =
Flow[A].throttle(1, duration, 1, ThrottleMode.shaping)
def routes = path("romeoEtJuliette") {
handleWebSocketMessages(Flow[Message].mapConcat {
case tm: TextMessage if romeoEtJulietteIterable.hasNext =>
TextMessage(romeoEtJulietteIterable.next().toJson.toString) :: Nil
case other =>
println(other)
Nil
})
} ~
path("romeoAndJuliette") { get(complete(romeoAndJulietteSource)) } ~
pathEnd { getFromFile(s"$workingDirectory/theatre.html") }
private def romeoAndJulietteSource: Source[String, NotUsed] = source
.map(c => s"${c.name} - ${c.text}")
.via(toNewLineFlow)
.via(throttler(0.5.second))
}
示例5: unmarshaller
//设置package包名称以及导入依赖的类
package com.github.bots4s.telegramkit.client
import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToEntityMarshaller}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import com.github.bots4s.telegramkit.marshalling.{BotMarshaller, BotUnmarshaller}
import com.github.bots4s.telegramkit.method.{BotApiRequest, BotApiRequestJson, BotApiRequestMultipart}
import com.github.bots4s.telegramkit.model._
private[client] trait HttpMarshalling { this: BotApiClient =>
implicit def unmarshaller[T: Manifest](implicit um: BotUnmarshaller[T]): FromEntityUnmarshaller[T] = {
Unmarshaller.stringUnmarshaller.map(body => um(body))
}
implicit def marshaller[T](implicit m: BotMarshaller[BotApiRequestJson[T]]): ToEntityMarshaller[BotApiRequest[T]] = {
Marshaller.strict {
case request: BotApiRequestJson[T] =>
val content = m(request)
Marshalling.Opaque(() => HttpEntity(ContentTypes.`application/json`, content))
case request: BotApiRequestMultipart[T] =>
def flatten(value: Any): Any = value match {
case Some(x) => flatten(x)
case e: Either[_, _] => flatten(e.fold(identity, identity))
case _ => value
}
val fields = request.getClass.getDeclaredFields.iterator.zip(request.productIterator).map {
case (k, v) => HttpMarshalling.snakeCase(k.getName) -> flatten(v)
}.filterNot(_._2 == None)
if (fields.isEmpty) {
Marshalling.Opaque(() => HttpEntity.empty(ContentTypes.`application/octet-stream`))
} else {
val parts = fields map {
case (k, v @ (_: String | _: Boolean | _: Long | _: Float)) =>
Multipart.FormData.BodyPart(k, HttpEntity(v.toString))
case (k, InputFile.InputFilePath(path)) =>
Multipart.FormData.BodyPart.fromPath(k, MediaTypes.`application/octet-stream`, path)
case (k, InputFile.InputFileData(filename, bs)) =>
Multipart.FormData.BodyPart(k, HttpEntity(ContentTypes.`application/octet-stream`, bs), Map("filename" -> filename))
case (k, other) =>
log.warning(s"unexpected field in multipart request, $k: $other")
Multipart.FormData.BodyPart(k, HttpEntity(""))
}
Marshalling.Opaque(() => Multipart.FormData(parts.toSeq: _*).toEntity())
}
}
}
}
private[client] object HttpMarshalling {
private val CapitalLetter = "[A-Z]".r
def snakeCase(s: String): String =
CapitalLetter.replaceAllIn(s, { "_" + _.group(0).toLowerCase })
}
示例6: ZeroFormatterSupport
//设置package包名称以及导入依赖的类
package zeroformatter.akka.http
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes.`application/octet-stream`
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import zeroformatter._
object ZeroFormatterSupport extends ZeroFormatterSupport {
override def serialize[A: Formatter](value: A) = unsafe.ZeroFormatter.serialize(value)
override def deserialize[A: Formatter](bytes: Array[Byte]) = unsafe.ZeroFormatter.deserialize[A](bytes)
}
trait ZeroFormatterSupport {
def serialize[A: Formatter](value: A): Array[Byte]
def deserialize[A: Formatter](bytes: Array[Byte]): A
private val zeroFormatterUnmarshaller =
Unmarshaller.byteArrayUnmarshaller
.forContentTypes(`application/octet-stream`)
.map {
case Array() => throw Unmarshaller.NoContentException
case data => data
}
private val zeroFormatterMarshaller = Marshaller.byteArrayMarshaller(`application/octet-stream`)
implicit def unmarshaller[A: Formatter]: FromEntityUnmarshaller[A] = {
zeroFormatterUnmarshaller
.map(bs => deserialize(bs))
}
implicit def marshaller[A: Formatter]: ToEntityMarshaller[A] =
zeroFormatterMarshaller
.compose(v => serialize(v))
}
示例7: upickleJsValueMarshaller
//设置package包名称以及导入依赖的类
package com.thoughtworks.akka.http
import akka.http.scaladsl.model.{MediaTypes, _}
import akka.http.scaladsl.server.Directives._
import com.thoughtworks.Extractor._
import scala.concurrent.Future
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
trait RpcSupport extends autowire.Server[upickle.Js.Value, upickle.default.Reader, upickle.default.Writer] {
implicit private def upickleJsValueMarshaller = {
Marshaller.StringMarshaller.wrap[upickle.Js.Value, MessageEntity](MediaTypes.`application/json`)(_.toString)
}
implicit private def upickleJsValueUnmarshaller = {
Unmarshaller.stringUnmarshaller.map(upickle.json.read)
}
final def write[Result](r: Result)(implicit writer: upickle.default.Writer[Result]) = {
writer.write(r)
}
final def read[Result](p: upickle.Js.Value)(implicit reader: upickle.default.Reader[Result]) = {
reader.read(p)
}
final def rpc(packagePrefix: String*)(routes: PartialFunction[Request, Future[upickle.Js.Value]]) = {
path(Segments) { segments =>
entity(as[upickle.Js.Value]) {
case upickle.Js.Obj([email protected]_*) =>
autowire.Core.Request(packagePrefix ++ segments, keyValuePairs.toMap) match {
case routes.extract(response) =>
complete {
response
}
case _ =>
reject
}
case _ =>
complete(HttpResponse(StatusCodes.BadRequest))
}
}
}
}
object RpcSupport extends RpcSupport
示例8: SpeedMeasurement
//设置package包名称以及导入依赖的类
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)
}
示例9: TemplatePageMarshalling
//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.Marshalling._
import akka.http.scaladsl.marshalling.ToResponseMarshaller
import akka.http.scaladsl.model._
import scala.concurrent.Future
import play.twirl.api.Html
object TemplatePageMarshalling {
private def getHtml(html: Html, charset: HttpCharset) = HttpResponse(
entity = HttpEntity(
ContentType.WithCharset(MediaTypes.`text/html`, charset),
html.body
)
)
def marshaller: ToResponseMarshaller[Html] = Marshaller(
implicit exeCtxt => html => Future.successful(
WithOpenCharset(MediaTypes.`text/html`, getHtml(html, _)) :: Nil
)
)
}
示例10: gencodecMarshaller
//设置package包名称以及导入依赖的类
package io.udash.web.guide.rest
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.model.HttpEntity.Strict
import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import com.avsystem.commons.serialization.GenCodec
import io.udash.rpc.DefaultUdashSerialization
trait HttpSerializationUtils extends DefaultUdashSerialization {
implicit def gencodecMarshaller[T](implicit codec: GenCodec[T]): Marshaller[T, Strict] =
Marshaller.withFixedContentType(MediaTypes.`application/json`)(
(obj: T) => {
var string: String = null
val output = outputSerialization((serialized) => string = serialized)
codec.write(output, obj)
HttpEntity(MediaTypes.`application/json`, string)
}
)
implicit def gencodecUnmarshaller[T](implicit codec: GenCodec[T]): Unmarshaller[HttpEntity, T] =
Unmarshaller
.stringUnmarshaller
.forContentTypes(MediaTypes.`application/json`)
.map(data => codec.read(inputSerialization(data)))
}
示例11: PlayJsonException
//设置package包名称以及导入依赖的类
package com.wavesplatform.http
import scala.util.control.Exception.nonFatalCatch
import scala.util.control.NoStackTrace
import akka.http.scaladsl.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.MediaTypes.{`application/json`, `text/plain`}
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json._
import scorex.api.http.ApiError
import scorex.transaction.{Transaction, ValidationError}
case class PlayJsonException(
cause: Option[Throwable] = None,
errors: Seq[(JsPath, Seq[JsonValidationError])] = Seq.empty) extends IllegalArgumentException with NoStackTrace
trait ApiMarshallers {
type TRM[A] = ToResponseMarshaller[A]
import akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers._
implicit val aem: TRM[ApiError] = fromStatusCodeAndValue[StatusCode, JsValue].compose { ae => ae.code -> ae.json }
implicit val vem: TRM[ValidationError] = aem.compose(ve => ApiError.fromValidationError(ve))
implicit val tw: Writes[Transaction] = Writes(_.json)
private val jsonStringUnmarshaller =
Unmarshaller.byteStringUnmarshaller
.forContentTypes(`application/json`)
.mapWithCharset {
case (ByteString.empty, _) => throw Unmarshaller.NoContentException
case (data, charset) => data.decodeString(charset.nioCharset.name)
}
private lazy val jsonStringMarshaller =
Marshaller.stringMarshaller(`application/json`)
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],
printer: JsValue => String = Json.prettyPrint): ToEntityMarshaller[A] =
jsonStringMarshaller.compose(printer).compose(writes.writes)
// preserve support for using plain strings as request entities
implicit val stringMarshaller = PredefinedToEntityMarshallers.stringMarshaller(`text/plain`)
}
object ApiMarshallers extends ApiMarshallers
示例12: jacksonObjectMapper
//设置package包名称以及导入依赖的类
package nz.mkokho.akkahttpjackson
import java.io.StringWriter
import scala.reflect.ClassTag
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.model.ContentTypes.`application/json`
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
import com.fasterxml.jackson.databind.ObjectMapper
trait JacksonJsonSupport {
def jacksonObjectMapper: ObjectMapper
implicit def jacksonJsonUnmarshaller[T: ClassTag]: FromEntityUnmarshaller[T] = {
Unmarshaller.byteStringUnmarshaller.forContentTypes(`application/json`).mapWithCharset { (data, charset) ?
val input = data.decodeString(charset.nioCharset.name)
deserialize[T](input)
}
}
implicit def jacksonJsonMarshaller[T <: AnyRef]: ToEntityMarshaller[T] = {
Marshaller.withFixedContentType(`application/json`) { any =>
HttpEntity(`application/json`, serialize(any))
}
}
def serialize[T](any: T): String = {
val value = new StringWriter
jacksonObjectMapper.writeValue(value, any)
value.toString
}
def deserialize[T: ClassTag](blob: String): T = {
jacksonObjectMapper.readValue(blob, implicitly[ClassTag[T]].runtimeClass.asInstanceOf[Class[T]])
}
}
示例13: taskToResponseMarshallable
//设置package包名称以及导入依赖的类
package aecor.example
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshallable, ToResponseMarshaller }
import monix.eval.Task
import monix.execution.Scheduler
trait MonixSupport {
implicit def taskToResponseMarshallable[A](
task: Task[A]
)(implicit A: ToResponseMarshaller[A]): ToResponseMarshallable =
new ToResponseMarshallable {
override implicit def marshaller: ToResponseMarshaller[Task[A]] =
Marshaller { implicit ec => task =>
task.runAsync(Scheduler(ec)).flatMap(A(_))
}
override def value: Task[A] = task
override type T = Task[A]
}
}
object MonixSupport extends MonixSupport
示例14: implicits
//设置package包名称以及导入依赖的类
package petclinic
import akka.http.scaladsl.marshalling.{ Marshaller, ToEntityMarshaller, ToResponseMarshaller }
import akka.http.scaladsl.model.HttpResponse
import cats.data.EitherT
import scala.concurrent.Future
case object implicits {
implicit def eitherTMarshaller[A](
implicit ma: ToEntityMarshaller[A],
me: ToEntityMarshaller[PetClinicError])
: ToResponseMarshaller[EitherT[Future, PetClinicError, A]] =
Marshaller(implicit ec =>
_.value.flatMap {
case Right(a) => ma.map(me => HttpResponse(entity = me))(a)
case Left(e) =>
me.map(
me =>
e.httpErrorCode
.map(
code => HttpResponse(status = code, entity = me)
)
.getOrElse(HttpResponse(entity = me)))(e)
})
}
示例15: dbActionMarshaller
//设置package包名称以及导入依赖的类
package petclinic
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, ToResponseMarshaller }
import cats.data.{ EitherT, State }
trait Marshallers {
def dbActionMarshaller[S, A](initial: S)(onResponse: S => Unit)(
implicit ma: ToEntityMarshaller[A],
me: ToEntityMarshaller[PetClinicError])
: ToResponseMarshaller[EitherT[State[S, ?], PetClinicError, A]] =
Marshaller(implicit ec =>
s => {
val (s2, r) = s.value.run(initial).value
onResponse(s2)
r match {
case Right(a) =>
ma.map(me => HttpResponse(entity = me))(a)
case Left(e) =>
me.map(
me =>
e.httpErrorCode
.map(
code => HttpResponse(status = code, entity = me)
)
.getOrElse(HttpResponse(entity = me)))(e)
}
})
}
object Marshallers extends Marshallers