当前位置: 首页>>代码示例>>Scala>>正文


Scala ToEntityMarshaller类代码示例

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


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

示例1: route

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

import akka.http.scaladsl.marshalling.{Marshal, ToEntityMarshaller}
import akka.http.scaladsl.model.{HttpHeader, HttpResponse, ResponseEntity, StatusCode}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.hakker.template.Render
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.{Encoder, Json}
import io.circe.syntax._

import scala.collection.immutable
import scala.concurrent.ExecutionContext

trait Controller extends Render {

  override lazy val config = ConfigFactory.load()
  val StatusCodes          = akka.http.scaladsl.model.StatusCodes

  def route: Route

  def apply(): Route = {
    get {
      // render frontend files
      pathPrefix("js") {
        renderDir("js")
      }
    } ~ route
  }

  def send(statusCode: StatusCode): Route = complete(statusCode)

  def send[T](statusCode: StatusCode, content: T, headers: immutable.Seq[HttpHeader] = Nil)(
      implicit marshaller: ToEntityMarshaller[T],
      ec: ExecutionContext): Route = {
    val response = Marshal(content)
      .to[ResponseEntity](marshaller, ec)
      .map(entity => {
        HttpResponse(statusCode, headers = headers).withEntity(entity)
      })
    complete(response)
  }

  def sendJson[T](statusCode: StatusCode, content: T)(implicit encoder: Encoder[T],
                                                      ec: ExecutionContext): Route = {
    sendJson(statusCode, content.asJson)
  }

  def sendJson[T](content: T)(implicit encoder: Encoder[T], ec: ExecutionContext): Route = {
    sendJson(StatusCodes.OK, content)
  }

  def sendJson(statusCode: StatusCode, json: Json)(implicit ec: ExecutionContext): Route = {
    send(statusCode, Option(json.noSpaces))
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:58,代码来源:Controller.scala

示例2: ScalaTagsSupport

//设置package包名称以及导入依赖的类
package task.airport
package util

import akka.http.scaladsl.marshalling.Marshaller.StringMarshaller
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.model.MediaTypes.`text/html`

import scalatags.Text.Tag

// See: https://github.com/cretz/scala-web-ideal/blob/master/server/src/main/scala/webideal/util/ScalaTagsSupport.scala
trait ScalaTagsSupport {

  implicit val ScalaTagsMarshaller: ToEntityMarshaller[Tag] =
    (StringMarshaller wrap `text/html`) {
      case html if html.tag == "html" => s"<!DOCTYPE html>${html.render}"
      case tag => tag.render
    }

}

object ScalaTagsSupport extends ScalaTagsSupport 
开发者ID:rarrabi,项目名称:task-airport,代码行数:22,代码来源:ScalaTagsSupport.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: getWithCfpbHeaders

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

import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.model.{ HttpMethods, HttpRequest }
import hmda.api.headers.{ HmdaInstitutionsHeader, HmdaUsernameHeader }

trait RequestHeaderUtils extends RequestBuilding {
  import HttpMethods._

  def getWithCfpbHeaders(path: String): HttpRequest = {
    new RequestBuilder(GET).apply(path)
      .addHeader(usernameHeader)
      .addHeader(institutionsHeader)
  }

  def postWithCfpbHeaders[T, ec: EC](path: String, content: T)(implicit m: ToEntityMarshaller[T]) = {
    new RequestBuilder(POST).apply(path, content)
      .addHeader(usernameHeader)
      .addHeader(institutionsHeader)
  }

  def postWithCfpbHeaders(path: String) = {
    new RequestBuilder(POST).apply(path)
      .addHeader(usernameHeader)
      .addHeader(institutionsHeader)
  }

  val usernameHeader = new HmdaUsernameHeader("banker11")
  val institutionsHeader = new HmdaInstitutionsHeader(List("0", "xxxxx"))

} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:33,代码来源:RequestHeaderUtils.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: 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

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

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

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

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

示例13: Main

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

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, ToResponseMarshaller }
import cats.MonadError
import cats.implicits._
import petclinic.implicits._
import scala.concurrent.ExecutionContext

object Main {
  def main(args: Array[String]): Unit = {
    implicit val system       = ActorSystem("petclinic-as")
    implicit val materializer = ActorMaterializer()
    implicit val ec           = system.dispatcher
    Http().bindAndHandle(service().route, "localhost", 8080)
    println(s"Server online at http://localhost:8080/")
  }
}

object service {
  def apply()(implicit ec: ExecutionContext): PetClinicService[Response] =
    new PetClinicService[Response] {
      def fmarshaller[A](
          implicit ma: ToEntityMarshaller[A],
          me: ToEntityMarshaller[PetClinicError]): ToResponseMarshaller[Response[A]] =
        implicitly
      val monadEv: MonadError[Response, PetClinicError] = implicitly
    }
} 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:32,代码来源:Main.scala

示例14: 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 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:34,代码来源:Marshallers.scala

示例15: __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


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