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

Scala Regions类代码示例

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

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



在下文中一共展示了Regions类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Access

//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy

import java.nio.file.{Files, StandardCopyOption}
import java.util.{Properties, UUID}

import awscala.s3.S3
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.model.GetObjectRequest
import hu.blackbelt.cd.bintray.VFS.FS

object Access {
  val bintray_organization = "bintray.organization"
  val bintray_user = "bintray.user"
  val bintray_apikey = "bintray.apikey"
  val aws_accessKeyId = "aws.accessKeyId"
  val aws_secretKey = "aws.secretKey"


  def collect = {
    implicit val s3 = S3()(com.amazonaws.regions.Region.getRegion(Regions.EU_CENTRAL_1))



    val destination = FS.getPath(s"/tmp/${UUID.randomUUID().toString}")
    Files.createDirectories(destination)
    val s3Object = s3.getObject(new GetObjectRequest("blackbelt-secrets", "bintray-deploy/access.properties"))
    Files.copy(s3Object.getObjectContent, destination, StandardCopyOption.REPLACE_EXISTING)

    import scala.collection.JavaConverters._
    val prop = new Properties()
    prop.load(Files.newInputStream(destination))
    prop.entrySet().asScala.foreach {
      (entry) => {
        sys.props += ((entry.getKey.asInstanceOf[String], entry.getValue.asInstanceOf[String]))
      }
    }
  }
} 
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:39,代码来源:Access.scala


示例2: client

//设置package包名称以及导入依赖的类
package org.zalando.react.nakadi.commit.handlers.aws

import com.amazonaws.regions.Regions
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import com.amazonaws.services.dynamodbv2.document.DynamoDB
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
import org.zalando.react.nakadi.properties.CommitProperties


trait Provider {
  def client: DynamoDB
  def leaseProperties: CommitProperties
}

class ClientProvider(override val leaseProperties: CommitProperties) extends Provider {

  private val credentialsProviderChain = new DefaultAWSCredentialsProviderChain()
  private val region = Regions.fromName(leaseProperties.awsCommitRegion)

  override val client: DynamoDB = {
    val c = new AmazonDynamoDBClient(credentialsProviderChain)
    c.configureRegion(region)
    new DynamoDB(c)
  }
} 
开发者ID:zalando-nakadi,项目名称:reactive-nakadi,代码行数:26,代码来源:ClientProvider.scala


示例3: AssetProcessing

//设置package包名称以及导入依赖的类
package templates

import aws.Interpreter.ErrorsOr
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import com.amazonaws.regions.{Region, Regions}
import com.ovoenergy.comms.model.{Channel, CommManifest}

object AssetProcessing {

  private val assetTemplateReferenceRegex = "(?:'|\")(?: *)(assets)(?:/[^(\"')]+)(?: *)(?:'|\")".r

  case class ProcessedFiles(templateFiles: List[UploadedTemplateFile], assetFiles: List[UploadedTemplateFile])

  def processAssets(region: Regions,
                    assetsS3Bucket: String,
                    commManifest: CommManifest,
                    uploadedFiles: List[UploadedTemplateFile]): ErrorsOr[ProcessedFiles] = {
    import cats.syntax.traverse._
    import cats.instances.list._
    val (assetFiles, nonAssetFiles) = uploadedFiles.partition(_.fileType == Asset)
    val processedTemplateFiles: Validated[NonEmptyList[String], List[UploadedTemplateFile]] = nonAssetFiles
      .traverseU(templateFile => {
        replaceAssetReferences(region, assetsS3Bucket, templateFile.channel, commManifest, templateFile.contents)
          .map(contents => templateFile.copy(contents = contents))
      })
    processedTemplateFiles.map(ProcessedFiles(_, assetFiles)).toEither
  }

  private def replaceAssetReferences(region: Regions,
                                     assetsS3Bucket: String,
                                     channel: Channel,
                                     commManifest: CommManifest,
                                     contents: Array[Byte]): ValidatedNel[String, Array[Byte]] = {
    def replaceReferences(s3Endpoint: String, contentsString: String) = {
      val replacementAssetsPath = s"$s3Endpoint/assets"
      assetTemplateReferenceRegex
        .replaceAllIn(contentsString, m => m.group(0).replaceFirst(m.group(1), replacementAssetsPath))
        .getBytes
    }
    determineS3Endpoint(region, assetsS3Bucket, channel, commManifest).map(replaceReferences(_, new String(contents)))
  }

