• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HttpHeader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.http.scaladsl.model.HttpHeader的典型用法代码示例。如果您正苦于以下问题:Scala HttpHeader类的具体用法?Scala HttpHeader怎么用?Scala HttpHeader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HttpHeader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:62,代码来源:MultipleTransportTest.scala


示例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))
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:58,代码来源:Controller.scala


示例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
      }

} 
开发者ID:akka,项目名称:alpakka,代码行数:54,代码来源:CanonicalRequest.scala


示例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")
} 
开发者ID:akka,项目名称:alpakka,代码行数:20,代码来源:CannedAcl.scala


示例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)
} 
开发者ID:akka,项目名称:alpakka,代码行数:33,代码来源:S3Headers.scala


示例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(";")
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:54,代码来源:CanonicalRequest.scala


示例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)
    )
    )
  }
} 
开发者ID:rmccray,项目名称:micro-service-seed,代码行数:62,代码来源:CorsSupport.scala


示例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)
} 
开发者ID:mdedetrich,项目名称:censored-raw-header,代码行数:26,代码来源:CensoredRawHeader.scala


示例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
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:48,代码来源:IdempotentDirectives.scala


示例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
    
  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:51,代码来源:AuthenticationDirectives.scala


示例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)
  }
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:27,代码来源:ResponseUtils.scala


示例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"
  }

} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:54,代码来源:Signer.scala


示例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(";")
  }

} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:44,代码来源:CanonicalRequest.scala


示例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)
      }
  }
} 
开发者ID:magneticio,项目名称:vamp-dcos,代码行数:43,代码来源:MarathonSse.scala


示例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)
  }
} 
开发者ID:chandu0101,项目名称:sri-sangria-example,代码行数:59,代码来源:CorsSupport.scala


示例16: oauthHeader

//设置package包名称以及导入依赖的类
package ch.becompany.http.oauth

import akka.http.scaladsl.model.headers.GenericHttpCredentials
import akka.http.scaladsl.model.{HttpHeader, HttpRequest, headers}
import akka.http.scaladsl.unmarshalling.Unmarshal
import ch.becompany.http.HttpClient
import com.hunorkovacs.koauth.domain.KoauthRequest
import com.hunorkovacs.koauth.service.consumer.DefaultConsumerService

import scala.concurrent.{ExecutionContext, Future}

trait OAuthSupport extends HttpClient {

  private val oauthHeaderName = "OAuth"

  val oauthConfig: OAuthConfig

  private lazy val consumer = new DefaultConsumerService(system.dispatcher)

  def oauthHeader(req: HttpRequest)(implicit ex: ExecutionContext): Future[HttpHeader] =
    for {
      body: Option[String] <-
        if (req.entity.isKnownEmpty()) Future(None)
        else Unmarshal(req.entity).to[String].map(Some(_))
      header <- oauthHeader(req, body)
    } yield header

  def oauthHeader(request: HttpRequest, body: Option[String])(implicit ex: ExecutionContext): Future[HttpHeader] =
    consumer.createOauthenticatedRequest(
      KoauthRequest(
        method = request.method.value,
        url = request.uri.toString,
        authorizationHeader = None,
        body = body
      ),
      oauthConfig.consumerKey,
      oauthConfig.consumerSecret,
      oauthConfig.accessToken,
      oauthConfig.accessTokenSecret
    ).
      map(_.header).
      map(header => headers.Authorization(GenericHttpCredentials(
        oauthHeaderName, header.substring(oauthHeaderName.length + 1))))

  abstract override def additionalHeaders(request: HttpRequest)(implicit ec: ExecutionContext): Future[Seq[HttpHeader]] = {
    val headersFuture = super.additionalHeaders(request)
    val oauthHeaderFuture = oauthHeader(request)
    for (headers <- headersFuture; oauthHeader <- oauthHeaderFuture)
      yield headers :+ oauthHeader
  }

} 
开发者ID:becompany,项目名称:akka-social-stream,代码行数:53,代码来源:OAuthSupport.scala


示例17: serviceSuccess

//设置package包名称以及导入依赖的类
package com.github.cupenya.auth

import akka.http.scaladsl.model.{ HttpHeader, StatusCode, StatusCodes }
import spray.json.JsonFormat

import scala.concurrent.{ ExecutionContext, Future }

