akka.http.scaladsl.server.RouteResult Scala Examples
The following examples show how to use akka.http.scaladsl.server.RouteResult.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: CompositeHttpService.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model.headers._ import akka.http.scaladsl.model.{HttpRequest, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.RouteResult.Complete import akka.http.scaladsl.server.directives.{DebuggingDirectives, LoggingMagnet} import akka.http.scaladsl.server.{Directive0, Route, RouteResult} import com.wavesplatform.dex.Application import com.wavesplatform.dex.api.routes.ApiRoute import com.wavesplatform.dex.domain.utils.ScorexLogging import com.wavesplatform.dex.settings.RestAPISettings class CompositeHttpService(apiTypes: Set[Class[_]], routes: Seq[ApiRoute], settings: RestAPISettings) extends ScorexLogging { private val swaggerService = new SwaggerDocService(apiTypes, s"${settings.address}:${settings.port}") private val redirectToSwagger = redirect("/api-docs/index.html", StatusCodes.PermanentRedirect) private val swaggerRoute: Route = swaggerService.routes ~ (pathEndOrSingleSlash | path("swagger"))(redirectToSwagger) ~ pathPrefix("api-docs") { pathEndOrSingleSlash(redirectToSwagger) ~ getFromResourceDirectory(s"META-INF/resources/webjars/swagger-ui/${SwaggerUiVersion.VersionString}", Application.getClass.getClassLoader) } val compositeRoute: Route = extendRoute(routes.map(_.route).reduce(_ ~ _)) ~ swaggerRoute ~ complete(StatusCodes.NotFound) val loggingCompositeRoute: Route = DebuggingDirectives.logRequestResult(LoggingMagnet(_ => logRequestResponse))(compositeRoute) private def logRequestResponse(req: HttpRequest)(res: RouteResult): Unit = res match { case Complete(resp) => val msg = s"HTTP ${resp.status.value} from ${req.method.value} ${req.uri}" if (resp.status == StatusCodes.OK) log.info(msg) else log.warn(msg) case _ => } private val corsAllowedHeaders = (if (settings.apiKeyDifferentHost) List("api_key", "X-API-Key") else List.empty[String]) ++ Seq("Authorization", "Content-Type", "X-Requested-With", "Timestamp", "Signature") private def corsAllowAll: Directive0 = if (settings.cors) respondWithHeader(`Access-Control-Allow-Origin`.*) else pass private def extendRoute(base: Route): Route = if (settings.cors) { ctx => val extendedRoute = corsAllowAll(base) ~ options { respondWithDefaultHeaders( `Access-Control-Allow-Credentials`(true), `Access-Control-Allow-Headers`(corsAllowedHeaders), `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE) )(corsAllowAll(complete(StatusCodes.OK))) } extendedRoute(ctx) } else base }
Example 2
Source File: Entities.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.controller import scala.concurrent.Future import scala.language.postfixOps import scala.util.Try import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.model.StatusCodes.PayloadTooLarge import akka.http.scaladsl.model.headers.RawHeader import akka.http.scaladsl.server.Directive0 import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.RequestContext import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.RouteResult import spray.json.JsonPrinter import org.apache.openwhisk.common.TransactionId import org.apache.openwhisk.core.entitlement.Privilege._ import org.apache.openwhisk.core.entitlement.Privilege import org.apache.openwhisk.core.entitlement.Privilege.READ import org.apache.openwhisk.core.entitlement.Resource import org.apache.openwhisk.core.entity._ import org.apache.openwhisk.core.entity.ActivationEntityLimit import org.apache.openwhisk.core.entity.size._ import org.apache.openwhisk.http.ErrorResponse.terminate import org.apache.openwhisk.http.Messages protected[controller] trait ValidateRequestSize extends Directives { protected def validateSize(check: => Option[SizeError])(implicit tid: TransactionId, jsonPrinter: JsonPrinter) = new Directive0 { override def tapply(f: Unit => Route) = { check map { case e: SizeError => terminate(PayloadTooLarge, Messages.entityTooBig(e)) } getOrElse f(None) } } protected final def isEntity(n: String) = Try { EntityName(n) } isSuccess }
Example 3
Source File: RouteUtils.scala From akka-grpc with Apache License 2.0 | 5 votes |
package akka.grpc.javadsl import scala.concurrent.ExecutionContext import java.util.concurrent.CompletionStage import akka.actor.ClassicActorSystemProvider import akka.annotation.ApiMayChange import akka.http.scaladsl import akka.http.javadsl.model.{ HttpRequest, HttpResponse } import akka.http.javadsl.server.Route import akka.http.javadsl.server.directives.RouteAdapter import akka.http.scaladsl.server.RouteResult import akka.japi.Function import scala.compat.java8.FutureConverters def toFunction( route: Route, system: ClassicActorSystemProvider): Function[HttpRequest, CompletionStage[HttpResponse]] = { implicit val sys = system.classicSystem implicit val ec: ExecutionContext = sys.dispatcher val handler = scaladsl.server.Route.asyncHandler(route.asScala) (request: HttpRequest) => { import FutureConverters._ handler(request.asInstanceOf[scaladsl.model.HttpRequest]).map(_.asInstanceOf[HttpResponse]).toJava } } }
Example 4
Source File: AkkaHttpActionAdapter.scala From akka-http-pac4j with Mozilla Public License 2.0 | 5 votes |
package com.stackstate.pac4j.http import akka.http.scaladsl.model.{HttpEntity, HttpHeader, HttpResponse, StatusCodes, Uri} import org.pac4j.core.context.HttpConstants import org.pac4j.core.http.adapter.HttpActionAdapter import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server.RouteResult import akka.http.scaladsl.server.RouteResult.Complete import com.stackstate.pac4j.AkkaHttpWebContext import org.pac4j.core.exception.http.{ BadRequestAction, ForbiddenAction, FoundAction, HttpAction, NoContentAction, OkAction, SeeOtherAction, TemporaryRedirectAction, UnauthorizedAction } import scala.concurrent.Future object AkkaHttpActionAdapter extends HttpActionAdapter[Future[RouteResult], AkkaHttpWebContext] { override def adapt(action: HttpAction, context: AkkaHttpWebContext): Future[Complete] = { Future.successful(Complete(action match { case _: UnauthorizedAction => // XHR requests don't receive a TEMP_REDIRECT but a UNAUTHORIZED. The client can handle this // to trigger the proper redirect anyway, but for a correct flow the session cookie must be set context.addResponseSessionCookie() HttpResponse(Unauthorized) case _: BadRequestAction => HttpResponse(BadRequest) case _ if action.getCode == HttpConstants.CREATED => HttpResponse(Created) case _: ForbiddenAction => HttpResponse(Forbidden) case a: FoundAction => context.addResponseSessionCookie() HttpResponse(SeeOther, headers = List[HttpHeader](Location(Uri(a.getLocation)))) case a: SeeOtherAction => context.addResponseSessionCookie() HttpResponse(SeeOther, headers = List[HttpHeader](Location(Uri(a.getLocation)))) case a: OkAction => val contentBytes = a.getContent.getBytes val entity = context.getContentType.map(ct => HttpEntity(ct, contentBytes)).getOrElse(HttpEntity(contentBytes)) HttpResponse(OK, entity = entity) case _: NoContentAction => HttpResponse(NoContent) case _ if action.getCode == 500 => HttpResponse(InternalServerError) case _ => HttpResponse(StatusCodes.getForKey(action.getCode).getOrElse(custom(action.getCode, ""))) })) } }
Example 5
Source File: RouteLogging.scala From akka-ddd-cqrs-es-example with MIT License | 5 votes |
package com.github.j5ik2o.bank.adaptor.controller import akka.event.Logging import akka.http.scaladsl.model.headers.{ Authorization, BasicHttpCredentials } import akka.http.scaladsl.model.{ HttpRequest, HttpResponse } import akka.http.scaladsl.server.{ Directive0, RouteResult } import akka.http.scaladsl.server.directives.{ DebuggingDirectives, LogEntry } trait RequestFormatter { def formatRequest(request: HttpRequest): LogEntry } trait RequestResultFormatter { def formatRequestResponse(request: HttpRequest): RouteResult => Option[LogEntry] } object DefaultRequestLoggingFormatter { implicit object requestFormatter extends RequestFormatter { override def formatRequest(request: HttpRequest): LogEntry = { LogEntry(s"${formatRequestToString(request)}/", Logging.InfoLevel) } } implicit object requestResultFormatter extends RequestResultFormatter { override def formatRequestResponse(request: HttpRequest): (RouteResult) => Option[LogEntry] = { case RouteResult.Complete(response) => val req = formatRequestToString(request) val res = formatResponseToString(response) Some(LogEntry(s"$req/$res", Logging.InfoLevel)) case _ => val req = formatRequestToString(request) Some(LogEntry(req, Logging.InfoLevel)) } } private def formatRequestToString(request: HttpRequest): String = { val protocol = request.protocol.value val method = request.method.name() val path = request.uri.toString() val headers = request.headers .collect { case Authorization(_: BasicHttpCredentials) => "authorization:Basic ***" case Authorization(_) => "authorization:***" case h => s"'${h.lowercaseName()}':'${h.value()}'" } .mkString(", ") s"$protocol $method $path [$headers]" } private def formatResponseToString(request: HttpResponse): String = { val status = request.status.value val headers = request.headers.map(h => s"'${h.lowercaseName()}':'${h.value()}'").mkString(", ") s"$status [$headers]" } } class RouteLogging()(implicit requestFormatter: RequestFormatter, requestResultFormatter: RequestResultFormatter) { val httpLogRequest: Directive0 = DebuggingDirectives.logRequest(requestFormatter.formatRequest _) val httpLogRequestResult: Directive0 = DebuggingDirectives.logRequestResult(requestResultFormatter.formatRequestResponse _) } object RouteLogging { def apply()(implicit requestFormatter: RequestFormatter, requestResultFormatter: RequestResultFormatter): RouteLogging = new RouteLogging() val default: RouteLogging = new RouteLogging()(DefaultRequestLoggingFormatter.requestFormatter, DefaultRequestLoggingFormatter.requestResultFormatter) }
Example 6
Source File: ProxyRoute.scala From vamp with Apache License 2.0 | 5 votes |
package io.vamp.http_api import akka.http.scaladsl.model.StatusCodes.BadGateway import akka.http.scaladsl.model.ws.UpgradeToWebSocket import akka.http.scaladsl.server.{ RequestContext, Route, RouteResult } import akka.stream.Materializer import akka.util.Timeout import io.vamp.common.Namespace import io.vamp.common.http.HttpApiDirectives import io.vamp.model.artifact.{ Gateway, Deployment, Workflow } import io.vamp.operation.controller.ProxyController import scala.concurrent.Future import scala.util.Try trait ProxyRoute extends AbstractRoute with ProxyController { this: HttpApiDirectives ⇒ implicit def materializer: Materializer def proxyRoute(implicit namespace: Namespace, timeout: Timeout): Route = path("host" / Segment / "port" / Segment / RemainingPath) { (host, port, path) ⇒ Try(handle(hostPortProxy(host, port.toInt, path))).getOrElse(complete(BadGateway)) } ~ path(Gateway.kind / Segment / Segment / Segment / RemainingPath) { (name1, name2, name3, path) ⇒ handle(gatewayProxy(s"$name1/$name2/$name3", path, skip = true)) } ~ path(Gateway.kind / Segment / Segment / RemainingPath) { (name1, name2, path) ⇒ handle(gatewayProxy(s"$name1/$name2", path, skip = true)) } ~ path(Gateway.kind / Segment / RemainingPath) { (gateway, path) ⇒ handle(gatewayProxy(gateway, path, skip = false)) } ~ path(Workflow.kind / Segment / "instances" / Segment / "ports" / Segment / RemainingPath) { (workflow, instance, port, path) ⇒ handle(instanceProxy(workflow, instance, port, path)) } ~ path(Deployment.kind / Segment / "clusters" / Segment / "services" / Segment / "instances" / Segment / "ports" / Segment / RemainingPath) { (deployment, cluster, service, instance, port, path) ⇒ handle(instanceProxy(deployment, cluster, service, instance, port, path)) } private def handle(handler: (RequestContext, Option[UpgradeToWebSocket]) ⇒ Future[RouteResult]): Route = { extractUpgradeToWebSocket { upgrade ⇒ context ⇒ handler(context, Option(upgrade)) } ~ { context ⇒ handler(context, None) } } }
Example 7
Source File: ExplainApi.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.druid import akka.actor.ActorRefFactory import akka.http.scaladsl.model.HttpEntity import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.RouteResult import akka.pattern.ask import akka.util.Timeout import com.netflix.atlas.akka.CustomDirectives._ import com.netflix.atlas.akka.WebApi import com.netflix.atlas.druid.ExplainApi.ExplainRequest import com.netflix.atlas.eval.graph.Grapher import com.netflix.atlas.json.Json import com.netflix.atlas.webapi.GraphApi.DataRequest import com.typesafe.config.Config import scala.concurrent.duration._ class ExplainApi(config: Config, implicit val actorRefFactory: ActorRefFactory) extends WebApi { private val grapher: Grapher = Grapher(config) private val dbRef = actorRefFactory.actorSelection("/user/db") private implicit val ec = actorRefFactory.dispatcher override def routes: Route = { endpointPath("explain" / "v1" / "graph") { get { ctx => val graphCfg = grapher.toGraphConfig(ctx.request) dbRef .ask(ExplainRequest(DataRequest(graphCfg)))(Timeout(10.seconds)) .map { response => val json = Json.encode(response) val entity = HttpEntity(MediaTypes.`application/json`, json) RouteResult.Complete(HttpResponse(StatusCodes.OK, entity = entity)) } } } } } object ExplainApi { case class ExplainRequest(dataRequest: DataRequest) }
Example 8
Source File: UpdateApi.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc import akka.actor.ActorRefFactory import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.RouteResult import com.netflix.atlas.akka.CustomDirectives._ import com.netflix.atlas.akka.WebApi import com.netflix.atlas.webapi.PublishApi import scala.concurrent.Promise class UpdateApi(implicit val actorRefFactory: ActorRefFactory) extends WebApi { private val publishRef = actorRefFactory.actorSelection("/user/publish") override def routes: Route = { endpointPathPrefix("database" / "v1" / "update") { post { extractRequestContext { ctx => parseEntity(customJson(p => PublishApi.decodeList(p))) { datapoints => val promise = Promise[RouteResult]() publishRef ! PublishApi.PublishRequest(datapoints, Nil, promise, ctx) _ => promise.future } } } } } }
Example 9
Source File: ZIODirectives.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.server.{ Directive, Directive1, Route, RouteResult } import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.server.directives.RouteDirectives import akka.http.scaladsl.util.FastFuture._ import zio.{ DefaultRuntime, Task, ZIO } import scala.concurrent.{ Future, Promise } import scala.util.{ Failure, Success } def zioCompleteOrRecoverWith(magnet: ZIOCompleteOrRecoverWithMagnet): Directive1[Throwable] = magnet.directive } object ZIODirectives extends ZIODirectives trait ZIOCompleteOrRecoverWithMagnet { def directive: Directive1[Throwable] } object ZIOCompleteOrRecoverWithMagnet extends ZIODirectives { implicit def apply[T]( task: => Task[T] )(implicit m: ToResponseMarshaller[T]): ZIOCompleteOrRecoverWithMagnet = new ZIOCompleteOrRecoverWithMagnet { override val directive: Directive1[Throwable] = Directive[Tuple1[Throwable]] { inner => ctx => val future = unsafeRunToFuture(task) import ctx.executionContext future.fast.transformWith { case Success(res) => ctx.complete(res) case Failure(error) => inner(Tuple1(error))(ctx) } } } }