  private def determineS3Endpoint(region: Regions,
                                  assetsS3Bucket: String,
                                  channel: Channel,
                                  commManifest: CommManifest): ValidatedNel[String, String] = {
    if (!Region.getRegion(region).isServiceSupported("s3")) {
      Invalid(NonEmptyList.of("S3 not supported in region selected"))
    } else if (!Region.getRegion(region).hasHttpsEndpoint("s3")) {
      Invalid(NonEmptyList.of("No https support for s3 in region selected"))
    } else {
      val s3ServiceEndpoint = Region.getRegion(region).getServiceEndpoint("s3")
      Valid(
        s"https://$s3ServiceEndpoint/$assetsS3Bucket/${commManifest.commType.toString.toLowerCase}/${commManifest.name}/${commManifest.version}/${channel.toString.toLowerCase}")
    }
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:59,代码来源:AssetProcessing.scala


示例4: KmsDecrypter

//设置package包名称以及导入依赖的类
package com.dwolla.awssdk.kms

import java.nio.ByteBuffer

import com.amazonaws.regions.Regions
import com.amazonaws.regions.Regions.US_WEST_2
import com.amazonaws.services.kms.model.DecryptRequest
import com.amazonaws.services.kms.{AWSKMSAsync, AWSKMSAsyncClientBuilder}
import com.dwolla.awssdk.kms.KmsDecrypter._
import com.dwolla.awssdk.utils.ScalaAsyncHandler.Implicits._

import scala.concurrent.{ExecutionContext, Future}

class KmsDecrypter(region: Regions = US_WEST_2) extends AutoCloseable {
  protected lazy val asyncClient: AWSKMSAsync = AWSKMSAsyncClientBuilder.standard().withRegion(US_WEST_2).build()

  def decrypt[A](transformer: Transform[A], cryptotext: A)(implicit ec: ExecutionContext): Future[Array[Byte]] = new DecryptRequest()
    .withCiphertextBlob(ByteBuffer.wrap(transformer(cryptotext)))
    .via(asyncClient.decryptAsync)
    .map(_.getPlaintext.array())

  def decrypt[A](transform: Transform[A], cryptotexts: (String, A)*)(implicit ec: ExecutionContext): Future[Map[String, Array[Byte]]] = {
    Future.sequence(cryptotexts.map {
      case (name, cryptotext) ? decrypt(transform, cryptotext).map(name ? _)
    }).map(Map(_: _*))
  }

  def decryptBase64(cryptotexts: (String, String)*)(implicit ec: ExecutionContext): Future[Map[String, Array[Byte]]] = decrypt(base64DecodingTransform, cryptotexts: _*)

  override def close(): Unit = asyncClient.shutdown()
}

object KmsDecrypter {
  type Transform[A] = A ? Array[Byte]

  val noopTransform: Transform[Array[Byte]] = (x: Array[Byte]) ? x
  val base64DecodingTransform: Transform[String] = javax.xml.bind.DatatypeConverter.parseBase64Binary
} 
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:39,代码来源:KmsDecrypter.scala


示例5: SQSConsumer

//设置package包名称以及导入依赖的类
package com.hivehome.kafka.connect.sqs

import javax.jms.{JMSException, MessageConsumer, Session}

import com.amazon.sqs.javamessaging.SQSConnectionFactory
import com.amazonaws.auth.{AWSCredentialsProviderChain, BasicAWSCredentials, DefaultAWSCredentialsProviderChain}
import com.amazonaws.internal.StaticCredentialsProvider
import com.amazonaws.regions.{Region, Regions}

object SQSConsumer {
  def apply(conf: Conf): MessageConsumer = {
    val chain = buildCredentialsProviderChain(conf)
    createSQSConsumer(conf, chain)
  }

  @throws(classOf[JMSException])
  private def createSQSConsumer(conf: Conf, chain: AWSCredentialsProviderChain): MessageConsumer = {
    val region = Regions.fromName(conf.awsRegion)
    val connectionFactory = SQSConnectionFactory.builder
      .withRegion(Region.getRegion(region))
      .withAWSCredentialsProvider(chain)
      .build

    val connection = connectionFactory.createConnection
    val session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE)
    val queue = session.createQueue(conf.queueName.get)
    val consumer = session.createConsumer(queue)
    connection.start()
    consumer
  }

  private def buildCredentialsProviderChain(conf: Conf): AWSCredentialsProviderChain = {
    (conf.awsKey, conf.awsSecret) match {
      case (Some(key), Some(secret)) =>
        val credentials = new BasicAWSCredentials(key, secret)
        new AWSCredentialsProviderChain(new StaticCredentialsProvider(credentials), new DefaultAWSCredentialsProviderChain)
      case _ => new DefaultAWSCredentialsProviderChain
    }
  }
} 
开发者ID:ConnectedHomes,项目名称:sqs-kafka-connect,代码行数:41,代码来源:SQSConsumer.scala


示例6: createQueue

//设置package包名称以及导入依赖的类
package com.hivehome.kafka.connect.sqs

import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.sqs.AmazonSQSClient
import com.amazonaws.services.sqs.model.{CreateQueueRequest, SendMessageRequest, SendMessageResult}
import org.scalacheck.Gen

import scala.collection.JavaConverters._

trait SQSSupport {
  val queueName = Gen.alphaStr
    .map(a => s"test-connect-${a.take(10)}")
    .sample.get
  var queueUrl: String = null

