本文整理汇总了Scala中com.amazonaws.services.lambda.runtime.Context类的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
}
}
}
)
}
}
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:46,代码来源:Main.scala
示例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)
}
}
开发者ID:ovotech,项目名称:comms-burrow-polling-lambda,代码行数:52,代码来源:Lambda.scala
示例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)
})
}
}
开发者ID:uryyyyyyy,项目名称:awsLambdaSample,代码行数:43,代码来源:Hello.scala
示例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}")
}
}
开发者ID:yeghishe,项目名称:scala-aws-lambda-seed.g8,代码行数:26,代码来源:Main.scala
示例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 = "")
}
开发者ID:NomadBlacky,项目名称:aws-lambda-sample-with-scala,代码行数:22,代码来源:AwsLambdaSample.scala
示例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)
}
}
开发者ID:terrbear,项目名称:iot-pinger,代码行数:34,代码来源:Notifier.scala
示例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}"
}
}
开发者ID:vit-o-matic,项目名称:load-test-lambda,代码行数:43,代码来源:SQSProxyLambda.scala
示例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"
}
开发者ID:ErrorsAndGlitches,项目名称:S3DropboxLambda,代码行数:56,代码来源:LambdaMain.scala
示例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)
}
}
开发者ID:dyamah,项目名称:sls-sbt,代码行数:35,代码来源:Handler.scala
示例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)
}
}
开发者ID:jousby,项目名称:scala-aws-lambda,代码行数:41,代码来源:ImageResponse.scala
示例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()
}
开发者ID:cm-wada-yusuke,项目名称:lambda-hero,代码行数:25,代码来源:AddHeroController.scala
示例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))
}
}
}
开发者ID:denen99,项目名称:fastly-lambda,代码行数:29,代码来源:Main.scala
示例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)
}
}
开发者ID:nisshiee,项目名称:chatwork-slack-relay,代码行数:34,代码来源:Main.scala
示例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))
)
}
开发者ID:yeghishe,项目名称:scala-aws-lambda-utils,代码行数:33,代码来源:Handler.scala
示例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}")
}
}
开发者ID:TimSoethout,项目名称:scala-lambda,代码行数:26,代码来源:Main.scala
示例16: S3
//设置package包名称以及导入依赖的类
package com.sample.lambda
import java.io.File
import java.nio.file.{Files, StandardCopyOption}
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{CannedAccessControlList, ObjectMetadata, PutObjectRequest}
import com.typesafe.config.ConfigFactory
import org.im4java.core.{ConvertCmd, IMOperation}
class S3 {
def handler(event: S3Event, context: Context): String = {
val config = ConfigFactory.load()
val record = event.getRecords.get(0)
val bucket = record.getS3.getBucket.getName
val key = record.getS3.getObject.getKey
val pattern = """(.+)\.(.+)""".r
val patternThumbnail = """(.+)_thumbnail\.(.+)""".r
key match {
case patternThumbnail(name, format) => {
}
case pattern(name, format) => {
val client = new AmazonS3Client()
val s3Object = client.getObject(bucket, key)
val inMetadata = s3Object.getObjectMetadata
val input = s3Object.getObjectContent
val inputFile = File.createTempFile("s3handler", "input")
Files.copy(input, inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
val resizedImage = File.createTempFile("s3handler", "resizedImage")
val op = new IMOperation()
op.addImage(inputFile.getAbsolutePath)
op.resize(config.getInt("resized.width"), config.getInt("resized.height"))
op.addImage(resizedImage.getAbsolutePath)
val converter = new ConvertCmd()
converter.run(op)
val resizedKey = name + "_thumbnail." + format
val putObjectRequest = new PutObjectRequest(bucket, resizedKey, resizedImage)
val resizedImageMetadata = new ObjectMetadata()
resizedImageMetadata.setContentType(inMetadata.getContentType)
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead).withMetadata(resizedImageMetadata)
client.putObject(putObjectRequest)
}
}
key
}
}
开发者ID:phji,项目名称:lambda-resize-s3-image,代码行数:61,代码来源:S3.scala
示例17: Handler
//设置package包名称以及导入依赖的类
package org.uncompiled.alexa
import java.text.SimpleDateFormat
import java.util.{Calendar,UUID}
import scala.xml.XML
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
class Handler extends RequestHandler[Request, Response] {
type AffectedLines = Set[String]
def handleRequest(input: Request, context: Context): Response = {
val xml = XML.load("http://www.metroalerts.info/rss.aspx?rs")
val incidents = (xml \\ "item")
val affectedLines : AffectedLines = incidents.map(i => (i \\ "title").text).toSet
def affectedLinesText() : String = {
val ALL_LINES = 6 // Metro currently has 6 rail lines
affectedLines.size match {
case ALL_LINES => "Oh my. All lines are currently impacted by delays."
case 0 => "Surprise! There are no incidents on the Metro rail system."
case 1 => s"There are incidents on the ${affectedLines.mkString} line."
case _ => s"There are incidents on the ${speak(affectedLines)} lines."
}
}
def transformWMATAShorthand(input: String): String = {
// TODO: This is probably fucked up.
// https://imgs.xkcd.com/comics/perl_problems.png
input
.replaceAll("w/add'l", "with additional")
.replaceAll("btwn", "between")
.replaceAll("Pl", "Place")
// WMATA uses 9A instead of 9AM and this sounds weird
.replaceAll("""(\d)(A|P)""", "$1 $2M ")
// Finally, remove slashes because Alexa will read them
.replaceAll("/", " ")
}
}
开发者ID:uncompiled,项目名称:alexa-metro-status,代码行数:41,代码来源:Handler.scala
示例18: StockTradeAPI
//设置package包名称以及导入依赖的类
import java.io.{InputStream, OutputStream}
import com.amazonaws.regions.Regions
import com.amazonaws.services.dynamodbv2.model.{DescribeStreamRequest, GetRecordsRequest, GetShardIteratorRequest, ShardIteratorType}
import com.amazonaws.services.dynamodbv2.{AmazonDynamoDB, AmazonDynamoDBClient, AmazonDynamoDBStreams, AmazonDynamoDBStreamsClient}
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import com.google.gson.Gson
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.io.Source
class StockTradeAPI extends RequestStreamHandler {
private val STATS_SOURCE_TABLE: String = "StockTradeStats"
def handleRequest(input: InputStream, output: OutputStream, context: Context) = {
Source.fromInputStream(input, "utf-8").getLines().foreach(println)
lazy val db: AmazonDynamoDB = new AmazonDynamoDBClient().withRegion(Regions.EU_WEST_1)
lazy val dbs: AmazonDynamoDBStreams = new AmazonDynamoDBStreamsClient().withRegion(Regions.EU_WEST_1)
lazy val tab = db.describeTable(STATS_SOURCE_TABLE).getTable
val records = dbs.describeStream(
new DescribeStreamRequest().withStreamArn(tab.getLatestStreamArn)
).getStreamDescription.getShards.toList.flatMap { shard =>
println(s"processing ${shard.getShardId}")
dbs.getRecords(
new GetRecordsRequest()
.withShardIterator(
dbs.getShardIterator(
new GetShardIteratorRequest()
.withStreamArn(tab.getLatestStreamArn)
.withShardIteratorType(ShardIteratorType.TRIM_HORIZON)
.withShardId(shard.getShardId)
).getShardIterator
).withLimit(100)
).getRecords.toList.map { record =>
println(s"adding record ${record.getDynamodb.getSequenceNumber}")
record.getDynamodb.getNewImage.values().toSeq.map{v =>
println(s"extracting value $v")
Option(v.getN).getOrElse(v.getS)
}.asJavaCollection
}.asJavaCollection
}.asJavaCollection
println(s"compute $records")
output.write(new Gson().toJson(records).getBytes())
}
}
开发者ID:mugglmenzel,项目名称:StockTradeFetcherLambda,代码行数:56,代码来源:StockTradeAPI.scala
示例19: HelloLambda
//设置package包名称以及导入依赖的类
package com.virtuslab.lambda.hello
import java.io.{InputStream, OutputStream, OutputStreamWriter}
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import com.virtuslab.lambda.hello.HelloLambda.formats
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
object HelloLambda {
implicit val formats = Serialization.formats(NoTypeHints)
}
class HelloLambda extends RequestStreamHandler {
override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
context.getLogger.log(s"Log: ${context.getRemainingTimeInMillis}")
println(s"Test ${context.getAwsRequestId}")
try {
val writer = new OutputStreamWriter(output, "UTF-8")
writer.write(write(s"Fetched with ID: ${context.getAwsRequestId}"))
writer.flush()
writer.close()
} catch {
case e: Throwable => context.getLogger.log(s"exception? -> ${e.getCause}")
}
}
}
开发者ID:pdolega,项目名称:lambda-samples,代码行数:31,代码来源:HelloLambda.scala
示例20: Response
//设置package包名称以及导入依赖的类
package com.virtuslab.lambda.http
import java.io.{InputStream, OutputStream, OutputStreamWriter}
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
import HttpLambda.formats
case class Response(body: Option[String] = None,
statusCode: Int = 200,
headers: Map[String, Any] = Map.empty[String, Any])
object HttpLambda {
implicit val formats = Serialization.formats(NoTypeHints)
}
class HttpLambda extends RequestStreamHandler {
override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
context.getLogger.log(s"Log: ${context.getRemainingTimeInMillis}")
println(s"Test ${context.getAwsRequestId}")
try {
val response = write(Response(Some(s"Fetched with ID: ${context.getAwsRequestId}")))
context.getLogger.log(s"Generated response is: ${response}")
val writer = new OutputStreamWriter(output, "UTF-8")
writer.write(response)
writer.flush()
writer.close()
} catch {
case e: Throwable => context.getLogger.log(s"exception? -> ${e}")
}
}
}
开发者ID:pdolega,项目名称:lambda-samples,代码行数:40,代码来源:HttpLambda.scala
注:本文中的com.amazonaws.services.lambda.runtime.Context类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论