本文整理汇总了Scala中akka.http.scaladsl.model.HttpHeader类的典型用法代码示例。如果您正苦于以下问题:Scala HttpHeader类的具体用法?Scala HttpHeader怎么用?Scala HttpHeader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpHeader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: transportName
//设置package包名称以及导入依赖的类
package com.softwaremill.session
import akka.http.scaladsl.model.{DateTime, HttpHeader}
import akka.http.scaladsl.model.headers.{RawHeader, HttpCookie, Cookie, `Set-Cookie`}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session.TestData._
trait MultipleTransportTest { this: ScalatestRouteTest =>
trait TestUsingTransport {
def transportName: String
def getSession: Option[String]
def setSessionHeader(s: String): HttpHeader
def isSessionExpired: Boolean
def getRefreshToken: Option[String]
def setRefreshTokenHeader(s: String): HttpHeader
def isRefreshTokenExpired: Boolean
def getSessionTransport: GetSessionTransport
def setSessionTransport: SetSessionTransport
}
object TestUsingCookies extends TestUsingTransport {
val sessionCookieName = sessionConfig.sessionCookieConfig.name
val refreshTokenCookieName = sessionConfig.refreshTokenCookieConfig.name
val transportName = "cookies"
def cookiesMap: Map[String, HttpCookie] = headers
.collect { case `Set-Cookie`(cookie) => cookie.name -> cookie }.toMap
def getSession = cookiesMap.get(sessionCookieName).map(_.value)
def setSessionHeader(s: String) = Cookie(sessionCookieName, s)
def isSessionExpired = cookiesMap.get(sessionCookieName).flatMap(_.expires).contains(DateTime.MinValue)
def getRefreshToken = cookiesMap.get(refreshTokenCookieName).map(_.value)
def setRefreshTokenHeader(s: String) = Cookie(refreshTokenCookieName, s)
def isRefreshTokenExpired = cookiesMap.get(refreshTokenCookieName).flatMap(_.expires).contains(DateTime.MinValue)
def getSessionTransport = usingCookies
def setSessionTransport = usingCookies
}
object TestUsingHeaders extends TestUsingTransport {
val transportName = "headers"
def getSession = header(sessionConfig.sessionHeaderConfig.sendToClientHeaderName).map(_.value)
def setSessionHeader(s: String) = RawHeader(sessionConfig.sessionHeaderConfig.getFromClientHeaderName, s)
def isSessionExpired = getSession.contains("")
def getRefreshToken = header(sessionConfig.refreshTokenHeaderConfig.sendToClientHeaderName).map(_.value)
def setRefreshTokenHeader(s: String) = RawHeader(sessionConfig.refreshTokenHeaderConfig.getFromClientHeaderName, s)
def isRefreshTokenExpired = getRefreshToken.contains("")
def getSessionTransport = usingHeaders
def setSessionTransport = usingHeaders
}
}
示例2: 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))
}
}
示例3: CanonicalRequest
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.auth
import java.net.URLEncoder
import akka.http.scaladsl.model.Uri.{Path, Query}
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
// Documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
private[alpakka] case class CanonicalRequest(method: String,
uri: String,
queryString: String,
headerString: String,
signedHeaders: String,
hashedPayload: String) {
def canonicalString: String = s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
private[alpakka] object CanonicalRequest {
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == "x-amz-content-sha256").map(_.value).getOrElse("")
CanonicalRequest(
req.method.value,
pathEncode(req.uri.path),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String =
query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
private def uriEncode(str: String) = URLEncoder.encode(str, "utf-8")
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String =
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
private def pathEncode(path: Path): String =
if (path.isEmpty) "/"
else
path.toString().flatMap {
case ch if "!$&'()*+,;:=".contains(ch) => "%" + Integer.toHexString(ch.toInt).toUpperCase
case other => other.toString
}
}
示例4: CannedAcl
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.acl
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.headers.RawHeader
sealed abstract class CannedAcl(val value: String) {
def header: HttpHeader = RawHeader("x-amz-acl", value)
}
object CannedAcl {
case object AuthenticatedRead extends CannedAcl("authenticated-read")
case object AwsExecRead extends CannedAcl("aws-exec-read")
case object BucketOwnerFullControl extends CannedAcl("bucket-owner-full-control")
case object BucketOwnerRead extends CannedAcl("bucket-owner-read")
case object Private extends CannedAcl("private")
case object PublicRead extends CannedAcl("public-read")
case object PublicReadWrite extends CannedAcl("public-read-write")
}
示例5: ServerSideEncryption
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.alpakka.s3.acl.CannedAcl
import scala.collection.immutable
sealed abstract class ServerSideEncryption(algorithm: String,
kmsKeyId: Option[String] = None,
context: Option[String] = None) {
def headers: immutable.Seq[HttpHeader] = algorithm match {
case "AES256" => RawHeader("x-amz-server-side-encryption", "AES256") :: Nil
case "aws:kms" if kmsKeyId.isDefined && context.isEmpty =>
RawHeader("x-amz-server-side-encryption", "aws:kms") ::
RawHeader("x-amz-server-side-encryption-aws-kms-key-id", kmsKeyId.get) ::
Nil
case "aws:kms" if kmsKeyId.isDefined && context.isDefined =>
RawHeader("x-amz-server-side-encryption", "aws:kms") ::
RawHeader("x-amz-server-side-encryption-aws-kms-key-id", kmsKeyId.get) ::
RawHeader("x-amz-server-side-encryption-context", context.get) ::
Nil
case _ => throw new IllegalArgumentException("Unsupported encryption algorithm.")
}
}
object ServerSideEncryption {
case object AES256 extends ServerSideEncryption("AES256")
case class KMS(keyId: String, context: Option[String] = None)
extends ServerSideEncryption("aws:kms", Some(keyId), context)
}
示例6: CanonicalRequest
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.auth
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.http.scaladsl.model.Uri.{Path, Query}
import java.net.URLEncoder
case class CanonicalRequest(method: String, uri: String,
queryString: String,
headerString: String,
signedHeaders: String,
hashedPayload: String) {
def canonicalString: String = {
s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
}
object CanonicalRequest {
private[this] val content_sha256 = "x-amz-content-sha256"
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == content_sha256).map(_.value).getOrElse("")
CanonicalRequest(
req.method.value,
preprocessPath(req.uri.path),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String = {
query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
}
def uriEncode(str: String): String = URLEncoder.encode(str, "utf-8")
def preprocessPath(path: Path): String = {
uriEncode(path.toString()).replace(":", "%3A").replace("%2F", "/")
}
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String = {
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
}
}
示例7: 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)
)
)
}
}
示例8: CensoredRawHeader
//设置package包名称以及导入依赖的类
package akka.http
package scaladsl.model.headers
import akka.http.impl.util.{Rendering, _}
import akka.http.javadsl.{model => jm}
import akka.http.scaladsl.model.HttpHeader
final case class CensoredRawHeader(name: String,
value: String,
censorValue: String)
extends jm.headers.RawHeader {
def renderInRequests = true
def renderInResponses = true
val lowercaseName: String = name.toRootLowerCase
def render[R <: Rendering](r: R): r.type = r ~~ name ~~ ':' ~~ ' ' ~~ value
private def censoredRender[R <: Rendering](r: R): r.type =
r ~~ name ~~ ':' ~~ ' ' ~~ censorValue
override def toString(): String = censoredRender(new StringRendering).get
}
object CensoredRawHeader {
def unapply[H <: HttpHeader](customHeader: H): Option[(String, String)] =
Some(customHeader.name -> customHeader.value)
}
示例9: IdempotentRequestFailedRejection
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.{BasicDirectives, RouteDirectives}
import com.flipkart.connekt.commons.cache.{DistributedCacheManager, DistributedCacheType}
import com.flipkart.connekt.commons.core.Wrappers.Try_#
import com.flipkart.connekt.commons.metrics.Instrumented
import com.flipkart.metrics.Timed
import scala.util.{Success, Try}
case class IdempotentRequestFailedRejection(requestId: String) extends Rejection
trait IdempotentDirectives extends HeaderDirectives with Instrumented {
val X_REQUEST_ID = "x-request-id"
def idempotentRequest(appName: String): Directive0 = {
BasicDirectives.extract[Seq[HttpHeader]](_.request.headers) flatMap { headers =>
getHeader(X_REQUEST_ID, headers) match {
case Some(reqId) if reqId.nonEmpty =>
get(appName, reqId) match {
case Success(isIdempotentReq) if !isIdempotentReq =>
add(appName, reqId)
BasicDirectives.pass
case _ =>
RouteDirectives.reject(IdempotentRequestFailedRejection(reqId))
}
case _ =>
BasicDirectives.pass
}
}
}
@Timed("add")
private def add(appName: String, requestId: String): Try[Boolean] = Try_#(message = "IdempotentDirectives.add Failed") {
DistributedCacheManager.getCache(DistributedCacheType.IdempotentCheck).put[Boolean](cacheKey(appName, requestId), true)
}
@Timed("get")
private def get(appName: String, requestId: String): Try[Boolean] = Try_#(message = "IdempotentDirectives.get Failed") {
DistributedCacheManager.getCache(DistributedCacheType.IdempotentCheck).get[Boolean](cacheKey(appName, requestId)).getOrElse(false)
}
private def cacheKey(appName: String, requestId: String): String = appName.toLowerCase + "_" + requestId
}
示例10: TokenAuthenticationFailedRejection
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.AuthenticationFailedRejection.{CredentialsMissing, CredentialsRejected}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.{BasicDirectives, RouteDirectives}
import com.flipkart.connekt.commons.entities.AppUser
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.metrics.Instrumented
import com.flipkart.connekt.receptors.service.AuthenticationService
trait AuthenticationDirectives extends HeaderDirectives with Instrumented{
case class TokenAuthenticationFailedRejection(message: String) extends Rejection
val X_API_KEY_HEADER = "x-api-key"
val X_SECURE_CODE_HEADER = "x-secure-code"
val AUTHORIZATION_HEADER = "Authorization"
def authenticate: Directive1[AppUser] = {
BasicDirectives.extract[Seq[HttpHeader]](_.request.headers) flatMap { headers =>
getHeader(X_API_KEY_HEADER, headers).orElse{
//try basic auth if available
getHeader(AUTHORIZATION_HEADER, headers).filter(_.startsWith("Basic")).map { authHeader =>
BasicHttpCredentials(authHeader.substring(6).trim).password
}
} match {
case Some(apiKey) if apiKey.nonEmpty =>
AuthenticationService.authenticateKey(apiKey) match {
case Some(user) =>
meter(s"authenticate.${user.userId}").mark()
provide(user)
case None =>
ConnektLogger(LogFile.SERVICE).warn(s"authentication failure for apiKey: [$apiKey]")
RouteDirectives.reject(AuthenticationFailedRejection(CredentialsRejected, null))
}
case _ =>
RouteDirectives.reject(AuthenticationFailedRejection(CredentialsMissing, null))
}
}
}
def verifySecureCode(secretFragments: String*): Directive0 = {
BasicDirectives.pass
}
}
示例11: ResponseUtils
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.wire
import akka.http.scaladsl.marshalling._
import akka.http.scaladsl.model.HttpHeader
import com.flipkart.connekt.commons.iomodels.GenericResponse
import com.flipkart.connekt.receptors.wire.GenericJsonSupport._
import scala.collection.immutable.Seq
object ResponseUtils extends JsonToEntityMarshaller {
private val gm = m.getOrElseUpdate(classOf[GenericResponse], genericMarshaller[GenericResponse]).asInstanceOf[ToEntityMarshaller[GenericResponse]]
implicit class ResponseUtil(r: GenericResponse) {
def respondWithHeaders(headers: Seq[HttpHeader]): ToResponseMarshallable = {
val toResponseMarshaller = PredefinedToResponseMarshallers.fromToEntityMarshaller[GenericResponse](r.status, headers)(gm)
ToResponseMarshallable(r)(toResponseMarshaller)
}
def respond = ResponseUtils.respond(r)
}
implicit def respond(r: GenericResponse): ToResponseMarshallable = {
val toResponseMarshaller = PredefinedToResponseMarshallers.fromToEntityMarshaller[GenericResponse](r.status, Seq.empty[HttpHeader])(gm)
ToResponseMarshallable(r)(toResponseMarshaller)
}
}
示例12: Signer
//设置package包名称以及导入依赖的类
package com.bluelabs.akkaaws
import java.security.MessageDigest
import java.time.format.DateTimeFormatter
import java.time.{ZoneOffset, ZonedDateTime}
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.stream.Materializer
import scala.concurrent.{ExecutionContext, Future}
object Signer {
val dateFormatter = DateTimeFormatter.ofPattern("YYYYMMdd'T'HHmmssX")
def signedRequest(request: HttpRequest, key: SigningKey, date: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC))(implicit mat: Materializer): Future[HttpRequest] = {
implicit val ec: ExecutionContext = mat.executionContext
val hashedBody = request.entity.dataBytes.runWith(StreamUtils.digest()).map { case hash =>
Utils.encodeHex(hash.toArray)
}
hashedBody.map { case hb =>
val headersToAdd = Seq(RawHeader("x-amz-date", date.format(dateFormatter)), RawHeader("x-amz-content-sha256", hb)) ++ sessionHeader(key.credentials)
val reqWithHeaders = request.withHeaders(request.headers ++ headersToAdd)
val cr = CanonicalRequest.from(reqWithHeaders)
val authHeader = authorizationHeader("AWS4-HMAC-SHA256", key, date, cr)
reqWithHeaders.withHeaders(reqWithHeaders.headers ++ Seq(authHeader))
}
}
def sessionHeader(creds: AWSCredentials): Option[HttpHeader] = {
creds match {
case bc: BasicCredentials => None
case AWSSessionCredentials(_, _, sessionToken) => Some(RawHeader("X-Amz-Security-Token", sessionToken))
}
}
def authorizationHeader(algorithm: String, key: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): HttpHeader = {
RawHeader("Authorization", authorizationString(algorithm, key, requestDate, canonicalRequest))
}
def authorizationString(algorithm: String, key: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): String = {
s"$algorithm Credential=${key.credentialString}, SignedHeaders=${canonicalRequest.signedHeaders}, Signature=${key.hexEncodedSignature(stringToSign(algorithm, key, requestDate, canonicalRequest).getBytes())}"
}
def stringToSign(algorithm: String, signingKey: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): String = {
val digest = MessageDigest.getInstance("SHA-256")
val hashedRequest = Utils.encodeHex(digest.digest(canonicalRequest.canonicalString.getBytes()))
s"$algorithm\n${requestDate.format(dateFormatter)}\n${signingKey.scope.scopeString}\n$hashedRequest"
}
}
示例13: CanonicalRequest
//设置package包名称以及导入依赖的类
package com.bluelabs.akkaaws
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
// Documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
case class CanonicalRequest(method: String, uri: String, queryString: String, headerString: String, signedHeaders: String, hashedPayload: String) {
def canonicalString: String = {
s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
}
object CanonicalRequest {
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == "x-amz-content-sha256").map(_.value()).getOrElse("")
CanonicalRequest(req.method.value,
req.uri.path.toString(),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String = {
query.sortBy(_._1).map{case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
}
private def uriEncode(str: String) = {
java.net.URLEncoder.encode(str, "utf-8")
}
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped: Map[String, Seq[HttpHeader]] = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value().replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map{ case (k: String, v: String) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String = {
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
}
}
示例14: openEventStream
//设置package包名称以及导入依赖的类
package io.vamp.container_driver.marathon
import akka.NotUsed
import akka.actor.Actor
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpHeader.ParsingResult
import akka.http.scaladsl.model.{ HttpHeader, HttpRequest, Uri }
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import de.heikoseeberger.akkasse.{ EventStreamUnmarshalling, ServerSentEvent }
import io.vamp.common.akka.{ CommonActorLogging, ExecutionContextProvider }
import io.vamp.container_driver.ContainerChangeEvent
import org.json4s.native.JsonMethods._
import org.json4s.{ DefaultFormats, StringInput }
trait MarathonSse {
this: Actor with CommonActorLogging with ExecutionContextProvider ?
import EventStreamUnmarshalling._
private implicit val formats = DefaultFormats
def openEventStream(uri: Uri): Unit = {
implicit val actorMaterializer = ActorMaterializer()(context)
Source.single(HttpRequest(uri = "/v2/events", headers = List(HttpHeader.parse("Accept", "text/event-stream").asInstanceOf[ParsingResult.Ok].header)))
.via(Http()(context.system).outgoingConnection(uri.authority.host.address, uri.authority.port))
.mapAsync(1)(Unmarshal(_).to[Source[ServerSentEvent, NotUsed]])
.runForeach(_.runForeach { e ?
e.`type`.foreach(t ? e.data.foreach(d ? onEvent(t ? d)))
})
}
private def onEvent: PartialFunction[(String, String), Unit] = {
case (t, data) if t == "deployment_step_success" ?
val ids = (parse(StringInput(data), useBigDecimalForDouble = true) \ "plan" \ "steps" \\ "actions" \ "app").extract[List[String]]
ids.foreach { id ?
log.info(s"marathon deployment event for: '$id'")
self ! ContainerChangeEvent(id)
}
}
}
示例15: 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)
}
}