  val sqs = new AmazonSQSClient()
  sqs.setRegion(Region.getRegion(Regions.EU_WEST_1))

  def createQueue(): Unit = {
    val request = new CreateQueueRequest(queueName)
      .withAttributes(Map("VisibilityTimeout" -> "2").asJava)
    val result = sqs.createQueue(request)
    queueUrl = result.getQueueUrl
    println("Url for created Queue = " + queueUrl)
  }

  def deleteQueue(): Unit = {
    sqs.deleteQueue(queueUrl)
  }

  def sendMessage(msgText: String): SendMessageResult = {
    sqs.sendMessage(new SendMessageRequest()
      .withQueueUrl(queueUrl)
      .withMessageBody(msgText))
  }
} 
开发者ID:ConnectedHomes,项目名称:sqs-kafka-connect,代码行数:37,代码来源:SQSSupport.scala


示例7: AWSRegionNames

//设置package包名称以及导入依赖的类
package akka.persistence.s3

import com.amazonaws.regions.{ Regions, Region }
import com.typesafe.config.Config

private object AWSRegionNames {
  val GovCloud = Regions.GovCloud.getName
  val US_EAST_1 = Regions.US_EAST_1.getName
  val US_WEST_1 = Regions.US_WEST_1.getName
  val US_WEST_2 = Regions.US_WEST_2.getName
  val EU_WEST_1 = Regions.EU_WEST_1.getName
  val EU_CENTRAL_1 = Regions.EU_CENTRAL_1.getName
  val AP_SOUTHEAST_1 = Regions.AP_SOUTHEAST_1.getName
  val AP_SOUTHEAST_2 = Regions.AP_SOUTHEAST_2.getName
  val AP_NORTHEAST_1 = Regions.AP_NORTHEAST_1.getName
  val AP_NORTHEAST_2 = Regions.AP_NORTHEAST_2.getName
  val SA_EAST_1 = Regions.SA_EAST_1.getName
  val CN_NORTH_1 = Regions.CN_NORTH_1.getName
}

class S3ClientConfig(config: Config) {
  import AWSRegionNames._
  val awsKey = config getString "aws-access-key-id"
  val awsSecret = config getString "aws-secret-access-key"
  val awsUseDefaultCredentialsProviderChain = config getBoolean "aws-use-default-credentials-provider-chain"
  val region: Region = config getString "region" match {
    case GovCloud       => Region.getRegion(Regions.GovCloud)
    case US_EAST_1      => Region.getRegion(Regions.US_EAST_1)
    case US_WEST_1      => Region.getRegion(Regions.US_WEST_1)
    case US_WEST_2      => Region.getRegion(Regions.US_WEST_2)
    case EU_WEST_1      => Region.getRegion(Regions.EU_WEST_1)
    case EU_CENTRAL_1   => Region.getRegion(Regions.EU_CENTRAL_1)
    case AP_SOUTHEAST_1 => Region.getRegion(Regions.AP_SOUTHEAST_1)
    case AP_SOUTHEAST_2 => Region.getRegion(Regions.AP_SOUTHEAST_2)
    case AP_NORTHEAST_1 => Region.getRegion(Regions.AP_NORTHEAST_1)
    case AP_NORTHEAST_2 => Region.getRegion(Regions.AP_NORTHEAST_2)
    case SA_EAST_1      => Region.getRegion(Regions.SA_EAST_1)
    case CN_NORTH_1     => Region.getRegion(Regions.CN_NORTH_1)
  }
  val endpoint: Option[String] = {
    val e = config getString "endpoint"
    if (e == "default") None else Some(e)
  }
  object options {
    val pathStyleAccess = config getBoolean "options.path-style-access"
    val chunkedEncodingDisabled = config getBoolean "options.chunked-encoding-disabled"
  }
} 
开发者ID:TanUkkii007,项目名称:akka-persistence-s3,代码行数:49,代码来源:S3Config.scala


示例8: AkkaHttp

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

import java.nio.ByteBuffer

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.http.scaladsl.server._
import com.amazonaws.auth.{AWSCredentialsProvider, BasicAWSCredentials}
import com.amazonaws.internal.StaticCredentialsProvider
import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.kinesis.{AmazonKinesis, AmazonKinesisClient}
import com.amazonaws.services.kinesis.model.{PutRecordRequest, PutRecordResult}
import com.typesafe.config.ConfigFactory

object AkkaHttp extends App with Kinesis {
  implicit val system = ActorSystem()
  implicit val executor = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val config = ConfigFactory.load()
  val logger = Logging(system, getClass)