package object service {

  def serviceSuccess[T: JsonFormat](t: T): ServiceResponse[T] =
    ServiceResponse(success = true, Some(t), None)
  def serviceNoSuccess[T: JsonFormat](message: String): ServiceResponse[T] =
    ServiceResponse(success = false, None, Some(ServiceResponseError(message, None)))
  def serviceUnauthorized[T: JsonFormat](message: String = "No authorization information supplied."): ServiceResponse[T] =
    ServiceResponse(success = false, None, Some(ServiceResponseError(message, None)))

  implicit def toServiceSuccess[T: JsonFormat](t: T): ServiceResponse[T] = serviceSuccess(t)

  def apiComplete[T: JsonFormat](response: Future[ServiceResponse[T]], statusCode: StatusCode)(implicit ec: ExecutionContext): Future[(StatusCode, List[HttpHeader], ServiceResponse[T])] = {
    response.map(apiComplete(_, statusCode = statusCode))
  }

  def apiComplete[T: JsonFormat](apiResponse: ServiceResponse[T], responseHeaders: List[HttpHeader] = Nil, statusCode: StatusCode = StatusCodes.OK): (StatusCode, List[HttpHeader], ServiceResponse[T]) = {
    (statusCode.intValue, responseHeaders, apiResponse)
  }
} 
开发者ID:cupenya,项目名称:auth-service,代码行数:27,代码来源:package.scala


示例18: call

//设置package包名称以及导入依赖的类
package xyz.joaovasques.sparkapi.api.standalone.interactors

import scala.concurrent.Future
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.HttpHeader.ParsingResult

trait Interactor[I,O] {

  val sparkApi: HttpRequest => Future[HttpResponse]
  val apiVersion: String
  val master: String

  protected val header =
    HttpHeader.parse("Content-Type", "application/json;charset=UTF-8") match {
      case ParsingResult.Ok(header, _)=> header
      case _ => ???
    }

  def call(request: I): Future[O]
} 
开发者ID:JoaoVasques,项目名称:spark-api,代码行数:22,代码来源:Interactor.scala


示例19: SubmitJobInteractor

//设置package包名称以及导入依赖的类
package xyz.joaovasques.sparkapi.api.standalone.interactors

import xyz.joaovasques.sparkapi.messages.SparkApiMessages._
import scala.concurrent.Future
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.actor.ActorSystem
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.model.{ HttpHeader, ResponseEntity }
import akka.http.scaladsl.model.HttpHeader.ParsingResult
import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.model.{ ContentTypes, HttpEntity }
import xyz.joaovasques.sparkapi.helpers._
import akka.stream.ActorMaterializer
import akka.http.scaladsl.model.StatusCodes._
import xyz.joaovasques.sparkapi.exceptions.SparkApiExceptions._
import xyz.joaovasques.sparkapi.actors.SparkActor._

class SubmitJobInteractor(val sparkApi: HttpRequest => Future[HttpResponse],
  val master: String, val apiVersion: String = "v1"
)(implicit system: ActorSystem) extends Interactor[SubmitJob, SparkJobSumissionResponse] with JsonHelpers {

  private val endpoint = s"/${apiVersion}/submissions/create"
  implicit val executionContext = system.dispatcher
  implicit val materializer = ActorMaterializer()

  private val unmarshaller: ResponseEntity => Future[SparkJobSumissionResponse] =
  { entity => Unmarshal(entity).to[SparkJobSumissionResponse] }

  private def handleSparkResponse(response: HttpResponse): Future[SparkJobSumissionResponse] =
    response.status match {
      case OK =>
        for(unmarshalledResponse <- unmarshaller(response.entity)) yield {
          if(unmarshalledResponse.success)
            unmarshalledResponse
          else
          throw JobSubmissionFailedException()
        }
      case otherStatus =>
        throw new SparkCommunicationException(otherStatus.intValue)
    }

  def call(request: SubmitJob): Future[SparkJobSumissionResponse] = {
    val httpRequest = RequestBuilding.Post(endpoint,
      HttpEntity(ContentTypes.`application/json`, generateSubmitJsonBody(request, master, request.envVars)))
      .addHeader(header)

    sparkApi(httpRequest) flatMap { handleSparkResponse(_) }
  }
} 
开发者ID:JoaoVasques,项目名称:spark-api,代码行数:50,代码来源:SubmitJobInteractor.scala


示例20: 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(originTo 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala LagomDevModeComponents类代码示例发布时间:2022-05-23
下一篇:
Scala ResourceHandler类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap