本文整理汇总了Scala中akka.http.scaladsl.marshalling.ToResponseMarshallable类的典型用法代码示例。如果您正苦于以下问题:Scala ToResponseMarshallable类的具体用法?Scala ToResponseMarshallable怎么用?Scala ToResponseMarshallable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ToResponseMarshallable类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: sendResponse
//设置package包名称以及导入依赖的类
package com.example.routes
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import com.example.config.ServerSettings
import com.example.model.{ ApiMessage, ApiMessages }
import scala.concurrent.Future
import scala.util.{ Failure, Success }
trait ResponseFactory {
import ServerSettings._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.generic.auto._
def sendResponse[T](
eventualResult: Future[T]
)(implicit _marshaller: T ? ToResponseMarshallable): Route =
onComplete(eventualResult) {
case Success(result) ?
log.info("akka-yourgiftcard HTTP Response: " + result.toString())
complete(result)
case Failure(e) ?
log.error(s"Error: ${e.toString}")
e match {
case e: Exception =>
complete(ToResponseMarshallable(UnprocessableEntity ? ApiMessage(e.getMessage)))
case _ =>
complete(
ToResponseMarshallable(
InternalServerError ? ApiMessage(ApiMessages.unknownException)
)
)
}
}
}
开发者ID:softinio,项目名称:akka-http-starter,代码行数:41,代码来源:ResponseFactory.scala
示例2: executor
//设置package包名称以及导入依赖的类
package com.ferhtaydn.server
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import com.ferhtaydn.models.{ JsonFormats, PatientInfo, PatientResult }
import com.ferhtaydn.rater.RatePredictor
import akka.http.scaladsl.model.StatusCodes._
import scala.concurrent.ExecutionContextExecutor
trait Server extends JsonFormats {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val logger: LoggingAdapter
def predictor: RatePredictor
protected val routes: Route =
pathPrefix("cancerater") {
get {
pathSingleSlash {
complete("Welcome to CanceRater")
}
} ~
get {
path("cm") {
complete {
predictor.confusionMatrixString.map[ToResponseMarshallable] {
case cm ? cm
}
}
}
} ~
post {
path("check") {
entity(as[PatientInfo]) { patientInfo ?
complete {
predictor.predict(patientInfo).map[ToResponseMarshallable] {
case Right(score) ? PatientResult(score)
case Left(error) ? BadRequest ? error
}
}
}
}
}
}
}
开发者ID:ferhtaydn,项目名称:canceRater,代码行数:57,代码来源:Server.scala
示例3: executionContext
//设置package包名称以及导入依赖的类
package onextent.oemap.server.http
import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.headers.Location
import akka.http.scaladsl.server.{Directives, Route}
import scala.concurrent.{ExecutionContext, Future}
trait JsonResource extends Directives with JsonSupport {
val notFoundCode = 404
val successCode = 204
implicit def executionContext: ExecutionContext
def completeWithLocationHeader[T](resourceId: Future[Option[T]], ifDefinedStatus: Int, ifEmptyStatus: Int): Route =
onSuccess(resourceId) {
case Some(t) => completeWithLocationHeader(ifDefinedStatus, t)
case None => complete(ifEmptyStatus, None)
}
def completeWithLocationHeader[T](status: Int, resourceId: T): Route =
extractRequestContext { requestContext =>
val request = requestContext.request
val location = request.uri.copy(path = request.uri.path / resourceId.toString)
respondWithHeader(Location(location)) {
complete(status, None)
}
}
def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route =
onSuccess(resource) {
case Some(t) => complete(ToResponseMarshallable(t))
case None => complete(notFoundCode, None)
}
def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(successCode, None) }
}
开发者ID:navicore,项目名称:oemap-server,代码行数:40,代码来源:JsonResource.scala
示例4: ImperativeRequestContext
//设置package包名称以及导入依赖的类
package org.cristal.api.helper
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise
final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
private implicit val ec = ctx.executionContext
def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}
trait ApiHelper {
def notImplementedResponse(msg: String = ""): StandardRoute =
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
s"<h1>We plan to support this resource soon.</h1>"))
def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
val p = Promise[RouteResult]()
inner(new ImperativeRequestContext(ctx, p))
p.future
}
}
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala
示例5: rootPath
//设置package包名称以及导入依赖的类
package hmda.api.http
import java.net.InetAddress
import java.time.Instant
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import hmda.api.model.Status
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import hmda.api.protocol.HmdaApiProtocol
import spray.json._
trait BaseHttpApi extends HmdaApiProtocol with HmdaCustomDirectives {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
val log: LoggingAdapter
def rootPath(name: String) =
pathSingleSlash {
timedGet { _ =>
complete {
val now = Instant.now.toString
val host = InetAddress.getLocalHost.getHostName
val status = Status("OK", name, now, host)
log.debug(status.toJson.toString)
ToResponseMarshallable(status)
}
}
}
def routes(apiName: String) = encodeResponse { rootPath(apiName) }
}
开发者ID:cfpb,项目名称:hmda-platform,代码行数:36,代码来源:BaseHttpApi.scala
示例6: json
//设置package包名称以及导入依赖的类
package scorex.api.http
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server._
import com.wavesplatform.http.{ApiMarshallers, PlayJsonException, api_key}
import com.wavesplatform.settings.RestAPISettings
import play.api.libs.json.Reads
import scorex.crypto.encode.Base58
import scorex.crypto.hash.SecureCryptographicHash
trait ApiRoute extends Directives with CommonApiFunctions with ApiMarshallers {
val settings: RestAPISettings
val route: Route
private lazy val apiKeyHash = Base58.decode(settings.apiKeyHash).toOption
private val jsonRejectionHandler = RejectionHandler.newBuilder().handle {
case ValidationRejection(_, Some(PlayJsonException(cause, errors))) => complete(WrongJson(cause, errors))
}.result()
def json[A: Reads](f: A => ToResponseMarshallable): Route = handleRejections(jsonRejectionHandler) {
entity(as[A]) { a => complete(f(a)) }
}
def withAuth: Directive0 = apiKeyHash.fold(pass) { hashFromSettings =>
optionalHeaderValueByType[api_key](()).flatMap {
case Some(k) if SecureCryptographicHash(k.key).sameElements(hashFromSettings) => pass
case _ => complete(ApiKeyNotValid)
}
}
def processRequest[A: Reads](pathMatcher: String, f: A => ToResponseMarshallable): Route =
(path(pathMatcher) & post & withAuth) {
json[A](f)
}
}
开发者ID:wavesplatform,项目名称:Waves,代码行数:38,代码来源:ApiRoute.scala
示例7: omdbApiRequest
//设置package包名称以及导入依赖的类
package org.yashsriv.api
import java.io.IOException
import scala.concurrent.Future
import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ HttpResponse, HttpRequest }
import akka.http.scaladsl.model.StatusCodes.{ OK, BadRequest }
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.unmarshalling.Unmarshal
import spray.json._
import org.yashsriv.helpers.Worker
import org.yashsriv.json.MovieSupport
import org.yashsriv.models.MovieQuery
import org.yashsriv.models.MovieResult
trait Movie extends Directives with Worker with MovieSupport with SprayJsonSupport {
def omdbApiRequest(request: HttpRequest): Future[HttpResponse] = Http().singleRequest(request)
def movieApi(implicit requestUri: Uri): Route = pathPrefix("movie") {
(post & entity(as[MovieQuery])) { movieQuery ?
complete {
fetchMovieInfo(movieQuery).map[ToResponseMarshallable] {
case Right(movieInfo) => movieInfo
case Left(errorMessage) => BadRequest ? errorMessage
}
}
}
}
def fetchMovieInfo(mq: MovieQuery)(implicit requestUri: Uri): Future[Either[String, MovieResult]] = {
omdbApiRequest(RequestBuilding.Get(requestUri withQuery convertToQuery(mq))).flatMap { response =>
response.status match {
case OK ? Unmarshal(response.entity).to[MovieResult].map(Right(_))
case BadRequest ? Future.successful(Left(s"${mq.toJson.prettyPrint} \nIncorrect Movie Format"))
case _ ? Unmarshal(response.entity).to[String].flatMap { entity ?
val error = s"Omdb request failed with status code ${response.status} and entity $entity"
Future.failed(new IOException(error))
}
}
}
}
}
开发者ID:yashsriv,项目名称:akka-http-batch-api,代码行数:54,代码来源:Movie.scala
示例8: ManagementRoute
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.standalone.http
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.{Directives, Route}
import cats.data.NonEmptyList
import com.typesafe.scalalogging.LazyLogging
import pl.touk.nussknacker.engine.api.deployment.DeploymentData
import pl.touk.nussknacker.engine.standalone.management.{DeploymentError, DeploymentService}
import pl.touk.nussknacker.engine.util.ThreadUtils
import pl.touk.http.argonaut.Argonaut62Support
import scala.concurrent.ExecutionContext
class ManagementRoute(processesClassLoader: ClassLoader, deploymentService: DeploymentService) extends Directives with Argonaut62Support with LazyLogging {
import argonaut.ArgonautShapeless._
def route(implicit ec: ExecutionContext): Route = ThreadUtils.withThisAsContextClassLoader(processesClassLoader) {
path("deploy") {
post {
entity(as[DeploymentData]) { data =>
complete {
toResponse(deploymentService.deploy(data.processId, data.processJson))
}
}
}
} ~ path("checkStatus" / Segment) { processId =>
get {
complete {
deploymentService.checkStatus(processId) match {
case None => HttpResponse(status = StatusCodes.NotFound)
case Some(resp) => resp
}
}
}
} ~ path("cancel" / Segment) { processId =>
post {
complete {
deploymentService.cancel(processId) match {
case None => HttpResponse(status = StatusCodes.NotFound)
case Some(resp) => resp
}
}
}
}
}
def toResponse(either: Either[NonEmptyList[DeploymentError], Unit]): ToResponseMarshallable = either match {
case Right(unit) =>
unit
case Left(error) =>
//TODO: something better?
HttpResponse(status = StatusCodes.BadRequest, entity = error.toList.mkString(", "))
}
}
开发者ID:TouK,项目名称:nussknacker,代码行数:60,代码来源:ManagementRoute.scala
示例9: 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
开发者ID:notxcain,项目名称:aecor,代码行数:23,代码来源:MonixSupport.scala
示例10: executor
//设置package包名称以及导入依赖的类
package zeroweather.proxy
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.stream.{ ActorMaterializer, Materializer }
import spray.json._
import zeroweather.message.Weather
import scala.concurrent.ExecutionContextExecutor
trait Protocols extends DefaultJsonProtocol {
implicit val weatherFormat = jsonFormat4(Weather.apply)
}
trait ProxyService extends Protocols {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val supplierConnector: SupplierConnector
implicit def exceptionHandler = ExceptionHandler {
case e: java.io.IOException =>
extractUri { uri =>
complete(HttpResponse(ServiceUnavailable, entity = e.getMessage))
}
}
val routes = {
pathPrefix("weather" / """[a-z]{2}""".r / """[a-zA-Z ]+""".r) { (countryCode, city) =>
pathEnd {
get {
complete {
supplierConnector.fetchWeather(countryCode, city).map[ToResponseMarshallable] {
case Right(weather) => weather
case Left(error) => BadRequest -> error
}
}
}
}
}
}
}
object Proxy extends App with ProxyService with Supplier with Configuration {
override implicit val system = ActorSystem("Proxy")
override implicit val executor = system.dispatcher
override implicit val materializer = ActorMaterializer()
Http().bindAndHandle(routes, config.getString("http.interface"), config.getInt("http.port"))
}
开发者ID:sbilinski,项目名称:zeroweather,代码行数:58,代码来源:Proxy.scala
示例11: searchClient
//设置package包名称以及导入依赖的类
package houseprices.search
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.Directives.get
import akka.http.scaladsl.server.Directives.path
import akka.http.scaladsl.server.Directives.segmentStringToPathMatcher
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import houseprices.search.model._
import houseprices.search.model.SearchResultJsonProtocol._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import scala.concurrent.ExecutionContext
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
trait SearchJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
implicit val format2 = jsonFormat3(PricePaidData)
implicit val format1 = jsonFormat2(SearchResult)
}
trait HousePriceSearchService extends SearchJsonProtocol {
def searchClient: SearchClient
implicit val ec: ExecutionContext
val routes =
path("search" / ".*".r) { text =>
get {
complete {
searchClient.search(Query(text))
}
}
}
}
class HousePriceSearchServer(val searchClient: SearchClient)(implicit val system: ActorSystem, implicit val materializer: ActorMaterializer) extends HousePriceSearchService {
val log = Logging(system, getClass)
implicit val ec = system.dispatcher
def startServer(interface: String, port: Int) = {
Http().bindAndHandle(routes, interface, port)
log.info("Search server ready at {}:{}", interface, port)
this
}
}
object DevHousePriceSearchServer extends App {
implicit val system = ActorSystem("housePriceSearchServer")
implicit val materializer = ActorMaterializer()
val searchClient = HttpSearchClient(system)
new HousePriceSearchServer(searchClient).startServer("localhost", 8080)
}
开发者ID:ayubmalik,项目名称:houseprices,代码行数:57,代码来源:HousePriceSearchServer.scala
示例12: SlackService
//设置package包名称以及导入依赖的类
package inbound
import akka.actor.ActorSystem
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import outbound.slack.responses.AuthTestResponse
import outbound.slack.SlackConsumer
import scala.concurrent.ExecutionContext
class SlackService(implicit s: ActorSystem, m: ActorMaterializer, ec: ExecutionContext) {
import AuthTestResponse._
val ws = new SlackConsumer
val routes =
pathPrefix("test") {
path("auth") {
get {
parameters('token) { token =>
complete {
ws.authTest(token).map[ToResponseMarshallable] {
case Right(authTestResponse) => authTestResponse
case Left(errorMessage) => {
s.log.error(errorMessage)
BadRequest -> errorMessage
}
}
}
}
}
} ~
path("api") {
get {
parameters('error.?, 'foo.?) { (error, foo) =>
complete {
ws.apiTest(error, foo).map[ToResponseMarshallable] {
case Right(apiTestResponse) => apiTestResponse
case Left(errorMessage) => {
s.log.error(errorMessage)
BadRequest -> errorMessage
}
}
}
}
}
}
}
}
开发者ID:rocketpages,项目名称:slakka,代码行数:55,代码来源:SlackService.scala
示例13: HealthResource
//设置package包名称以及导入依赖的类
package hlouw.dcos.service.rest.resources
import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import hlouw.dcos.service.rest.services.HealthCheck
import scala.concurrent.ExecutionContextExecutor
class HealthResource(router: String)(implicit system: ActorSystem, executor: ExecutionContextExecutor, materializer: ActorMaterializer) {
val routes =
path("ping") {
complete("pong")
} ~
path("health") {
complete {
HealthCheck.pingDependencies(router).map[ToResponseMarshallable] {
case s => StatusCodes.OK -> s
}
}
}
}
开发者ID:hlouw,项目名称:dcos-rest-service,代码行数:27,代码来源:HealthResource.scala
示例14: executionContext
//设置package包名称以及导入依赖的类
package com.vaiski.linkr.routing
import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.Location
import akka.http.scaladsl.server.{Directives, Route}
import com.vaiski.linkr.serializers.JsonSupport
import scala.concurrent.{ExecutionContext, Future}
trait JsonResource extends Directives with JsonSupport {
implicit def executionContext: ExecutionContext
def completeWithLocationHeader[T](location: Future[String]): Route =
onSuccess(location) { url =>
respondWithHeader(Location(url)) {
complete(StatusCodes.MovedPermanently, None)
}
}
def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route =
onSuccess(resource) {
case Some(t) => complete(ToResponseMarshallable(t))
case None => complete(StatusCodes.NotFound, None)
}
def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(StatusCodes.NoContent, None) }
}
开发者ID:vaiski,项目名称:linkr,代码行数:29,代码来源:JsonResource.scala
示例15: executionContext
//设置package包名称以及导入依赖的类
package resources.rest
import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.headers.Location
import akka.http.scaladsl.server.{Directives, Route}
import org.json4s.{DefaultFormats, native}
import scala.concurrent.{ExecutionContext, Future}
trait BaseResource extends Directives {
implicit val serialization = native.Serialization
implicit val formats = DefaultFormats
implicit def executionContext: ExecutionContext
implicit val system = ActorSystem("microservices-cqrs")
def completeWithLocationHeader[T](resourceId: Future[Option[T]], ifDefinedStatus: Int, ifEmptyStatus: Int): Route =
onSuccess(resourceId) {
case Some(t) => completeWithLocationHeader(ifDefinedStatus, t)
case None => complete(ifEmptyStatus, None)
}
def completeWithLocationHeader[T](status: Int, resourceId: T): Route =
extractRequestContext { requestContext =>
val request = requestContext.request
val location = request.uri.copy(path = request.uri.path / resourceId.toString)
respondWithHeader(Location(location)) {
complete(status, None)
}
}
def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route =
onSuccess(resource) {
case Some(t) => complete(ToResponseMarshallable(t))
case None => complete(404, None)
}
def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(204, None) }
}
开发者ID:servlok,项目名称:SimpleTODO,代码行数:44,代码来源:BaseResource.scala
示例16: reject
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives
import akka.http.documenteddsl._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes.Redirection
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.server.Rejection
import akka.http.scaladsl.server.directives.RouteDirectives
trait RouteDDirectives {
def reject: DRoute = RouteDDirectives._reject
def reject(rejections: Rejection*): DRoute = DRoute(_.reject(rejections: _*))
def complete(m: => ToResponseMarshallable): DRoute = DRoute(_.complete(m))
def failWith(error: Throwable): DRoute = DRoute(_.fail(error))
def redirect(uri: Uri, redirectionType: Redirection): DRoute = DRoute(_.redirect(uri, redirectionType))
}
object RouteDDirectives extends RouteDDirectives {
private val _reject = DRoute.maybe(RouteDirectives.reject)
}
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:21,代码来源:RouteDDirectives.scala
示例17: GameTickerModulePerRequest
//设置package包名称以及导入依赖的类
package proton.game
import akka.actor.{Actor, ActorLogging, ActorRef, OneForOneStrategy, ReceiveTimeout, SupervisorStrategy}
import akka.event.LoggingReceive
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.{HttpRequest, StatusCode, StatusCodes}
import akka.http.scaladsl.server.RouteResult
import spray.json.{JsonPrinter, RootJsonFormat}
import scala.concurrent.Promise
class GameTickerModulePerRequest[TConfig <: GameTickerConfig, TSharedState <: GameSharedState,
TPublicState <: GamePublicState : RootJsonFormat, TPrivateState <: GamePrivateState[TPublicState],
TCommand <: GameCommand : RootJsonFormat]
(message: GameMessage[TConfig, TSharedState, TPublicState, TPrivateState, TCommand],
settings: GameTickerModuleSettings,
request: HttpRequest, promise: Promise[RouteResult], target: ActorRef,
envelope: Envelope)
extends Actor with ActorLogging with SprayJsonSupport with GameProtocol {
import context._
import StatusCodes._
import message._
import message.GameMessageProtocol._
implicit val printer: JsonPrinter = settings.jsonPrinter
setReceiveTimeout(settings.httpTimeout)
target ! envelope
def receive = LoggingReceive {
case [email protected](id, gameMeta) =>
if (gameMeta.status == GameStatus.GameNotConfigured) {
complete(NotFound, res)
}
else
complete(OK, res)
case res: GameResponse => complete(OK, res)
case v: Validation => complete(BadRequest, v)
case ReceiveTimeout => complete(GatewayTimeout, Validation("Request timeout", GameEvents.Timeout))
}
def complete[T <: AnyRef](status: StatusCode, obj: T)(implicit marshaller: ToResponseMarshaller[T]) = {
ToResponseMarshallable(obj).apply(request) onComplete {
case scala.util.Success(response) =>
promise.success(RouteResult.Complete(response.copy(status)))
stop(self)
case scala.util.Failure(e) =>
promise.failure(e)
stop(self)
}
}
override val supervisorStrategy =
OneForOneStrategy() {
case e =>
complete(InternalServerError, Validation("Could not complete request.", GameEvents.Unhandled, Some(e)))
SupervisorStrategy.Stop
}
}
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:62,代码来源:GameTickerModulePerRequest.scala
注:本文中的akka.http.scaladsl.marshalling.ToResponseMarshallable类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论