  import Directives._

  val route: Route =
    path("order" / IntNumber) { id =>
      complete(id.toString)
    } ~
    parameters('key, 'value) { (key, value) =>
      if(accessKeyId.isDefined && secretAccessKey.isDefined) {
        put(key, value)
      }
      complete(s"key: ${key}, value: ${value}")
    }

  val bindingFuture = Http().bindAndHandle(route, config.getString("http.interface"), config.getInt("http.port"))

  override def put(key: String, value: String): PutRecordResult = {
    val credentialsProvider: AWSCredentialsProvider = new StaticCredentialsProvider(new BasicAWSCredentials(accessKeyId.get, secretAccessKey.get))
    val kinesis: AmazonKinesis = new AmazonKinesisClient(credentialsProvider)
    kinesis.setRegion(Region.getRegion(Regions.AP_NORTHEAST_1))
    val request: PutRecordRequest = new PutRecordRequest()
    request.setStreamName(streamName)
    request.setData(ByteBuffer.wrap(value.getBytes("UTF-8")))
    request.setPartitionKey(key)
    val putRecord: PutRecordResult = kinesis.putRecord(request)
    println(s"key:${key} ,record:${value}, ${putRecord}")
    println("--------")
    kinesis.putRecord(request)
  }
} 
开发者ID:shigemk2,项目名称:my-akka-http-sample,代码行数:54,代码来源:AkkaHttp.scala


示例9: AWSClient

//设置package包名称以及导入依赖的类
package org.andrewconner.spot.cmdrs

import cats.Later
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.auth.AWSCredentials
import com.amazonaws.handlers.AsyncHandler
import com.amazonaws.regions.{ Regions, Region }
import com.amazonaws.services.ec2.AmazonEC2AsyncClient
import com.amazonaws.services.ec2.model.{ DescribeSpotPriceHistoryResult, DescribeSpotPriceHistoryRequest }
import org.andrewconner.spot.modules.AppShutdown
import org.joda.time.DateTime
import org.andrewconner.spot.core._
import play.api.inject.ApplicationLifecycle

import scala.concurrent.{ ExecutionContext, Future }
import scalaz.Memo
import scalaz.concurrent.Task
import scalaz.Scalaz._

class AWSClient(credentials: AWSCredentials, appShutdown: AppShutdown)(implicit val ec: ExecutionContext) {

  val clients = Regions.values().map { r =>
    r -> Lazily {
      val client = new AmazonEC2AsyncClient(credentials)
      client.setRegion(Region.getRegion(r))
      client
    }
  }.toMap

  appShutdown.onStopAsync {
    clients.foreach(_._2.foreach(_.shutdown()))
  }

  def fetchSpotPrices(region: Regions)(request: DescribeSpotPriceHistoryRequest, nextToken: String): Task[DescribeSpotPriceHistoryResult] = {
    Task.async[DescribeSpotPriceHistoryResult] { k =>
      clients(region).get.describeSpotPriceHistoryAsync(request.clone().withNextToken(Option(nextToken).getOrElse("")), asyncHandler[DescribeSpotPriceHistoryRequest, DescribeSpotPriceHistoryResult](k))
      ()
    }
  }

  private def asyncHandler[R <: AmazonWebServiceRequest, T](register: scalaz.\/[Throwable, T] => Unit): AsyncHandler[R, T] = {
    new AsyncHandler[R, T] {
      def onSuccess(req: R, res: T) = register(res.right)
      def onError(ex: Exception) = register(ex.left)
    }
  }

} 
开发者ID:andrewconner,项目名称:spotsy,代码行数:49,代码来源:AWSClient.scala


示例10: AWS

//设置package包名称以及导入依赖的类
package services.aws

import com.amazonaws.regions.Region
import com.amazonaws.regions.Regions
import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient
import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient
import com.amazonaws.services.ec2.AmazonEC2Client
import com.amazonaws.services.ec2.AmazonEC2Client
import com.amazonaws.services.ec2.model.DescribeTagsRequest
import com.amazonaws.services.ec2.model.DescribeTagsRequest
import com.amazonaws.services.ec2.model.Filter
import com.amazonaws.services.ec2.model.Filter
import com.amazonaws.util.EC2MetadataUtils
import com.amazonaws.util.EC2MetadataUtils
import scala.collection.JavaConverters._


object AWS {

  lazy val region = Region getRegion Regions.EU_WEST_1
  lazy val EC2Client = region.createClient(classOf[AmazonEC2Client], null, null)
  lazy val CloudWatch = region.createClient(classOf[AmazonCloudWatchAsyncClient], null, null)

}

trait AwsInstanceTags {
  lazy val instanceId = Option(EC2MetadataUtils.getInstanceId)

  def readTag(tagName: String) = {
    instanceId.flatMap { id =>
      val tagsResult = AWS.EC2Client.describeTags(
        new DescribeTagsRequest().withFilters(
          new Filter("resource-type").withValues("instance"),
          new Filter("resource-id").withValues(id),
          new Filter("key").withValues(tagName)
        )
      )
      tagsResult.getTags.asScala.find(_.getKey == tagName).map(_.getValue)
    }
  }
} 
开发者ID:guardian,项目名称:r2-archive-view,代码行数:43,代码来源:AWS.scala


示例11: AwsContextProvider

//设置package包名称以及导入依赖的类
package aws

import com.amazonaws.auth.{
  AWSCredentialsProviderChain,
  AWSStaticCredentialsProvider,
  BasicAWSCredentials,
  ContainerCredentialsProvider
}
import com.amazonaws.auth.profile.ProfileCredentialsProvider
import com.amazonaws.regions.Regions
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
import com.amazonaws.services.s3.AmazonS3Client
import play.api.Logger

object AwsContextProvider {

  def genContext(isRunningInCompose: Boolean, region: Regions): (AmazonDynamoDBClient, AmazonS3Client) = {
    if (isRunningInCompose) {
      Logger.info("Running in compose")
      System.setProperty("com.amazonaws.sdk.disableCertChecking", "true")
      val awsCreds                      = new AWSStaticCredentialsProvider(new BasicAWSCredentials("key", "secret"))
      val dClient: AmazonDynamoDBClient = new AmazonDynamoDBClient(awsCreds).withRegion(region)
      val s3Client: AmazonS3Client      = new AmazonS3Client(awsCreds).withRegion(region)
      dClient.setEndpoint(sys.env("LOCAL_DYNAMO"))
      (dClient, s3Client)
    } else {
      val awsCreds = new AWSCredentialsProviderChain(
        new ContainerCredentialsProvider(),
        new ProfileCredentialsProvider()
      )
      (new AmazonDynamoDBClient(awsCreds).withRegion(region), new AmazonS3Client(awsCreds).withRegion(region))
    }
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:35,代码来源:AwsContextProvider.scala


示例12: Config

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.e2e

import com.amazonaws.regions.Regions
import com.typesafe.config.ConfigFactory

object Config {

  private val config = ConfigFactory.load()
  private val targetEnv = config.getString("targetEnvironment")
  private val awsRegion = config.getString("aws.region")

  def getSecret(baseKey: String): String = {
    import sys.process._
    val key = s"${targetEnv.toLowerCase}.$baseKey"
    s"credstash -r $awsRegion get $key".!!.trim()
  }

  object AWS {
    val region = Regions.fromName(awsRegion)
  }

  object SNS {
    val legacyTopicV1 = getSecret("example_trigger.sns_topic.v1")
    val legacyTopicV2 = getSecret("example_trigger.sns_topic.v2")
    val aivenTopic    = getSecret("example_trigger.sns_topic.aiven.v3")
  }

  object Mailgun {
    val domain = getSecret("mailgun.domain")
    val apiKey = getSecret("mailgun.api_key")
  }

  object Twilio {
    val accountSid = getSecret("twilio.account_sid")
    val authToken  = getSecret("twilio.auth_token")
    val messageServiceSid = getSecret("twilio.service_sid")
  }

} 
开发者ID:ovotech,项目名称:comms-e2e-tests,代码行数:40,代码来源:Config.scala


示例13: verify

//设置package包名称以及导入依赖的类
package com.malliina.aws.cognito

import java.net.URI
import java.nio.charset.StandardCharsets

import com.amazonaws.regions.Regions
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.util.EntityUtils
import play.api.libs.json.Json

trait Verifier {
  def verify(token: RawToken): Either[JWTError, VerifiedToken]

  def verifyAccess(token: RawAccessToken): Either[JWTError, AccessToken] =
    verify(token).right.flatMap(JWT.access)

  def verifyId(token: RawIDToken): Either[JWTError, IdToken] =
    verify(token).right.flatMap(JWT.id)
}

class TokenVerifier(publicKeys: Seq[PubKey],
                    val expectedIssuer: Issuer) extends Verifier {
  override def verify(token: RawToken): Either[JWTError, VerifiedToken] =
    JWT.verifyToken(token, expectedIssuer, publicKeys)
}

object TokenVerifier {
  def forUserPool(region: Regions, userPool: UserPool): TokenVerifier = {
    val keySetUri = jwtSet(region, userPool)
    val keys = Json.parse(fetch(keySetUri)).as[JWTKeys].keys map { key =>
      PubKey(key.kid, Keys.publicKey(key))
    }
    val expectedIssuer = Issuer(s"https://cognito-idp.${region.getName}.amazonaws.com/$userPool")
    new TokenVerifier(keys, expectedIssuer)
  }

  protected def jwtSet(region: Regions, userPool: UserPool): URI =
    new URI(s"https://cognito-idp.${region.getName}.amazonaws.com/$userPool/.well-known/jwks.json")

  def fetch(uri: URI): String = {
    val http = HttpClients.createDefault()
    try {
      fetch(http, uri)
    } finally {
      http.close()
    }
  }

  protected def fetch(http: CloseableHttpClient, uri: URI): String = {
    val req = new HttpGet(uri)
    val res = http execute req
    try {
      val entity = res.getEntity
      EntityUtils.toString(entity, StandardCharsets.UTF_8)
    } finally {
      res.close()
    }
  }
} 
开发者ID:malliina,项目名称:cognito-utils,代码行数:61,代码来源:TokenVerifier.scala


示例14: MyAmazonSES

//设置package包名称以及导入依赖的类
package utils

import com.amazonaws.auth.AWSCredentials
import com.amazonaws.regions.Regions
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient
import com.amazonaws.services.simpleemail.model._

class MyAmazonSES(credentials: AWSCredentials, region: Regions) {
  lazy val client = new AmazonSimpleEmailServiceClient(credentials)
  client.withRegion(region)

  def send(mail: Mail): Unit = {
    val req = new SendEmailRequest()
      .withSource(mail.from)
      .withDestination(mail.dest)
      .withMessage(mail.message)
    client.sendEmail(req)
  }
}

case class Mail(dest: Destination, subject: Content, body: Body, from: String) {
  def message: Message = new Message().withSubject(subject).withBody(body)
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:24,代码来源:MyAmazonSES.scala


示例15: Config

//设置package包名称以及导入依赖的类
package utils

import com.amazonaws.auth.{AWSCredentials, BasicAWSCredentials}
import com.amazonaws.regions.Regions
import play.api.Configuration

class Config(orig: Configuration) {
  lazy val googleMapsKey: Option[String] = orig.getString("google.maps.key")
  lazy val amazon = orig.getConfig("amazon").map(new AmazonConfig(_))
  lazy val mail: Option[String] = orig.getString("management.mail")
}

class AmazonConfig(config: Configuration) {
  val regionRaw: Option[String] = config.getString("region")
  val access: Option[String] = config.getString("access_key")
  val secret: Option[String] = config.getString("secret_key")

  lazy val credentials: Option[AWSCredentials] = for {
    a <- access
    s <- secret
  } yield new BasicAWSCredentials(a, s)

  lazy val region: Option[Regions] = regionRaw.map(Regions.fromName)

  def ses: Option[MyAmazonSES] = for {
    c <- credentials
    r <- region
  } yield new MyAmazonSES(c, r)
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:30,代码来源:Config.scala


示例16: LoadHitResultQueue

//设置package包名称以及导入依赖的类
package vitomatic

import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.sqs.AmazonSQSClient
import com.amazonaws.services.sqs.model.{CreateQueueRequest, GetQueueUrlRequest}
import com.fasterxml.jackson.databind.ObjectMapper
import com.typesafe.config.ConfigFactory
import vitomatic.model.SingleHitResult
import scala.util.Try


class LoadHitResultQueue {

  val objectMapper = new ObjectMapper()

  val config = ConfigFactory.load()

  lazy val awsCredentials = new BasicAWSCredentials(
    config.getString("aws.accessKeyId"),
    config.getString("aws.secretAccessKey"))

  val queueName = config.getString("aws.sqs.queueName")

  val sqs = new AmazonSQSClient(awsCredentials)
  sqs.setRegion(Region.getRegion(Regions.valueOf(config.getString("aws.region"))))

  def enqueue(data: SingleHitResult, ctx: Context): String = {
    val clientQueueName = s"${queueName}_${data.getClientId}"
    Try(sqs.createQueue(new CreateQueueRequest(clientQueueName)))
    val queueUrl = sqs.getQueueUrl(new GetQueueUrlRequest(clientQueueName)).getQueueUrl
    val json = objectMapper.writeValueAsString(data)
    val messageId = sqs.sendMessage(queueUrl, json).getMessageId
    messageId
  }

  def echo(data: String): String = {
    s"Hello ${data}"
  }

} 
开发者ID:vit-o-matic,项目名称:load-test-lambda,代码行数:43,代码来源:SQSProxyLambda.scala


示例17: AwsProvider

//设置package包名称以及导入依赖的类
package com.ovoenergy.orchestration.aws

import com.amazonaws.auth._
import com.amazonaws.auth.profile.ProfileCredentialsProvider
import com.amazonaws.regions.Regions
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
import com.ovoenergy.comms.templates.TemplatesContext
import org.slf4j.LoggerFactory

object AwsProvider {

  private val log = LoggerFactory.getLogger("AwsClientProvider")

  def dynamoClient(isRunningInLocalDocker: Boolean, region: Regions): AmazonDynamoDBClient = {
    if (isRunningInLocalDocker) {
      log.warn("Running in local docker")
      System.setProperty("com.amazonaws.sdk.disableCertChecking", "true")
      val awsCreds                           = getCreds(isRunningInLocalDocker, region)
      val dynamoClient: AmazonDynamoDBClient = new AmazonDynamoDBClient(awsCreds).withRegion(region)
      dynamoClient.setEndpoint(sys.env("LOCAL_DYNAMO"))
      dynamoClient
    } else {
      val awsCreds = getCreds(isRunningInLocalDocker, region)
      new AmazonDynamoDBClient(awsCreds).withRegion(region)
    }
  }

  def templatesContext(isRunningInLocalDocker: Boolean, region: Regions) = {
    val awsCreds = getCreds(isRunningInLocalDocker, region)
    TemplatesContext.cachingContext(awsCreds)
  }

  private def getCreds(isRunningInLocalDocker: Boolean, region: Regions): AWSCredentialsProvider = {
    if (isRunningInLocalDocker)
      new AWSStaticCredentialsProvider(new BasicAWSCredentials("key", "secret"))
    else
      new AWSCredentialsProviderChain(
        new ContainerCredentialsProvider(),
        new ProfileCredentialsProvider()
      )
  }
} 
开发者ID:ovotech,项目名称:comms-orchestration,代码行数:43,代码来源:AwsProvider.scala


示例18: ElasticLoadBalancingAwareDowningSettings

//设置package包名称以及导入依赖的类
package tanukki.akka.cluster.autodown.aws.elasticloadbalancing

import akka.actor.ActorSystem
import com.amazonaws.regions.{Regions, Region}

case class ElasticLoadBalancingAwareDowningSettings(region: Region, loadBalancerName: String) {
  require(loadBalancerName.nonEmpty, "loadBalancerName should not be empty")
}

object ElasticLoadBalancingAwareDowningSettings {
  def apply(system: ActorSystem): ElasticLoadBalancingAwareDowningSettings = {
    val c = system.settings.config
    ElasticLoadBalancingAwareDowningSettings(
      Region.getRegion(Regions.fromName(c.getString("custom-downing.aws.elasticloadbalancing.leader-auto-downing-roles-if-unhealthy.region"))),
      c.getString("custom-downing.aws.elasticloadbalancing.leader-auto-downing-roles-if-unhealthy.loadbalancer-name")
    )
  }
} 
开发者ID:TanUkkii007,项目名称:aws-aware-akka-cluster-custom-downing,代码行数:19,代码来源:ElasticLoadBalancingAwareDowningSettings.scala


示例19: ApplicationStartupS3DAO

//设置package包名称以及导入依赖的类
package daos

import java.io.{File, FileOutputStream, InputStream}
import javax.inject.{Inject, Singleton}

import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.{AmazonS3, AmazonS3ClientBuilder}
import org.apache.commons.io.IOUtils
import play.api.Configuration



@Singleton
class ApplicationStartupS3DAO @Inject()(config: Configuration) {
  private val s3: AmazonS3 = AmazonS3ClientBuilder.standard()
      .withCredentials(new DefaultAWSCredentialsProviderChain())
      .withRegion(Regions.EU_WEST_2)
      .build()
  private val bucketName = config.underlying.getString("s3-static")

  def downloadImageToTempFile(key: String): File = {
    val inputStream: InputStream = s3.getObject(bucketName, key).getObjectContent
    val tempFile = File.createTempFile(s"temp-file-$key", ".tmp")
    tempFile.deleteOnExit()
    val out = new FileOutputStream(tempFile)
    IOUtils.copy(inputStream, out)
    inputStream.close()
    out.close()
    tempFile
  }
} 
开发者ID:muhsinali,项目名称:picture-gallery-scala,代码行数:33,代码来源:ApplicationStartupS3DAO.scala


示例20: MyAmazonSES

//设置package包名称以及导入依赖的类
package utils

import com.amazonaws.regions.Regions
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder
import com.amazonaws.services.simpleemail.model._

class MyAmazonSES(region: Regions) {
  lazy val client = AmazonSimpleEmailServiceClientBuilder.standard()
      .withRegion(region)
      .build()

  def send(mail: Mail): Unit = {
    val req = new SendEmailRequest()
      .withSource(mail.from)
      .withDestination(mail.dest)
      .withMessage(mail.message)
    client.sendEmail(req)
  }
}

case class Mail(dest: Destination, subject: Content, body: Body, from: String) {
  def message: Message = new Message().withSubject(subject).withBody(body)
} 
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:24,代码来源:MyAmazonSES.scala



注:本文中的com.amazonaws.regions.Regions类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala DateType类代码示例发布时间:2022-05-23
下一篇:
Scala Stop类代码示例发布时间: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