本文整理汇总了Scala中com.amazonaws.services.lambda.runtime.Context类的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Main
//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy
import java.net.URLDecoder
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.typesafe.scalalogging.LazyLogging
import scala.collection.JavaConverters._
class Main(context: Context) extends LazyLogging {
private def decodeS3Key(key: String): String = URLDecoder.decode(key.replace("+", " "), "utf-8")
def deploy(event: S3Event) = {
event.getRecords.asScala.foreach(
s3EventRecord => {
val bucket = s3EventRecord.getS3.getBucket.getName
val key = decodeS3Key(s3EventRecord.getS3.getObject.getKey)
val loc = StorageLocation(bucket, key)
logger.info(s"received event for $loc")
val parts = key.split('/')
require(parts.size > 1, s"cannot extract project name and version from $key")
val project = parts(0)
val version = parts(1)
val deployer = new Deploy(Project(loc, project, version))
logger.info(s"fetching $loc")
val archive = deployer.fetch {
is => {
logger.info("fetched")
logger.info("starting deployment to bintray")
deployer.upload(is).failed.toOption.foreach(throw _)
logger.info("deployment success")
}
}
}
)
}
}
示例2: Lambda
//设置package包名称以及导入依赖的类
package com.ovoenergy.lambda
import java.io.{Closeable, InputStreamReader}
import java.util.{Map => JMap}
import collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import com.amazonaws.services.s3.AmazonS3Client
import com.ovoenergy.lambda.client.{KafkaMetricsClient, LibratoClient}
import com.ovoenergy.lambda.domain.{ConsumerGroupMetricResponse, KafkaMetrics, PartitionData}
import com.squareup.okhttp.OkHttpClient
import com.typesafe.config.ConfigFactory
class Lambda extends RequestHandler[JMap[String, Object], Unit] with ConnectionHelpers{
val s3Client = new AmazonS3Client
override def handleRequest(event: JMap[String, Object], context: Context): Unit = {
val environment = context.getFunctionName.split('-').last
println(s"Hello, I'm a Lambda running in the $environment environment")
val config = using(s3Client.getObject("ovo-comms-platform-config", s"comms-burrow-polling-lambda/$environment/application.conf")){ s3Obj =>
using(new InputStreamReader(s3Obj.getObjectContent)){ configReader =>
ConfigFactory.parseReader(configReader)
}
}
val libratoEmail = config.getString("librato.api.email")
val libratoToken = config.getString("librato.api.token")
val libratoUrl = config.getString("librato.api.url")
val kafkaMetricsUrl = config.getString("kafka.metrics.url")
val kafkaConsumerGroups = config.getStringList("kafka.metrics.consumerGroups").asScala
val httpClient = new OkHttpClient()
val metricsClient = new KafkaMetricsClient(kafkaMetricsUrl, "local", kafkaConsumerGroups, httpClient)
val metrics = metricsClient.getMetrics.map(genKafkaMetrics)
using(new LibratoClient(libratoEmail, libratoToken, libratoUrl, environment)){ libratoClient =>
metrics.foreach { metric =>
libratoClient.addMetrics(metric)
}
libratoClient.submitMetrics()
}
}
private def genKafkaMetrics(response :ConsumerGroupMetricResponse): KafkaMetrics = {
val partitionData = response.status.partitions.map { partition =>
PartitionData(partition.partition, partition.end.lag)
}
KafkaMetrics(response.status.group, partitionData)
}
}
示例3: Hello
//设置package包名称以及导入依赖的类
package com.github.uryyyyyyy.aws.lambda.sqs.consumer
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider
import com.amazonaws.auth.profile.ProfileCredentialsProvider
import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.sqs.AmazonSQSAsyncClient
import com.amazonaws.services.sqs.model.{DeleteMessageRequest, ReceiveMessageRequest}
import scala.collection.JavaConversions._
object Hello {
val sqsEndPoint = "https://sqs.ap-northeast-1.amazonaws.com/522463962970/sampleQueue"
val credentials = new EnvironmentVariableCredentialsProvider()
val client = new AmazonSQSAsyncClient(credentials)
def main(args: Array[String]): Unit = {
println("Hello, world!")
}
def hello(count: Int, context: Context) = {
println("Hello World!!")
client.setRegion(Region.getRegion(Regions.AP_NORTHEAST_1))
val receiveMessageRequest = new ReceiveMessageRequest()
.withMaxNumberOfMessages(10)
.withWaitTimeSeconds(10)
.withQueueUrl(sqsEndPoint)
val result = client.receiveMessage(receiveMessageRequest)
val messages = result.getMessages
messages.foreach(m => {
println(s"count: ${m.getBody}")
val deleteMessageRequest = new DeleteMessageRequest()
.withQueueUrl(sqsEndPoint)
.withReceiptHandle(m.getReceiptHandle)
client.deleteMessage(deleteMessageRequest)
})
}
}
示例4: MySimpleHander
//设置package包名称以及导入依赖的类
package $package$
import com.amazonaws.services.lambda.runtime.Context
import scala.concurrent.Future
import io.circe.generic.auto._
import io.github.yeghishe.lambda._
// handler io.github.yeghishe.MySimpleHander::handler
// input "foo"
object MySimpleHander extends App {
def handler(name: String, context: Context): String = s"Hello \$name"
}
case class Name(name: String)
case class Greeting(message: String)
// handler io.github.yeghishe.MyHandler
// input {"name": "Yeghishe"}
class MyHandler extends Handler[Name, Greeting] {
def handler(name: Name, context: Context): Greeting = {
logger.info(s"Name is \$name")
Greeting(s"Hello \${name.name}")
}
}
示例5: AwsLambdaSample
//设置package包名称以及导入依赖的类
package org.nomadblacky.aws.lambda.samples
import com.amazonaws.services.lambda.runtime.Context
import scala.beans.BeanProperty
import scala.io.Source
class AwsLambdaSample {
def hello(request: Request, context: Context): Responce = {
Responce(Source.fromURL(request.url).mkString)
}
}
case class Request(@BeanProperty var url: String) {
def this() = this(url = "")
}
case class Responce(@BeanProperty var body: String) {
def this() = this(body = "")
}
示例6: Natertot
//设置package包名称以及导入依赖的类
package org.terrbear
import dispatch._, Defaults._
import scala.collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.Context
object Natertot {
def main(args: Array[String]): Unit = {
val notifier = new Notifier
val answer = notifier.notify(notifier.YES_PLZ)
println(answer())
}
}
class Notifier {
val PUSHOVER_KEY = "your-pushover-key"
val PUSHOVER_APP_KEY = "your-pushover-app-key"
val YES_PLZ = "Can you please get J out of bed?"
def lambda(input: java.io.InputStream, context: Context) : String = {
val logger = context.getLogger
logger.log("got a click!")
logger.log(notify(YES_PLZ)())
"all done"
}
def notify(msg: String): Future[String] = {
val request = url("https://api.pushover.net/1/messages.json").POST << Map("token" -> PUSHOVER_APP_KEY, "user" -> PUSHOVER_KEY, "message" -> msg)
Http(request OK as.String)
}
}
示例7: 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}"
}
}
示例8: LambdaMain
//设置package包名称以及导入依赖的类
package com.s3dropbox.lambda
import java.util.Locale
import com.amazonaws.services.kms.AWSKMSClientBuilder
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import com.amazonaws.services.s3.AmazonS3ClientBuilder
import com.amazonaws.services.s3.event.S3EventNotification.S3Entity
import com.amazonaws.services.s3.model.S3Object
import com.dropbox.core.DbxRequestConfig
import com.dropbox.core.v2.DbxClientV2
import com.dropbox.core.v2.files.WriteMode
import com.s3dropbox.lambda.LambdaMain._
import com.s3dropbox.lambda.ZipFileIterator.ZipFileEntry
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream
final class LambdaMain extends RequestHandler[S3Event, Unit] {
override def handleRequest(event: S3Event, context: Context): Unit = {
val kmsDecryption: KMSDecryption = new KMSDecryption(AWSKMSClientBuilder.defaultClient())
val dbxToken: String = kmsDecryption.decrypt(sys.env(EncryptedDbTokenEnvVar))
val config: DbxRequestConfig =
DbxRequestConfig
// the clientIdentifier might be the app key...
.newBuilder(context.getFunctionName)
.withAutoRetryEnabled()
.withUserLocaleFrom(Locale.US)
.build()
val dbxClient: DbxClientV2 = new DbxClientV2(config, dbxToken)
val s3entity: S3Entity = event.getRecords.get(event.getRecords.size - 1).getS3
val s3obj: S3Object = AmazonS3ClientBuilder
.defaultClient()
.getObject(s3entity.getBucket.getName, s3entity.getObject.getKey)
val zipFileIter: ZipFileIterator = new ZipFileIterator(s3obj.getObjectContent)
zipFileIter.foreach((zentry: ZipFileEntry) => {
println(s"Uploading [${zentry.filename}] to Dropbox")
dbxClient
.files()
.uploadBuilder(s"/${zentry.filename}")
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(new ByteInputStream(zentry.data, zentry.data.length))
})
zipFileIter.close()
}
}
private object LambdaMain {
var EncryptedDbTokenEnvVar: String = "EncryptedDropboxToken"
}
示例9: Handler
//设置package包名称以及导入依赖的类
package com.dyamah.hellosls
import com.amazonaws.auth.{AWSCredentialsProviderChain, EnvironmentVariableCredentialsProvider}
import com.amazonaws.regions.Regions
import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEventsClient
import com.amazonaws.services.cloudwatchevents.model._
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import scala.collection.JavaConversions._
object Handler {
def handleRequest(input: Request, context: Context): Response = {
val logger = context.getLogger
val message = ruleAndTarget match {
case (Some(rule), Some(target)) =>
logger.log(s"A pair of rule and target has been found: ${rule.getArn}-${target.getArn}")
val nextReq = new Request(id = input.id, count = input.count + 1)
target.setInput(nextReq.toJson)
cwClient.putTargets(new PutTargetsRequest().withRule(rule.getName).withTargets(target))
s"Next request is ${nextReq.toJson}"
case (Some(rule), _) =>
"A rule has been found, but no target of the rule"
case _ =>
"No rule has been found"
}
Response(message, input)
}
}
示例10: ImageResponse
//设置package包名称以及导入依赖的类
package demo
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.util.Base64
import com.amazonaws.services.lambda.runtime.Context
import io.github.jousby.lambda.http._
import io.github.jousby.lambda.http.model.{HttpRequest, HttpResponse}
import org.apache.commons.io.IOUtils
import scala.util.Try
class ImageResponse extends HttpRequestStreamHandler {
import ImageResponse._
def handleHttpRequest(request: HttpRequest, context: Context): Try[HttpResponse] = Try {
val encodedImage: String = encodeImage("add-128.png")
val response = HttpResponse(
body = Some(encodedImage),
isBase64Encoded = true)
context.getLogger.log(s"$response")
response
}
}
object ImageResponse {
def encodeImage(filename: String): String = {
// load image
val imageStream: InputStream = this.getClass.getClassLoader.getResourceAsStream(filename)
// to base64 string
val bytes = IOUtils.toByteArray(imageStream)
new String(Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8)
}
}
示例11: handleRequest
//设置package包名称以及导入依赖的类
package lambda
import com.amazonaws.services.lambda.runtime.{ Context, RequestHandler }
import domains.Hero
import infrastructures.{ HeroDBClient, SequenceDBClient }
trait AddHeroComponent extends RequestHandler[AddHeroRequest, Hero] {
val sequenceClient: SequenceDBClient
val heroClient: HeroDBClient
override def handleRequest(input: AddHeroRequest, context: Context): Hero = {
val seq = sequenceClient.sequence("heroId")
val newHero = Hero(seq, input.name)
heroClient.create(newHero)
newHero
}
}
class AddHeroController extends AddHeroComponent {
override val sequenceClient: SequenceDBClient = new SequenceDBClient()
override val heroClient: HeroDBClient = new HeroDBClient()
}
示例12: Main
//设置package包名称以及导入依赖的类
package com.iheart.lambda
import java.net.URLDecoder
import com.iheart.lambda.Utils._
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ning.NingWSClient
import scala.collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.amazonaws.services.lambda.runtime.Context
import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
class Main {
val wsClient = NingWSClient()
def handleEvent(event: S3Event, context: Context) = {
event.getRecords.asScala.foreach { record =>
val bucket = record.getS3.getBucket.getName
val key = URLDecoder.decode(record.getS3.getObject.getKey,"UTF-8")
println("Received key " + key)
sendToNewRelic(parseLogFile(bucket,key))
}
}
}
示例13: Main
//设置package包名称以及导入依赖的类
package org.nisshiee.chatwork_slack_relay
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import com.amazonaws.services.lambda.runtime.Context
import com.typesafe.config.ConfigFactory
import net.ceedubs.ficus.Ficus._
import org.nisshiee.chatwork_slack_relay.domain._
import org.nisshiee.chatwork_slack_relay.domain.chatwork._
class Main
extends MixinRelayService
with MixinAsakaiNotifyService {
lazy val config = ConfigFactory.load
lazy val targetRoomIds: List[Id[Room]] =
config.as[List[Long]]("chatwork.targetRoomIds").
map(Id.apply[Room])
lazy val asakaiRoomId: Id[Room] = Id[Room](config.as[Long]("chatwork.asakai.roomId"))
lazy val asakaiTargetUserName: String = config.as[String]("chatwork.asakai.targetUser")
def main(input: String, context: Context): String = {
val relayF = relayService.run(targetRoomIds)
val asakaiF = asakaiNotifyService.run(asakaiRoomId, asakaiTargetUserName)
val future = (relayF zip asakaiF).
map { _ => "done" }.
recover {
case t => t.toString
}
Await.result(future, Duration.Inf)
}
}
示例14: Handler
//设置package包名称以及导入依赖的类
package io.github.yeghishe.lambda
import java.io.{InputStream, OutputStream}
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration._
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import io.circe.{Decoder, Encoder}
import org.apache.log4j.Logger
abstract class Handler[T, R](implicit decoder: Decoder[T], encoder: Encoder[R]) extends RequestStreamHandler {
import Encoding._
protected implicit val logger = Logger.getLogger(this.getClass)
protected def handler(input: T, context: Context): R
def handleRequest(is: InputStream, os: OutputStream, context: Context): Unit =
in(is).flatMap(i => out(handler(i, context), os)).get
}
abstract class FutureHandler[T, R](d: Option[Duration] = None)(
implicit decoder: Decoder[T],
encoder: Encoder[R],
ec: ExecutionContext
) extends Handler[T, R] {
protected def handlerFuture(input: T, context: Context): Future[R]
protected def handler(input: T, context: Context): R = Await.result(
handlerFuture(input, context),
d.getOrElse(Duration(context.getRemainingTimeInMillis().toLong, MILLISECONDS))
)
}
示例15: MySimpleHander
//设置package包名称以及导入依赖的类
package io.github.yeghishe
import com.amazonaws.services.lambda.runtime.Context
import scala.concurrent.Future
import io.circe.generic.auto._
import io.github.yeghishe.lambda._
// handler io.github.yeghishe.MySimpleHander::handler
// input "foo"
object MySimpleHander extends App {
def handler(name: String, context: Context): String = s"Hello $name"
}
case class Name(name: String)
case class Greeting(message: String)
// handler io.github.yeghishe.MyHandler
// input {"name": "Yeghishe"}
class MyHandler extends Handler[Name, Greeting] {
def handler(name: Name, context: Context): Greeting = {
logger.info(s"Name is $name")
Greeting(s"Hello ${name.name}")
}
}