本文整理汇总了Scala中akka.http.scaladsl.server.RejectionHandler类的典型用法代码示例。如果您正苦于以下问题:Scala RejectionHandler类的具体用法?Scala RejectionHandler怎么用?Scala RejectionHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RejectionHandler类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1:
//设置package包名称以及导入依赖的类
package io.hydrosphere.mist.master.interfaces.http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.directives.ContentTypeResolver.Default
import akka.http.scaladsl.server.{Directives, RejectionHandler, Route}
private val fallbackToSpa = RejectionHandler.newBuilder()
.handleNotFound(getFromFile(index))
.result()
val route: Route = {
pathPrefix("ui") {
get {
pathEnd {
redirect("/ui/", PermanentRedirect)
} ~
pathSingleSlash {
getFromFile(index)
} ~
handleRejections(fallbackToSpa) {
getFromDirectory(path)
}
}
}
}
}
开发者ID:Hydrospheredata,项目名称:mist,代码行数:29,代码来源:HttpUi.scala
示例2: Hello
//设置package包名称以及导入依赖的类
package com.github.cupenya.hello
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, Directives, RejectionHandler }
import akka.http.scaladsl.model.StatusCodes._
import com.github.cupenya.hello.authentication.AuthorizationDirectives
import spray.json._
import scala.concurrent.ExecutionContext
case class Hello(message: String)
case class AuthError(error: String)
trait Protocols extends DefaultJsonProtocol {
implicit val helloFormat = jsonFormat1(Hello)
}
trait HelloHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with Protocols with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val helloRoute = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("hello") {
get {
complete(Hello(s"hello ${authInfo.userId}"))
}
}
}
}
}
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:39,代码来源:HelloHttpService.scala
示例3: handler
//设置package包名称以及导入依赖的类
package com.queirozf.utils
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{MalformedQueryParamRejection, MalformedRequestContentRejection, RejectionHandler}
import com.queirozf.utils.ResponseUtils.JsonBadRequest
def handler = {
RejectionHandler
.newBuilder()
.handle {
case MalformedRequestContentRejection(msg, e) => complete(JsonBadRequest("GLOBAL", msg, Some(e)))
case MalformedQueryParamRejection(parameterName, errorMsg, maybeThrowable) =>
maybeThrowable match {
case Some(e) => complete(JsonBadRequest(parameterName,errorMsg, Some(e)))
case None => complete(JsonBadRequest(parameterName, errorMsg))
}
}
.result()
.withFallback(RejectionHandler.default)
}
}
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:23,代码来源:CustomRejectionHandling.scala
示例4: AuthError
//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directives, RejectionHandler}
import com.github.cupenya.microservices.sdk.authentication.AuthorizationDirectives
import com.github.cupenya.microservices.sdk.logging.Logging
import spray.json._
import scala.concurrent.ExecutionContext
case class AuthError(error: String)
trait SampleHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with DefaultJsonProtocol with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val routes = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("test") {
get {
complete(OK, None)
}
}
}
}
}
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:34,代码来源:SampleHttpService.scala
示例5: corsAllowOrigins
//设置package包名称以及导入依赖的类
package com.signalswarm
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Route, Directive0, MethodRejection, RejectionHandler}
trait CorsSupport {
protected def corsAllowOrigins: List[String]
protected def corsAllowedHeaders: List[String]
protected def corsAllowCredentials: Boolean
protected def optionsCorsHeaders: List[HttpHeader]
protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
.newBuilder().handle {
case MethodRejection(supported) =>
complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, supported) ::
allowOrigin ::
optionsCorsHeaders
))
}
.result()
private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
else
None
def cors[T]: Directive0 = mapInnerRoute { route => context =>
((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
case (OPTIONS, Some(allowOrigin)) =>
handleRejections(corsRejectionHandler(allowOrigin)) {
respondWithHeaders(allowOrigin,
`Access-Control-Allow-Credentials`(corsAllowCredentials)) {
preflightRequestHandler ~ route
}
}
case (_, Some(allowOrigin)) =>
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route ~ preflightRequestHandler
}
case (_, _) =>
route
})(context)
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE),
`Access-Control-Allow-Headers`(corsAllowedHeaders)
)
)
}
}
开发者ID:rmccray,项目名称:micro-service-seed,代码行数:62,代码来源:CorsSupport.scala
示例6:
//设置package包名称以及导入依赖的类
package com.acromancer.acromancer.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport
with SecuritySupport
with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:GitsAndGlamour,项目名称:acromancer-game,代码行数:35,代码来源:RoutesRequestWrapper.scala
示例7: exceptionHandler
//设置package包名称以及导入依赖的类
package com.peim.utils
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, MethodRejection, RejectionHandler, ValidationRejection}
import com.peim.model.exception.MoneyServiceException
import com.peim.model.response.ErrorResponse
import play.api.libs.json.Json
trait ExceptionHandlers {
implicit def exceptionHandler: ExceptionHandler =
ExceptionHandler {
case e: MoneyServiceException =>
extractUri { uri =>
val errorResponse = ErrorResponse(Conflict.intValue,
"Conflict", e.getMessage)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(Conflict, entity = entity))
}
case e: Exception =>
extractUri { uri =>
val errorResponse = ErrorResponse(InternalServerError.intValue,
"Internal Server Error", e.getMessage)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(InternalServerError, entity = entity))
}
}
implicit def rejectionHandler: RejectionHandler =
RejectionHandler.newBuilder()
.handleNotFound {
val errorResponse = ErrorResponse(NotFound.intValue,
"NotFound", "The requested resource could not be found.")
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(NotFound, entity = entity))
}
.handle { case ValidationRejection(message, _) =>
val errorResponse = ErrorResponse(BadRequest.intValue, "Bad Request", message)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(BadRequest, entity = entity)) }
.handleAll[MethodRejection] { methodRejections =>
val names = methodRejections.map(_.supported.name)
val errorResponse = ErrorResponse(MethodNotAllowed.intValue,
"Not Allowed", s"Access to $names is not allowed.")
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(MethodNotAllowed, entity = entity))
}
.result()
}
开发者ID:peim,项目名称:money-transfer-service,代码行数:52,代码来源:ExceptionHandlers.scala
示例8: corsAllowOrigins
//设置package包名称以及导入依赖的类
package sri.sangria.mongoserver.routes
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Credentials`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Methods`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Origin`
import akka.http.scaladsl.model.headers.Origin
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.MethodRejection
import akka.http.scaladsl.server.RejectionHandler
trait CorsSupport {
protected def corsAllowOrigins: List[String]
protected def corsAllowedHeaders: List[String]
protected def corsAllowCredentials: Boolean
protected def optionsCorsHeaders: List[HttpHeader]
protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
.newBuilder().handle {
case MethodRejection(supported) =>
complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, supported) ::
allowOrigin ::
optionsCorsHeaders
))
}
.result()
private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
else
None
def cors[T]: Directive0 = mapInnerRoute { route => context =>
((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
case (OPTIONS, Some(allowOrigin)) =>
handleRejections(corsRejectionHandler(allowOrigin)) {
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route
}
}
case (_, Some(allowOrigin)) =>
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route
}
case (_, _) =>
route
})(context)
}
}
开发者ID:chandu0101,项目名称:sri-sangria-example,代码行数:59,代码来源:CorsSupport.scala
示例9:
//设置package包名称以及导入依赖的类
package com.softwaremill.bootzooka.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport with SecuritySupport with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:Bii03,项目名称:students-clustering,代码行数:33,代码来源:RoutesRequestWrapper.scala
示例10: allowedOrigins
//设置package包名称以及导入依赖的类
package allawala.chassis.http.route
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.headers.{Allow, HttpOrigin, HttpOriginRange}
import akka.http.scaladsl.server.{Directives, MethodRejection, RejectionHandler}
import ch.megard.akka.http.cors.scaladsl.CorsDirectives._
import ch.megard.akka.http.cors.scaladsl.settings.CorsSettings
trait CorsSupport extends Directives {
private val AllOrigins = "*"
def allowedOrigins: Seq[String]
private def optionsRejectionHandler: RejectionHandler =
RejectionHandler.newBuilder().handleAll[MethodRejection] { rejections =>
val methods = rejections.map(_.supported)
lazy val names = methods.map(_.name).mkString(", ")
respondWithHeader(Allow(methods)) {
options {
complete(OK -> s"Supported methods : $names.")
} ~
complete(MethodNotAllowed -> s"HTTP method not allowed, supported methods: $names!")
}
}.result().withFallback(RejectionHandler.default)
private lazy val httpOriginRange = {
allowedOrigins.find(_.trim == AllOrigins) match {
case Some(_) => HttpOriginRange.*
case None => HttpOriginRange(allowedOrigins.map(HttpOrigin(_)): _*)
}
}
lazy val corsSettings: CorsSettings.Default = CorsSettings.defaultSettings.copy(
allowedOrigins = httpOriginRange,
allowedMethods = scala.collection.immutable.Seq(OPTIONS, POST, PUT, GET, DELETE)
)
lazy val rejectionHandler: RejectionHandler = corsRejectionHandler withFallback optionsRejectionHandler
}
开发者ID:allawala,项目名称:service-chassis,代码行数:42,代码来源:CorsSupport.scala
示例11: corsRejectionHandler
//设置package包名称以及导入依赖的类
package com.mz.training.common.rest
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpMethods, HttpResponse}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, MethodRejection, RejectionHandler}
trait CorsSupport {
protected val corsAllowOrigins: List[String] = List("*")
protected val corsAllowedHeaders: List[String] = List("Origin", "X-Requested-With", "Content-Type", "Accept", "Accept-Encoding", "Accept-Language", "Host", "Referer", "User-Agent")
protected val corsAllowCredentials: Boolean = true
protected val optionsCorsHeaders: List[HttpHeader] = List[HttpHeader](
`Access-Control-Allow-Methods`(HttpMethods.GET, HttpMethods.PUT, HttpMethods.POST, HttpMethods.DELETE),
`Access-Control-Allow-Headers`(corsAllowedHeaders.mkString(", ")),
`Access-Control-Max-Age`(60 * 60 * 24 * 20), // cache pre-flight response for 20 days
`Access-Control-Allow-Credentials`(corsAllowCredentials)
)
protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
.newBuilder().handle {
case MethodRejection(supported) =>
complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, supported) ::
allowOrigin ::
optionsCorsHeaders
))
}
.result()
private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
else
None
def cors[T]: Directive0 = mapInnerRoute { route => context =>
((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
case (OPTIONS, Some(allowOrigin)) =>
handleRejections(corsRejectionHandler(allowOrigin)) {
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route
}
}
case (_, Some(allowOrigin)) =>
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route
}
case (_, _) =>
route
})(context)
}
}
开发者ID:michalzeman,项目名称:angular2-training,代码行数:60,代码来源:AkkaHttpCorsSupport.scala
示例12:
//设置package包名称以及导入依赖的类
package northendlink.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport
with SecuritySupport
with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:OOSINT,项目名称:NorthendLink-Site,代码行数:35,代码来源:RoutesRequestWrapper.scala
注:本文中的akka.http.scaladsl.server.RejectionHandler类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论