• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Unmarshaller类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.http.scaladsl.unmarshalling.Unmarshaller的典型用法代码示例。如果您正苦于以下问题:Scala Unmarshaller类的具体用法?Scala Unmarshaller怎么用?Scala Unmarshaller使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Unmarshaller类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: HttpResponseUtil

//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker.ws

import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Sink
import akka.util.ByteString

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

package object http {

  implicit final class HttpResponseUtil(responseF: Future[HttpResponse]) extends HttpClientApi {

    val entityData: Future[ByteString] =
      for {
        response <- responseF
        byteString <- {
          val source = response.entity.dataBytes
          source.runWith(Sink.head[ByteString])
        }
      } yield byteString

    def mapStrict[T](f: HttpResponse => T): Future[T] =
      for {
        response   <- responseF
        byteString <- entityData
        strictEntity = HttpEntity.Strict(response.entity.contentType, byteString)
      } yield f(response.withEntity(strictEntity))

    def entityAs[T](implicit unmarshaller: Unmarshaller[String, T]): Future[Try[T]] = {
      val result = for {
        byteString <- entityData
        t          <- unmarshaller(byteString.utf8String)
      } yield Success(t)
      result.recover {
        case t: Throwable => Failure(t)
      }
    }
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:42,代码来源:package.scala


示例2: PreprocessedFromStringUnmarshaller

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl

import akka.http.scaladsl.marshallers.playjson.PlayJsonSupport.PlayJsonError
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.server.{RejectionError, ValidationRejection}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, FromStringUnmarshaller, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json.{JsError, JsValue, Json, Reads}

class PreprocessedFromStringUnmarshaller[T](sanitize: Preprocess[String], _fsu: FromStringUnmarshaller[T]) {
  implicit val fsu: FromStringUnmarshaller[T] = Unmarshaller withMaterializer {
    implicit ec =>
      implicit mat =>
        string =>
          _fsu(sanitize(string))
  }
}

object PreprocessedFromStringUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[String] = Preprocess.identity, fsu: FromStringUnmarshaller[T]): PreprocessedFromStringUnmarshaller[T] = {
    new PreprocessedFromStringUnmarshaller(sanitize, fsu)
  }
}

class PreprocessedFromEntityUnmarshaller[T](sanitize: Preprocess[JsValue], reads: Reads[T]) {
  private val jsonStringUnmarshaller =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset)       => data.decodeString(charset.nioCharset.name)
      }

  implicit val fsu: FromEntityUnmarshaller[T] = jsonStringUnmarshaller map { data =>
    val json = sanitize(Json parse data)

    reads reads json recoverTotal { error =>
      throw RejectionError(ValidationRejection(JsError.toJson(error).toString, Some(PlayJsonError(error))))
    }
  }
}

object PreprocessedFromEntityUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[JsValue] = Preprocess.identity, reads: Reads[T]): PreprocessedFromEntityUnmarshaller[T] = {
    new PreprocessedFromEntityUnmarshaller(sanitize, reads)
  }
}

trait Preprocess[T] {
  def apply(x: T): T
}
object Preprocess {
  def identity[T]: Preprocess[T] = new Preprocess[T] {
    override def apply(x: T): T = x
  }
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:57,代码来源:Preprocess.scala


示例3: Marshalling

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala


示例4: RandomAuthService

//设置package包名称以及导入依赖的类
package com.rndmi.messaging.auth

import java.util.logging.Logger

import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import io.bigfast.messaging.MessagingServer._
import io.bigfast.messaging.auth.AuthService
import io.grpc.Metadata
import spray.json.{JsonParser, ParserInput}


class RandomAuthService extends AuthService {

  import RandomAuthService._

  override def doAuth(metadata: Metadata) = {

    val authorization = metadata.get[String](authorizationKey)
    val session = metadata.get[String](sessionKey)

    logger.info(s"Checking auth for $authorization, $session")

    val httpResponse = http.singleRequest(
      HttpRequest(uri = uri).withHeaders(
        AuthorizationHeader(authorization),
        SessionHeader(session)
      )
    )(materializer)

    httpResponse flatMap { response =>
      val responseEntity = response.entity
      val eventualRandomResponse = unmarshaller.apply(responseEntity)

      logger.info(s"Parsed this response: $eventualRandomResponse")
      eventualRandomResponse
    } map { resp =>
      resp.data.userId.toString
    }
  }
}

object RandomAuthService extends JsonSupport {
  val authorizationKey = Metadata.Key.of("AUTHORIZATION", Metadata.ASCII_STRING_MARSHALLER)
  val sessionKey = Metadata.Key.of("X-AUTHENTICATION", Metadata.ASCII_STRING_MARSHALLER)
  val http = Http()
  val uri = ConfigFactory.load().getString("auth.uri")
  implicit val materializer = ActorMaterializer()

  val logger = Logger.getLogger(this.getClass.getName)

  val unmarshaller: Unmarshaller[HttpEntity, RandomResponse] = {
    Unmarshaller.byteArrayUnmarshaller mapWithCharset { (data, charset) =>
      JsonParser(ParserInput(data)).asJsObject.convertTo[RandomResponse]
    }
  }
} 
开发者ID:kykl,项目名称:mva,代码行数:61,代码来源:RandomAuthService.scala


示例5: 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))
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:TimedPersistenceStore.scala


示例6: 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)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:36,代码来源:PersistenceStoreRepository.scala


示例7: CoordinateFormat

//设置package包名称以及导入依赖的类
package model

import akka.http.scaladsl.unmarshalling.Unmarshaller
import base.CaseObjectSerializationSupport
import mapdomain.graph.Coordinate
import mapdomain.sidewalk.Ramp
import spray.json.{ DefaultJsonProtocol, DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait ModelFormatter extends DefaultJsonProtocol with CaseObjectSerializationSupport {

  implicit object CoordinateFormat extends RootJsonFormat[Coordinate] {
    def write(c: Coordinate) = JsObject(
      "lat" -> JsNumber(c.latitude),
      "lng" -> JsNumber(c.longitude))

    def read(value: JsValue) = value.asJsObject.getFields("lat", "lng") match {
      case Seq(JsNumber(latitude), JsNumber(longitude)) ?
        Coordinate(latitude.toDouble, longitude.toDouble)
      case _ ? throw DeserializationException("Coordinate expected")
    }
  }

  implicit object PathCoordinateFormat extends RootJsonFormat[PathCoordinate] {
    def write(pc: PathCoordinate) =
      if (pc.street.isDefined)
        JsObject(
          "lat" -> JsNumber(pc.coordinate.latitude),
          "lng" -> JsNumber(pc.coordinate.longitude),
          "street" -> JsString(pc.street.get))
      else
        JsObject(
          "lat" -> JsNumber(pc.coordinate.latitude),
          "lng" -> JsNumber(pc.coordinate.longitude))

    def read(value: JsValue) = value.asJsObject.getFields("lat", "lng", "street") match {
      case Seq(JsNumber(latitude), JsNumber(longitude), JsString(street)) ?
        PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble), Some(street))
      case Seq(JsNumber(latitude), JsNumber(longitude)) ?
        PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble))
      case _ ? throw DeserializationException("PathCoordinate expected")
    }
  }

  implicit val EdgeTypeFormat = caseObjectJsonFormat[EdgeType](StreetEdgeType, SidewalkEdgeType, StreetCrossingEdgeType)
  implicit val VertexTypeFormat = caseObjectJsonFormat[VertexType](StreetVertexType, SidewalkVertexType)
  implicit val ReportableElementTypeFormat = caseObjectJsonFormat[ReportableElementType](RAMP, SIDEWALK)
  implicit val RampFormat = jsonFormat4(Ramp.apply)
  implicit val EdgeFormat = jsonFormat4(Edge.apply)
  implicit val VertexFormat = jsonFormat3(Vertex.apply)
  implicit val MapContainerFormat = jsonFormat2(MapContainer.apply)
  implicit val StreetFormat = jsonFormat3(Street.apply)
  implicit val SidewalkFormat = jsonFormat2(Sidewalk.apply)
  implicit val ReportableElementFormat = jsonFormat6(ReportableElement.apply)
  implicit val StopFormat = jsonFormat4(Stop.apply)
  implicit val PublicTransportPathFormat = jsonFormat4(PublicTransportPath)
  implicit val StopCombinationFormat = jsonFormat6(PTCombination.apply)

  implicit val EdgeTypeUnmarshaller = Unmarshaller.strict[String, EdgeType](EdgeTypeFormat.mapping)
} 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:60,代码来源:ModelFormatter.scala


示例8: 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 })
} 
开发者ID:bots4s,项目名称:TelegramKit,代码行数:57,代码来源:HttpMarshalling.scala


示例9: 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))
} 
开发者ID:pocketberserker,项目名称:scala-zero-formatter,代码行数:38,代码来源:ZeroFormatterSupport.scala


示例10: 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 
开发者ID:ThoughtWorksInc,项目名称:akka-http-rpc,代码行数:51,代码来源:RpcSupport.scala


示例11: Mapper

//设置package包名称以及导入依赖的类
package org.akka.templates

import akka.http.scaladsl.marshalling.Marshaller.withFixedContentType
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest}
import akka.http.scaladsl.unmarshalling.{FromRequestUnmarshaller, Unmarshal, Unmarshaller}
import akka.stream.Materializer
import com.fasterxml.jackson.annotation.JsonInclude.Include
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, PropertyNamingStrategy}
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.concurrent.ExecutionContext


package object json {
  val objectMapper = new ObjectMapper()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .setSerializationInclusion(Include.NON_EMPTY)
    .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    .registerModule(DefaultScalaModule)

  implicit class ObjAsJsonUsingJackson(obj: Any) {
    def asJson: String = objectMapper.writeValueAsString(obj)
  }

  implicit class StringJsonAsCaseClass(json: String) {
    def asObject[T](implicit m: Manifest[T]): T = objectMapper.readValue(json, m.runtimeClass).asInstanceOf[T]
  }

  implicit def jsonMarshaller[T]: ToEntityMarshaller[T] =
    withFixedContentType(ContentTypes.`application/json`) { any =>
      HttpEntity(ContentTypes.`application/json`, any.asJson)
    }

  implicit def jsonUnmarshaller[T](implicit m: Manifest[T], materializer: Materializer): FromRequestUnmarshaller[T] =
    Unmarshaller[HttpRequest, T] {
      implicit ec: ExecutionContext => r => Unmarshal(r.entity).to[String].map(_.asObject[T])
    }
} 
开发者ID:gabfssilva,项目名称:akka-http-microservice-templates,代码行数:40,代码来源:json.scala


示例12: 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)
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:27,代码来源:SpeedMeasurement.scala


示例13: Marshalling

//设置package包名称以及导入依赖的类
package com.bluelabs.s3stream

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}

import scala.xml.NodeSeq

object Marshalling {
  import ScalaXmlSupport._

  implicit val MultipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x             =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text, (x \ "Key").text,
          (x \ "Etag").text
        )
    }
  }
} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:32,代码来源:Marshalling.scala


示例14: 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)))
} 
开发者ID:UdashFramework,项目名称:udash-guide,代码行数:27,代码来源:HttpSerializationUtils.scala


示例15: element2Json

//设置package包名称以及导入依赖的类
package $package$.svc

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling._
import akka.http.scaladsl.model.MessageEntity
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller}
import com.microworkflow.domain.Element
import com.microworkflow.svc.ElementJsonProtocol._
import spray.json._

trait JsonMarshalling extends SprayJsonSupport with DefaultJsonProtocol {

  def element2Json(e: Element): JsObject =
    JsObject(Map("id" ? JsString(e.id.toString), "timestamp" ? JsNumber(e.timestamp)))

  implicit def element2MessageEntity: Marshaller[Element, MessageEntity] = Marshaller.combined(element2Json)

  implicit val rawElementFromEntityUnmarshaller: FromEntityUnmarshaller[Element] =
    PredefinedFromEntityUnmarshallers.stringUnmarshaller.map(s ? {
      val jsonAst = JsonParser(s)
      jsonAst.convertTo[Element]
    })
} 
开发者ID:polymorphic,项目名称:gatling-simulation-template.g8,代码行数:24,代码来源:JsonMarshalling.scala


示例16: 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 
开发者ID:wavesplatform,项目名称:Waves,代码行数:62,代码来源:ApiMarshallers.scala


示例17: 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]])
  }

} 
开发者ID:mkokho,项目名称:akka-http-jackson-support,代码行数:44,代码来源:JacksonJsonSupport.scala


示例18: handle

//设置package包名称以及导入依赖的类
package ch.becompany.http

import java.io.IOException

import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, ResponseEntity}
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import akka.stream.ActorMaterializer
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.{ExecutionContext, Future}

trait HttpHandler[A] {
  def handle(request: HttpRequest, response: HttpResponse)(implicit ec: ExecutionContext): Future[A]
}

class UnmarshallingHttpHandler[A](implicit materializer: ActorMaterializer, unmarshaller: Unmarshaller[ResponseEntity, A])
  extends HttpHandler[A] with LazyLogging{

  def handle(request: HttpRequest, response: HttpResponse)(implicit ec: ExecutionContext): Future[A] =
    response.status match {
      case OK => Unmarshal(response.entity).to[A]
      case _ => handleError(response)
    }

  def handleError(response: HttpResponse)(implicit ec: ExecutionContext): Future[A] = {
    Unmarshal(response.entity).to[String].flatMap { entity =>
      val error = s"HTTP error ${response.status}: $entity"
      logger.error(error)
      Future.failed(new IOException(error))
    }
  }

} 
开发者ID:becompany,项目名称:akka-social-stream,代码行数:35,代码来源:HttpHandler.scala


示例19: __AkkaInstances

//设置package包名称以及导入依赖的类
package org.twistednoodle.json_api.integrations.circe

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import io.circe.syntax._
import io.circe.{Json, Printer, parser}

// Created by iwaisman on 12/30/16.

trait AkkaInstances { self: CirceApi =>

  private[circe] object __AkkaInstances {

    // Printers
    final val noSpacesNoNulls = Printer.noSpaces.copy(dropNullKeys = true)
    final val spaces4NoNulls = Printer.spaces4.copy(dropNullKeys = true)

    implicit def circeDocumentMarshaller(implicit printer: Json => String = noSpacesNoNulls.pretty): ToEntityMarshaller[JsonApiDocument] =
      Marshaller.StringMarshaller.wrap(`application/vnd.api+json`)(doc => printer(doc.asJson))

    implicit val circeDocumentUnmarshaller = Unmarshaller.
      stringUnmarshaller.
      forContentTypes(`application/vnd.api+json`, `application/json`).
      map(parser.decode[JsonApiDocument])
  }
} 
开发者ID:iwaisman,项目名称:json_api-scala,代码行数:28,代码来源:AkkaInstances.scala


示例20: scalaPBFromRequestUnmarshaller

//设置package包名称以及导入依赖的类
package com.example.utilities.serialization

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaType.Compressible
import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, MediaType}
import akka.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.http.scaladsl.util.FastFuture
import com.google.protobuf.CodedInputStream
import com.trueaccord.scalapb.json.JsonFormat
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}

import scala.concurrent.Future

trait ScalaPBMarshalling {
  private val protobufContentType = ContentType(MediaType.applicationBinary("octet-stream", Compressible, "proto"))
  private val applicationJsonContentType = ContentTypes.`application/json`

  def scalaPBFromRequestUnmarshaller[O <: GeneratedMessage with Message[O]](companion: GeneratedMessageCompanion[O]): FromEntityUnmarshaller[O] = {
    Unmarshaller.withMaterializer[HttpEntity, O](_ => implicit mat => {
      case [email protected](`applicationJsonContentType`, data) =>
        val charBuffer = Unmarshaller.bestUnmarshallingCharsetFor(entity)
        FastFuture.successful(JsonFormat.fromJsonString(data.decodeString(charBuffer.nioCharset().name()))(companion))
      case [email protected](`protobufContentType`, data) =>
        FastFuture.successful(companion.parseFrom(CodedInputStream.newInstance(data.asByteBuffer)))
      case entity =>
        Future.failed(UnsupportedContentTypeException(applicationJsonContentType, protobufContentType))
    })
  }

  implicit def scalaPBToEntityMarshaller[U <: GeneratedMessage]: ToEntityMarshaller[U] = {
    def jsonMarshaller(): ToEntityMarshaller[U] = {
      val contentType = applicationJsonContentType
      Marshaller.withFixedContentType(contentType) { value =>
        HttpEntity(contentType, JsonFormat.toJsonString(value))
      }
    }

    def protobufMarshaller(): ToEntityMarshaller[U] = {
      Marshaller.withFixedContentType(protobufContentType) { value =>
        HttpEntity(protobufContentType, value.toByteArray)
      }
    }

    Marshaller.oneOf(jsonMarshaller(), protobufMarshaller())
  }

} 
开发者ID:kalamara,项目名称:akka-cassandra-hazelcast-cluster,代码行数:49,代码来源:ScalaPBMarshalling.scala



注:本文中的akka.http.scaladsl.unmarshalling.Unmarshaller类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Lang类代码示例发布时间:2022-05-23
下一篇:
Scala StreamSinkProvider类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap