本文整理汇总了Scala中akka.http.scaladsl.marshalling.ToResponseMarshallable类的典型用法代码示例。如果您正苦于以下问题:Scala ToResponseMarshallable类的具体用法?Scala ToResponseMarshallable怎么用?Scala ToResponseMarshallable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ToResponseMarshallable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
)
)
}
}
}
示例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
}
}
}
}
}
}
}
示例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) }
}
示例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
}
}
示例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) }
}
示例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)
}
}
示例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))
}
}
}
}
}
示例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(", "))
}
}
示例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
示例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"))
}
示例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)
}
示例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
}
}
}
}
}
}
}
}
示例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
}
}
}
}
示例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) }
}
示例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) }
}