本文整理汇总了Scala中akka.http.scaladsl.model.headers.RawHeader类的典型用法代码示例。如果您正苦于以下问题:Scala RawHeader类的具体用法?Scala RawHeader怎么用?Scala RawHeader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RawHeader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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")
}
示例2: 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)
}
示例3: S3HeadersSpec
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.alpakka.s3.acl.CannedAcl
import org.scalatest.{FlatSpec, Matchers}
class S3HeadersSpec extends FlatSpec with Matchers {
"ServerSideEncryption" should "create well formed headers for AES-256 encryption" in {
ServerSideEncryption.AES256.headers should contain(RawHeader("x-amz-server-side-encryption", "AES256"))
}
it should "create well formed headers for aws:kms encryption" in {
val kms =
ServerSideEncryption.KMS("arn:aws:kms:my-region:my-account-id:key/my-key-id", Some("base-64-encoded-context"))
kms.headers should contain(RawHeader("x-amz-server-side-encryption", "aws:kms"))
kms.headers should contain(
RawHeader("x-amz-server-side-encryption-aws-kms-key-id", "arn:aws:kms:my-region:my-account-id:key/my-key-id")
)
kms.headers should contain(RawHeader("x-amz-server-side-encryption-context", "base-64-encoded-context"))
}
"StorageClass" should "create well formed headers for 'infrequent access'" in {
StorageClass.InfrequentAccess.header shouldEqual RawHeader("x-amz-storage-class", "STANDARD_IA")
}
"S3Headers" should "aggregate headers to one sequence" in {
val s3Headers = S3Headers(
cannedAcl = CannedAcl.PublicRead,
metaHeaders = MetaHeaders(Map("custom-meta" -> "custom")),
encryption = ServerSideEncryption.AES256,
customHeaders = Seq(RawHeader("Cache-Control", "no-cache")),
storageClass = StorageClass.ReducedRedundancy
)
s3Headers.headers.size shouldEqual 5
}
}
示例4: EchoBotSpec
//设置package包名称以及导入依赖的类
package bot.application
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.{MessageReplier, SignatureVerifier}
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}
import scala.concurrent.Future
class EchoBotSpec
extends FlatSpec
with Matchers
with ScalatestRouteTest
with EventsJsonSupport
with MockFactory {
def createBot(
sv: SignatureVerifier = mock[SignatureVerifier],
mr: MessageReplier = mock[MessageReplier]
): EchoLineBot = new EchoLineBot(
channelSecret = "channelSecret",
signatureVerifier = sv,
messageReplier = mr
)
it should "reply text message as reveived" in {
val signatureVerifier = stub[SignatureVerifier]
(signatureVerifier.isValid _).when(*, *, *) returns true
val messageReplier = stub[MessageReplier]
(messageReplier.replyMessage _).when(*, *).returns(Future.successful(Unit))
val bot = createBot(
signatureVerifier,
messageReplier
)
val event = MessageEvent(
replyToken = "replyToken",
timestamp = 0,
source = UserSource(id = "1"),
message = TextMessage(id = "2", text = "test message")
)
val body = Events(List(event))
val header = RawHeader("X-Line-Signature", "signature")
Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
status shouldBe StatusCodes.OK
responseAs[String] shouldBe "OK"
}
(signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
(messageReplier.replyMessage _).verify("replyToken", "test message").once
}
}
示例5: BaseLineBotSpec
//设置package包名称以及导入依赖的类
package bot.application
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.SignatureVerifier
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}
class BaseLineBotSpec
extends FlatSpec
with Matchers
with ScalatestRouteTest
with EventsJsonSupport
with MockFactory {
def createBot(
sv: SignatureVerifier = mock[SignatureVerifier],
rv:List[Event] => Unit
): BaseLineBot[Unit] = new BaseLineBot[Unit] {
override val channelSecret: String = "channelSecret"
override val signatureVerifier: SignatureVerifier = sv
override def receive(events: List[Event]): Unit = rv(events)
}
it should "Verify signature" in {
val signatureVerifier = stub[SignatureVerifier]
(signatureVerifier.isValid _).when(*, *, *) returns true
val receive = stubFunction[List[Event], Unit]
receive.when(*).returns(Unit)
val bot = createBot(
signatureVerifier,
receive
)
val event = MessageEvent(
replyToken = "replyToken",
timestamp = 0,
source = UserSource(id = "1"),
message = TextMessage(id = "2", text = "test message")
)
val body = Events(List(event))
val header = RawHeader("X-Line-Signature", "signature")
Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
status shouldBe StatusCodes.OK
responseAs[String] shouldBe "OK"
}
(signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
receive.verify(body.events).once
}
}
示例6: InstitutionsPathsSpec
//设置package包名称以及导入依赖的类
package hmda.api.http.institutions
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.Uri.Path
import hmda.api.http.InstitutionHttpApiSpec
import hmda.api.model._
import hmda.model.institution.Institution
import hmda.persistence.demo.DemoData
class InstitutionsPathsSpec extends InstitutionHttpApiSpec {
"Institutions Paths" must {
"return a list of institutions matching the 'CFPB-HMDA-Institutions' header" in {
val i1 = DemoData.testInstitutions.find(i => i.id == "1").get
val i2 = DemoData.testInstitutions.find(i => i.id == "2").get
val institutions: Set[Institution] = Set(i1, i2)
val institutionsWrapped = institutions.map(i => InstitutionWrapper(i.id, i.respondent.name))
Get("/institutions")
.addHeader(usernameHeader)
.addHeader(RawHeader("CFPB-HMDA-Institutions", "1,2")) ~> institutionsRoutes ~> check {
status mustBe StatusCodes.OK
responseAs[Institutions] mustBe Institutions(institutionsWrapped)
}
}
"return an institution by id" in {
getWithCfpbHeaders("/institutions/0") ~> institutionsRoutes ~> check {
status mustBe StatusCodes.OK
val institution = DemoData.testInstitutions.head
val institutionWrapped = InstitutionWrapper(institution.id, institution.respondent.name)
val filings = DemoData.testFilings.filter(f => f.institutionId == institution.id.toString)
responseAs[InstitutionDetail] mustBe InstitutionDetail(institutionWrapped, filings.reverse)
}
val path = Path("/institutions/xxxxx")
getWithCfpbHeaders(path.toString) ~> institutionsRoutes ~> check {
status mustBe StatusCodes.NotFound
responseAs[ErrorResponse] mustBe ErrorResponse(404, "Institution xxxxx not found", path)
}
}
}
}
示例7: GCMDispatcherPrepare
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.flows.dispatchers
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import com.flipkart.connekt.busybees.models.GCMRequestTracker
import com.flipkart.connekt.busybees.streams.errors.ConnektPNStageException
import com.flipkart.connekt.busybees.streams.flows.MapFlowStage
import com.flipkart.connekt.commons.entities.MobilePlatform
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.iomodels.GCMPayloadEnvelope
import com.flipkart.connekt.commons.iomodels.MessageStatus.InternalStatus
import com.flipkart.connekt.commons.services.KeyChainManager
import com.flipkart.connekt.commons.utils.StringUtils._
class GCMDispatcherPrepare extends MapFlowStage[GCMPayloadEnvelope, (HttpRequest, GCMRequestTracker)] {
override implicit val map: GCMPayloadEnvelope => List[(HttpRequest, GCMRequestTracker)] = message => {
try {
ConnektLogger(LogFile.PROCESSORS).debug("GCMDispatcherPrepare received message: {}", supplier(message.messageId))
ConnektLogger(LogFile.PROCESSORS).trace("GCMDispatcherPrepare received message: {}", supplier(message))
val requestEntity = HttpEntity(ContentTypes.`application/json`, message.gcmPayload.getJson)
val requestHeaders = scala.collection.immutable.Seq[HttpHeader](RawHeader("Authorization", "key=" + KeyChainManager.getGoogleCredential(message.appName).get.apiKey))
val httpRequest = HttpRequest(HttpMethods.POST, "/fcm/send", requestHeaders, requestEntity)
val requestTrace = GCMRequestTracker(message.messageId, message.clientId, message.deviceId, message.appName, message.contextId, message.meta)
List(httpRequest -> requestTrace)
} catch {
case e: Throwable =>
ConnektLogger(LogFile.PROCESSORS).error(s"GCMDispatcherPrepare failed with ${e.getMessage}", e)
throw new ConnektPNStageException(message.messageId, message.clientId, message.deviceId.toSet, InternalStatus.StageError, message.appName, MobilePlatform.ANDROID, message.contextId, message.meta, s"GCMDispatcherPrepare-${e.getMessage}", e)
}
}
}
示例8: WNSDispatcherPrepare
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.flows.dispatchers
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import com.flipkart.connekt.busybees.models.WNSRequestTracker
import com.flipkart.connekt.busybees.streams.errors.ConnektPNStageException
import com.flipkart.connekt.busybees.streams.flows.MapFlowStage
import com.flipkart.connekt.commons.entities.MobilePlatform
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.iomodels.MessageStatus.InternalStatus
import com.flipkart.connekt.commons.iomodels.WNSPayloadEnvelope
import com.flipkart.connekt.commons.services.WindowsOAuthService
import com.flipkart.connekt.commons.utils.StringUtils._
class WNSDispatcherPrepare extends MapFlowStage[WNSPayloadEnvelope, (HttpRequest, WNSRequestTracker)] {
override val map: WNSPayloadEnvelope => List[(HttpRequest, WNSRequestTracker)] = message => {
try {
// ConnektLogger(LogFile.PROCESSORS).debug(s"WNSDispatcher received message: ${message.messageId}")
// ConnektLogger(LogFile.PROCESSORS).trace(s"WNSDispatcher received message: $message")
val bearerToken = WindowsOAuthService.getToken(message.appName.trim.toLowerCase).map(_.token).getOrElse("NO_TOKEN_AVAILABLE")
val headers = scala.collection.immutable.Seq[HttpHeader](RawHeader("Authorization", "Bearer " + bearerToken),
RawHeader("X-WNS-Type", message.wnsPayload.getType), RawHeader("X-WNS-TTL", message.time_to_live.toString)
)
val payload = HttpEntity(message.wnsPayload.getContentType, message.wnsPayload.getBody)
val request = HttpRequest(HttpMethods.POST, message.token, headers, payload)
ConnektLogger(LogFile.PROCESSORS).trace(s"WNSDispatcher prepared http request: $request")
List((request, WNSRequestTracker(message.messageId, message.clientId, message.deviceId, message.appName, message.contextId, message, message.meta)))
} catch {
case e: Throwable =>
ConnektLogger(LogFile.PROCESSORS).error(s"WNSDispatcher:: onPush :: Error", e)
throw new ConnektPNStageException(message.messageId, message.clientId, Set(message.deviceId), InternalStatus.StageError, message.appName, MobilePlatform.WINDOWS, message.contextId, message.meta, s"WNSDispatcherPrepare-${e.getMessage}", e)
}
}
}
示例9: OpenWebDispatcherPrepare
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.flows.dispatchers
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import com.flipkart.connekt.busybees.models.OpenWebRequestTracker
import com.flipkart.connekt.busybees.streams.errors.ConnektPNStageException
import com.flipkart.connekt.busybees.streams.flows.MapFlowStage
import com.flipkart.connekt.commons.entities.MobilePlatform
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.iomodels.MessageStatus.InternalStatus
import com.flipkart.connekt.commons.iomodels.OpenWebStandardPayloadEnvelope
import com.flipkart.connekt.commons.utils.StringUtils._
class OpenWebDispatcherPrepare extends MapFlowStage[OpenWebStandardPayloadEnvelope, (HttpRequest, OpenWebRequestTracker)] {
override implicit val map: OpenWebStandardPayloadEnvelope => List[(HttpRequest, OpenWebRequestTracker)] = message => {
try {
// ConnektLogger(LogFile.PROCESSORS).debug(s"OpenWebDispatcherPrepare received message: ${message.messageId}")
// ConnektLogger(LogFile.PROCESSORS).trace(s"OpenWebDispatcherPrepare received message: ${message.toString}")
val requestEntity = HttpEntity(ContentTypes.`application/octet-stream`, message.payload.data)
val requestHeaders: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(message.headers.map { case (key, value) => RawHeader(key, value).asInstanceOf[HttpHeader] }.toList: _*)
val httpRequest = HttpRequest(HttpMethods.POST, message.providerUrl, requestHeaders, requestEntity)
val requestTrace = OpenWebRequestTracker(message.messageId, message.clientId, message.deviceId, message.appName, message.contextId, message.meta)
List(httpRequest -> requestTrace)
} catch {
case e: Throwable =>
ConnektLogger(LogFile.PROCESSORS).error(s"OpenWebDispatcherPrepare failed with ${e.getMessage}", e)
throw new ConnektPNStageException(message.messageId, message.clientId, Set(message.deviceId), InternalStatus.StageError, message.appName, MobilePlatform.OPENWEB, message.contextId, message.meta, s"OpenWebDispatcherPrepare-${e.getMessage}", e)
}
}
}
示例10: SmsProviderPrepare
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.flows.transformers
import java.util
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers.RawHeader
import com.flipkart.connekt.busybees.models.SmsRequestTracker
import com.flipkart.connekt.busybees.streams.errors.ConnektStageException
import com.flipkart.connekt.busybees.streams.flows.MapFlowStage
import com.flipkart.connekt.commons.entities.Channel
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile, ServiceFactory}
import com.flipkart.connekt.commons.iomodels.MessageStatus.InternalStatus
import com.flipkart.connekt.commons.iomodels.SmsPayloadEnvelope
import com.flipkart.connekt.commons.services.KeyChainManager
import com.flipkart.connekt.commons.utils.StringUtils.{JSONUnMarshallFunctions, _}
import scala.collection.JavaConverters._
class SmsProviderPrepare extends MapFlowStage[SmsPayloadEnvelope, (HttpRequest, SmsRequestTracker)] {
lazy implicit val stencilService = ServiceFactory.getStencilService
override val map: (SmsPayloadEnvelope) => List[(HttpRequest, SmsRequestTracker)] = smsPayloadEnvelope => profile("map") {
try {
val selectedProvider = smsPayloadEnvelope.provider.last
val credentials = KeyChainManager.getSimpleCredential(s"sms.${smsPayloadEnvelope.appName.toLowerCase}.$selectedProvider").get
val tracker = SmsRequestTracker(messageId = smsPayloadEnvelope.messageId,
clientId = smsPayloadEnvelope.clientId,
receivers = smsPayloadEnvelope.payload.receivers,
provider = selectedProvider,
appName = smsPayloadEnvelope.appName,
contextId = smsPayloadEnvelope.contextId,
request = smsPayloadEnvelope,
meta = smsPayloadEnvelope.meta)
val providerStencil = stencilService.getStencilsByName(s"ckt-sms-$selectedProvider").find(_.component.equalsIgnoreCase("prepare")).get
val result = stencilService.materialize(providerStencil, Map("data" -> smsPayloadEnvelope, "credentials" -> credentials, "tracker" -> tracker).getJsonNode)
val httpRequests = result.asInstanceOf[util.LinkedHashMap[HttpRequest, String]].asScala.map { case (request, updatedTracker) =>
(request.addHeader(RawHeader("x-message-id", smsPayloadEnvelope.messageId))
.addHeader(RawHeader("x-context-id", smsPayloadEnvelope.contextId))
.addHeader(RawHeader("x-client-id", smsPayloadEnvelope.clientId))
.addHeader(RawHeader("x-stencil-id", smsPayloadEnvelope.stencilId))
.addHeader(RawHeader("x-app-name", smsPayloadEnvelope.appName))
, updatedTracker.getObj[SmsRequestTracker])
}.toList
httpRequests
}
catch {
case e: Exception =>
ConnektLogger(LogFile.PROCESSORS).error(s"SMSChannelFormatter error for ${smsPayloadEnvelope.messageId}", e)
throw ConnektStageException(smsPayloadEnvelope.messageId, smsPayloadEnvelope.clientId, smsPayloadEnvelope.destinations, InternalStatus.StageError, smsPayloadEnvelope.appName, Channel.SMS, smsPayloadEnvelope.contextId, smsPayloadEnvelope.meta, "SMSChannelFormatter::".concat(e.getMessage), e)
}
}
}
示例11: EmailProviderPrepare
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.flows.transformers
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.Materializer
import com.flipkart.connekt.busybees.models.EmailRequestTracker
import com.flipkart.connekt.busybees.streams.flows.MapAsyncFlowStage
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile, ServiceFactory}
import com.flipkart.connekt.commons.iomodels.EmailPayloadEnvelope
import com.flipkart.connekt.commons.services.KeyChainManager
import com.flipkart.connekt.commons.utils.StringUtils._
import scala.concurrent.{ExecutionContext, Future}
class EmailProviderPrepare(parallelism: Int)(implicit ec: ExecutionContext) extends MapAsyncFlowStage[EmailPayloadEnvelope, (HttpRequest, EmailRequestTracker)](parallelism) {
private lazy implicit val stencilService = ServiceFactory.getStencilService
override val map: (EmailPayloadEnvelope) => Future[List[(HttpRequest, EmailRequestTracker)]] = emailPayloadEnvelope => Future(profile("map") {
val selectedProvider = emailPayloadEnvelope.provider.last
val credentials = KeyChainManager.getSimpleCredential(s"email.${emailPayloadEnvelope.appName.toLowerCase}.$selectedProvider").get
ConnektLogger(LogFile.PROCESSORS).debug(s"EmailProviderPrepare received message: ${emailPayloadEnvelope.messageId}")
//ConnektLogger(LogFile.PROCESSORS).trace(s"EmailProviderPrepare received message: {}", supplier(emailPayloadEnvelope))
val tracker = EmailRequestTracker(messageId = emailPayloadEnvelope.messageId,
clientId = emailPayloadEnvelope.clientId,
to = emailPayloadEnvelope.payload.to.map(_.address),
cc = emailPayloadEnvelope.payload.cc.map(_.address),
appName = emailPayloadEnvelope.appName,
contextId = emailPayloadEnvelope.contextId,
provider = selectedProvider,
request = emailPayloadEnvelope,
meta = emailPayloadEnvelope.meta)
val providerStencil = stencilService.getStencilsByName(s"ckt-email-$selectedProvider").find(_.component.equalsIgnoreCase("prepare")).get
val result = stencilService.materialize(providerStencil, Map("data" -> emailPayloadEnvelope, "credentials" -> credentials).getJsonNode)
val httpRequest = result.asInstanceOf[HttpRequest]
.addHeader(RawHeader("x-message-id", emailPayloadEnvelope.messageId))
.addHeader(RawHeader("x-context-id", emailPayloadEnvelope.contextId))
List(Tuple2(httpRequest, tracker))
})(ec)
}
示例12: BaseRouteTest
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.tests.routes
import java.util.concurrent.TimeUnit
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import com.flipkart.connekt.commons.entities.AppUser
import com.flipkart.connekt.receptors.routes.common.ClientRoute
import com.flipkart.connekt.receptors.routes.master.{RegistrationRoute, SendRoute}
import com.flipkart.connekt.receptors.routes.stencils.StencilsRoute
import org.scalatest.Matchers
import scala.concurrent.duration.FiniteDuration
abstract class BaseRouteTest extends BaseReceptorsTest with Matchers with ScalatestRouteTest {
implicit val routeTestTimeout = RouteTestTimeout(FiniteDuration.apply(30, TimeUnit.SECONDS))
var stencilRoute: server.Route = null
var registrationRoute: server.Route = null
var sendRoute: server.Route = null
var clientRoute: server.Route = null
implicit val am = system
val header = RawHeader("x-api-key", "sandbox-key-01")
implicit var user: AppUser = null
override def beforeAll() = {
super.beforeAll()
user = new AppUser("test", "test", "", "")
stencilRoute = new StencilsRoute().route
registrationRoute = new RegistrationRoute().route
sendRoute = new SendRoute().route
clientRoute = new ClientRoute().route
}
}
示例13: 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"
}
}
示例14: AkkaHttpLogBuilderSpec
//设置package包名称以及导入依赖的类
package io.neons.collector.infrastructure.log.builder
import java.util.UUID
import akka.http.scaladsl.model.MediaTypes.`image/gif`
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import io.neons.collector.application.akka.http.directive.TransparentPixel
import io.neons.collector.testcase.CollectorConfigTestCase
import org.scalatest.{FlatSpec, Matchers}
class AkkaHttpLogBuilderSpec extends FlatSpec with Matchers with CollectorConfigTestCase {
"Log builder" should "build log from http request and client ip" in {
val builder = new AkkaHttpLogBuilder()
builder.addClientIp("91.100.100.1")
builder.addHttpRequest(HttpRequest(
HttpMethods.GET,
uri = "/collect",
entity = HttpEntity(`image/gif`, TransparentPixel.pixel)
)
.withHeaders(
RawHeader("timeout-access", "test"),
RawHeader("cookie", "test"),
RawHeader("host", "localhost")
))
val result = builder.build
result.clientIp should be ("91.100.100.1")
result.headers.length should be (1)
result.cookies.length should be (0)
UUID.fromString(result.requestUuidL).toString should be (result.requestUuidL)
result.method should be ("GET")
result.uri should be ("/collect")
}
}
示例15: from
//设置package包名称以及导入依赖的类
package jp.co.dzl.example.akka.api.service
import akka.NotUsed
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse }
import akka.stream.scaladsl.Flow
trait GitHub {
def from(original: HttpRequest): Flow[HttpRequest, HttpRequest, NotUsed]
def send: Flow[HttpRequest, HttpResponse, NotUsed]
}
class GitHubImpl(
host: String,
port: Int,
timeout: Int,
httpClient: HttpClient
) extends GitHub {
def from(original: HttpRequest): Flow[HttpRequest, HttpRequest, NotUsed] = Flow[HttpRequest].map { req =>
val xForwardedHost = original.headers.find(_.is("host")).map(_.value()).getOrElse(s"$host:$port")
val modifiedHeader = original.addHeader(RawHeader("X-Forwarded-Host", xForwardedHost))
.headers
.filterNot(_.lowercaseName() == "host")
.filterNot(_.lowercaseName() == "timeout-access")
req.withHeaders(modifiedHeader)
}
def send: Flow[HttpRequest, HttpResponse, NotUsed] =
Flow[HttpRequest].via(httpClient.connectionHttps(host, port, timeout))
}