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

Scala FromEntityUnmarshaller类代码示例

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

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



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

示例1: 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


示例2: 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


示例3: 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


示例4: Marshallers

//设置package包名称以及导入依赖的类
package com.jatescher.layer.marshalling

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller
import com.jatescher.layer.marshalling.v1._
import com.jatescher.layer.models.MessagePartContents.ImageMessagePartContent
import com.jatescher.layer.models.MessageParts.{ ImageMessagePart, TextMessagePart }
import com.jatescher.layer.models.MessageSenders.{ HumanMessageSender, NonHumanMessageSender }
import com.jatescher.layer.models._
import spray.json._

object Marshallers extends SprayJsonSupport with DefaultJsonProtocol {

  implicit val ConversationMarshaller: ToEntityMarshaller[Conversation] = ConversationFormat.ConversationJsonFormat
  implicit val ErrorResponseUnmarshaller: FromEntityUnmarshaller[ErrorResponse] = ErrorResponseFormat.ErrorResponseJsonFormat
  implicit val NonHumanMessageSenderMarshaller: ToEntityMarshaller[NonHumanMessageSender] = MessageSenderFormat.NonHumanMessageSenderJsonFormat
  implicit val HumanMessageSenderMarshaller: ToEntityMarshaller[HumanMessageSender] = MessageSenderFormat.HumanMessageSenderJsonFormat
  implicit val MessageSenderMarshaller: ToEntityMarshaller[MessageSender] = MessageSenderFormat.MessageSenderJsonFormat
  implicit val MessagePartContentMarshaller: ToEntityMarshaller[MessagePartContent] = MessagePartContentFormat.MessagePartContentJsonFormat
  implicit val ImageMessagePartContentMarshaller: ToEntityMarshaller[ImageMessagePartContent] = MessagePartContentFormat.ImageMessagePartContentJsonFormat
  implicit val TextMessagePartMarshaller: ToEntityMarshaller[TextMessagePart] = MessagePartFormat.TextMessagePartJsonFormat
  implicit val ImageMessagePartMarshaller: ToEntityMarshaller[ImageMessagePart] = MessagePartFormat.ImageMessagePartJsonFormat
  implicit val MessagePartMarshaller: ToEntityMarshaller[MessagePart] = MessagePartFormat.MessagePartJsonFormat
  implicit val MessageMarshaller: ToEntityMarshaller[Message] = MessageFormat.MessageJsonFormat
  implicit val MessageUnmarshaller: FromEntityUnmarshaller[Message] = MessageFormat.MessageJsonFormat

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:29,代码来源:Marshallers.scala


示例5: unmarshalEntityTo

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

import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshal}
import akka.stream.ActorMaterializer
import rest.client.entities.ExecutionResultCode

import scala.concurrent.{ExecutionContext, Future}

trait EntityUnmarshallers {

  implicit val mat: ActorMaterializer
  implicit val ec: ExecutionContext

  def unmarshalEntityTo[A](response: HttpResponse)(implicit u: FromEntityUnmarshaller[A]): Future[A] = {
    response.status match {
      case StatusCodes.OK => Unmarshal(response.entity).to[A]
      case _ =>
        val error = new Exception(response.toString())
        response.discardEntityBytes()
        Future.failed(error)
    }
  }

  def extractStatusCode(response: HttpResponse): Future[Int] = {
    val eventualInt = response.status match {
      case StatusCodes.OK => Future.successful(ExecutionResultCode.OK)
      case _              => Future.failed(new Exception(response.toString()))
    }
    response.discardEntityBytes()
    eventualInt
  }

} 
开发者ID:lymr,项目名称:fun-chat,代码行数:35,代码来源:EntityUnmarshallers.scala


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


示例7: GenericJsonSupport

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.wire

import akka.http.scaladsl.marshalling.{PredefinedToEntityMarshallers, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers}
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.flipkart.connekt.receptors.wire.GenericJsonSupport._
import scala.collection.mutable
import scala.reflect.ClassTag


object GenericJsonSupport {

  val jacksonModules = Seq(DefaultScalaModule)

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModules(jacksonModules: _*)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  val m: mutable.Map[Class[_], ToEntityMarshaller[_]] = mutable.Map.empty[Class[_], ToEntityMarshaller[_]]
  val um: mutable.Map[Class[_], FromEntityUnmarshaller[_]] = mutable.Map.empty[Class[_], FromEntityUnmarshaller[_]]
}

trait JsonToEntityMarshaller extends PredefinedToEntityMarshallers {

  implicit def findMarshaller[T](implicit cTag: ClassTag[T]): ToEntityMarshaller[T] =
    m.getOrElseUpdate(cTag.runtimeClass, genericMarshaller[T]).asInstanceOf[ToEntityMarshaller[T]]

  def genericMarshaller[T]: ToEntityMarshaller[T] =
    stringMarshaller(MediaTypes.`application/json`)
      .compose[T](mapper.writeValueAsString)
}

trait JsonFromEntityUnmarshaller extends PredefinedFromEntityUnmarshallers {

  implicit def findUnmarshaller[T](implicit cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    um.getOrElseUpdate(cTag.runtimeClass, genericUnmarshaller[T](cTag)).asInstanceOf[FromEntityUnmarshaller[T]]

  def genericUnmarshaller[T](cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    stringUnmarshaller.forContentTypes(MediaTypes.`application/json`)
      .map(mapper.readValue(_, cTag.runtimeClass).asInstanceOf[T])
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:45,代码来源:JsonToEntityMarshaller.scala


示例8: MarshallingSuite

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

import scala.reflect.ClassTag
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FunSuite, Matchers}
import upickle.AttributeTagged

class MarshallingSuite  extends FunSuite
  with Matchers
  with ScalatestRouteTest
  with ScalaFutures {

  def routes[A: ClassTag: ToEntityMarshaller: FromEntityUnmarshaller]: Route = (pathSingleSlash & post) {
    entity(as[A]) { a => complete(a) }
  }

  test("simple case class w/o companion") {
    bidiCheck(OptionPickler)(SimpleNoCompanionCustomPickler(41, 1))
  }

  test("simple case class w/ companion & implicit ReadWriter defined") {
    bidiCheck(upickle.default)(WithCompanionAndImplicitRw("str"))
  }

  test("sealed hierarchy") {
    bidiCheck(upickle.default)[SimpleHierNoCompanion](TInt(1))
    bidiCheck(upickle.default)[SimpleHierNoCompanion](TBool(true))
  }

  test("parametrized class hierarchy") {
    bidiCheck(upickle.default)(Parametrized(1))
    bidiCheck(upickle.default)(Parametrized(List(1,2,3)))
    bidiCheck(upickle.default)(Parametrized(SimpleNoCompanion(-10, 10)))
  }

  private def bidiCheck[P <: AttributeTagged](p: P) = {
    new {
      def apply[A: ClassTag: ToEntityMarshaller: FromEntityUnmarshaller: p.Reader: p.Writer](a: A) = {
        Post("/", a) ~> routes[A] ~> check { responseAs[A] shouldBe a }
      }
    }
  }
} 
开发者ID:tkroman,项目名称:micromarshal,代码行数:49,代码来源:MarshallingSuite.scala


示例9: 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


示例10: 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


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


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

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


示例13: 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


示例14: ApiMarshalling

//设置package包名称以及导入依赖的类
package com.vivint.ceph.api

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.ParsingException
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.http.scaladsl.model.MediaTypes
import com.vivint.ceph.model.{ Job, PlayJsonFormats, RunState, ReservationReleaseDetails }
import model.ErrorResponse
import play.api.libs.json._

object ApiMarshalling {
  def fromJsonResponse[T](implicit reader: Reads[T]): FromEntityUnmarshaller[T] =
    Unmarshaller.stringUnmarshaller.
      forContentTypes(MediaTypes.`application/json`).
      map { str => Json.parse(str).as[T] }

  def toJsonResponse[T](implicit writer: Writes[T]): ToEntityMarshaller[T] =
    Marshaller.stringMarshaller(MediaTypes.`application/json`).
      compose { data: T =>
        Json.stringify(Json.toJson(data)) }

  import PlayJsonFormats._
  import model.ApiPlayJsonFormats._
  implicit val jobsWriter = toJsonResponse[Iterable[Job]]
  implicit val reservationReleaseWriter = toJsonResponse[Iterable[ReservationReleaseDetails]]
  implicit val errorWriter = toJsonResponse[ErrorResponse]

  def uuidFromString(str: String) =
    try {
      java.util.UUID.fromString(str)
    } catch {
      case ex: IllegalArgumentException =>
        throw ParsingException(s"Couldn't parse UUID: ${ex.getMessage}")
    }

  def runStateFromString(str: String) =
    RunState.values.find(_.name == str).getOrElse {
      throw ParsingException(s"invalid runState '${str}', expected one of '${RunState.values.mkString(", ")}'")
    }


  implicit val runStateTextReader: Unmarshaller[String, RunState.EnumVal] =
    Unmarshaller.strict[String, RunState.EnumVal](runStateFromString)
} 
开发者ID:vivint-smarthome,项目名称:ceph-on-mesos,代码行数:45,代码来源:ApiMarshalling.scala


示例15: CustomMarshallers

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

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.scaladsl.Source
import akka.util.ByteString
import play.api.libs.json.{JsObject, JsValue, Json}

object CustomMarshallers {

  implicit val JsonIteratorMarshaller: ToResponseMarshaller[Iterator[JsValue]] =
    Marshaller.opaque { values =>
      HttpResponse(
        entity = HttpEntity.Chunked.fromData(
          ContentTypes.`application/json`,
          // TODO: Make this an actual iterator/stream
          Source.single(
            ByteString(Json.toJson(values.toVector).toString)
          )
        )
      )
    }

  implicit val JsonIteratorUnmarshaller: FromEntityUnmarshaller[Iterator[JsValue]] =
    Unmarshaller.withMaterializer(_ =>
      implicit mat =>
        _.dataBytes.runFold(Iterator[JsValue]()) {
          case (res, str) =>
            res ++ Iterator.single(Json.parse(str.toByteBuffer.array()))
        }
    )

  implicit val JsonMapUnmarshaller: FromEntityUnmarshaller[Map[String, JsValue]] = {
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset) => data.decodeString(charset.nioCharset.name)
      }
      .map(data => Json.parse(data).as[JsObject].value.toMap)
  }

  implicit val OptionalJsonMapUnmarshaller: FromEntityUnmarshaller[Option[Map[String, JsValue]]] = {
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (data, charset) => data.decodeString(charset.nioCharset.name)
      }
      .map {
        case data if data.nonEmpty => Some(Json.parse(data).as[JsObject].value.toMap)
        case _ => None
      }
  }

  implicit val JsonMapMarshaller: ToEntityMarshaller[Map[String, JsValue]] =
    Marshaller.withFixedContentType(`application/json`)(value =>
      HttpEntity(JsObject(value).toString)
    )
} 
开发者ID:SeanCheatham,项目名称:scala-graph,代码行数:62,代码来源:CustomMarshallers.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala StringUtils类代码示例发布时间:2022-05-23
下一篇:
Scala OK类代码示例发布时间: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