### Build and Deploy SAM Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/README.md Use the SAM CLI to build and deploy an example application. Ensure you have SAM CLI, Java 11, Maven, and Docker installed. ```bash # Switch to the directory containing an example for the powertools-idempotency module $ cd powertools-examples-idempotency/sam ``` -------------------------------- ### Deploy SQS Batch Example with SAM Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-batch/README.md Instructions for deploying the SQS batch processing example using AWS SAM. Navigate to the SQS deployment directory and run `sam build` followed by `sam deploy --guided`. ```bash cd deploy/sqs sam build sam deploy --guided ``` -------------------------------- ### Basic Lambda Handler Setup for Testing Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md Example setup for unit testing a Lambda handler that uses the Idempotency utility. This includes mocking dependencies and initializing the handler. ```java public class AppTest { @Mock private DynamoDbClient client; private App app; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); app = new App(client); } @Test public void testApp() { app.handleRequest(..., context); // ... assert } } ``` -------------------------------- ### Build and Deploy Application with Bazel and SAM Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/sam-bazel/README.md Build the Java application using Bazel and deploy it using the AWS SAM CLI. Ensure you have followed the SAM getting started guide. ```bash bazel build //:powertools_sam_deploy.jar sam deploy --guided ``` -------------------------------- ### Example Log Output Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-parameters/sam/README.md This is an example of the log output you might see after testing the application, showing injected secret values. ```json { ... "thread": "main", "level": "INFO", "loggerName": "org.demo.parameters.ParametersFunction", "message": "secretjsonobj=MyObject{id=23443, code='hk38543oj24kn796kp67bkb234gkj679l68'}\n", ... } ``` -------------------------------- ### Build and Deploy Sample Application Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/kotlin/README.md Use this command to build the sample application and deploy it to your AWS environment using SAM. Follow the guided prompts for configuration. ```bash sam build && sam deploy --guided ``` -------------------------------- ### Example Response from Idempotency Endpoint Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-idempotency/sam/README.md This is an example of the JSON response you should expect after successfully testing the idempotency endpoint. ```json { "message": "hello world", "location": "123.123.123.1" } ``` -------------------------------- ### Build on Native OS (Linux) Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-idempotency/sam-graalvm/README.md For Linux users with GraalVM installed, this command builds the application natively. Ensure JAVA_HOME is set to your GraalVM installation path. ```shell export JAVA_HOME= mvn clean -Pnative-image package -DskipTests sam build ``` -------------------------------- ### Build on Native OS (Linux) Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-cloudformation/infra/sam-graalvm/README.md For Linux users with GraalVM installed. Sets JAVA_HOME, builds the native image, and then builds the SAM application. ```shell export JAVA_HOME= cd ../.. mvn clean -Pnative-image package -DskipTests cd infra/sam-graalvm sam build ``` -------------------------------- ### Example Event 1 for Idempotency Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This is the first example event used for idempotency testing. It includes user details, product ID, charge type, and amount. ```json { "userDetail": { "username": "User1", "user_email": "user@example.com" }, "productId": 1500, "charge_type": "subscription", "amount": 500 } ``` -------------------------------- ### Build the application with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-kafka/README.md Use the AWS SAM CLI to build the application. Ensure you have AWS SAM CLI installed. ```bash sam build ``` -------------------------------- ### Deploy with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-cloudformation/README.md Use this command to build and deploy the sample application using the AWS SAM CLI. Ensure you have SAM CLI installed and configured. ```bash cd infra/sam sam build sam deploy --guided --parameter-overrides BucketNameParam=my-unique-bucket-2.10.0718 ``` -------------------------------- ### Deploy with CDK Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-cloudformation/README.md Use these commands to build and deploy the sample application using AWS CDK. Ensure you have CDK, Java 11, Maven, and Docker installed. ```bash cd infra/cdk mvn package cdk synth cdk deploy -c BucketNameParam=my-unique-bucket-2.10.0718 ``` -------------------------------- ### Deploy the application with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-kafka/README.md Deploy the application to AWS using the guided deployment option. You will be prompted for required parameters. ```bash sam deploy --guided ``` -------------------------------- ### Capture Cold Start Metric Automatically Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/metrics.md Use the `@FlushMetrics` annotation with `captureColdStart = true` to automatically capture cold start metrics. This creates a separate EMF blob for the 'ColdStart' metric with 'FunctionName' and 'Service' dimensions. ```java import software.amazon.lambda.powertools.metrics.FlushMetrics; public class MetricsColdStart implements RequestHandler { @Override @FlushMetrics(captureColdStart = true) public Object handleRequest(Object input, Context context) { ... } } ``` -------------------------------- ### Integrating Lambda Metadata with Other Powertools Utilities Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/lambda_metadata.md This example demonstrates how to integrate Lambda Metadata with Logging, Tracing, and Metrics utilities to enrich observability data with Availability Zone information. ```java import software.amazon.lambda.powertools.logging.Logging; import software.amazon.lambda.powertools.tracing.Tracing; import software.amazon.lambda.powertools.tracing.TracingUtils; import software.amazon.lambda.powertools.metrics.FlushMetrics; import software.amazon.lambda.powertools.metrics.Metrics; import software.amazon.lambda.powertools.metrics.MetricsFactory; import software.amazon.lambda.powertools.metrics.model.MetricUnit; import software.amazon.lambda.powertools.metadata.LambdaMetadata; import software.amazon.lambda.powertools.metadata.LambdaMetadataClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; public class IntegratedExample implements RequestHandler { private static final Logger LOG = LoggerFactory.getLogger(IntegratedExample.class); private static final Metrics metrics = MetricsFactory.getMetricsInstance(); @Logging @Tracing @FlushMetrics(captureColdStart = true) @Override public String handleRequest(Object input, Context context) { LambdaMetadata metadata = LambdaMetadataClient.get(); String azId = metadata.getAvailabilityZoneId(); // Add AZ as dimension for all metrics metrics.addDimension("availability_zone_id", azId); // Add AZ to structured logs MDC.put("availability_zone_id", azId); LOG.info("Processing request"); // Add AZ to traces TracingUtils.putAnnotation("availability_zone_id", azId); // Add metrics metrics.addMetric("RequestProcessed", 1, MetricUnit.COUNT); return "{\"status\": \"ok\"}"; } } ``` -------------------------------- ### Initialize TracingUtils in Lambda Constructor for SnapStart Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/tracing.md Reference TracingUtils in your Lambda handler's constructor to ensure it's loaded for SnapStart priming. This is useful if you don't already have a custom TracingUtils setup. ```java import software.amazon.lambda.powertools.validation.Validation; import software.amazon.lambda.powertools.validation.ValidationConfig; public class MyFunctionHandler implements RequestHandler { public MyFunctionHandler() { TracingUtils.init(); // Ensure TracingUtils is loaded for SnapStart } @Override @Validation(inboundSchema = "classpath:/schema_in.json", outboundSchema = "classpath:/schema_out.json") public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) { // ... return something; } } ``` -------------------------------- ### Success Event Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md A sample JSON payload representing a successful event, including user details and an order ID, which can be used to generate an idempotency key. ```json { "user": { "uid": "BB0D045C-8878-40C8-889E-38B3CB0A61B1", "name": "Foo" }, "orderId": 10000 } ``` -------------------------------- ### SQS Batch Handler Implementation Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/batch.md Implement an SQS batch handler using `BatchMessageHandlerBuilder`. This example shows how to configure the handler to process SQS messages and deserialize them into `Product` objects. ```java import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import software.amazon.lambda.powertools.batch.BatchMessageHandlerBuilder; import software.amazon.lambda.powertools.batch.handler.BatchMessageHandler; public class SqsBatchHandler implements RequestHandler { private final BatchMessageHandler handler; public SqsBatchHandler() { handler = new BatchMessageHandlerBuilder() .withSqsBatchHandler() .buildWithMessageHandler(this::processMessage, Product.class); } @Override public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) { return handler.processBatch(sqsEvent, context); } private void processMessage(Product p, Context c) { // Process the product } } ``` -------------------------------- ### Configure Log Buffering with Logback Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/logging.md Configure log buffering using `BufferingAppender` in `logback.xml`. This setup buffers logs at DEBUG level and flushes them on error. It uses `LambdaJsonEncoder` for structured JSON output. ```xml 20480 DEBUG true ``` -------------------------------- ### Deploy Sample Application with CDK Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/cdk/README.md Use this command to deploy the sample application. If it's your first time running CDK, you'll need to bootstrap the environment first. ```bash cdk deploy ``` -------------------------------- ### Deploy Sample Application with Terraform and Maven Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/terraform/README.md Run these commands to initialize Terraform and then package the Java application and apply the Terraform configuration to deploy the sample application. ```bash terraform init mvn package && terraform apply ``` -------------------------------- ### Deploy Sample Application Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-cloudformation/infra/sam-graalvm/README.md Deploys the sample application using SAM with a specified bucket name parameter. ```shell sam deploy --guided --parameter-overrides BucketNameParam=my-unique-bucket-2.10.0718 ``` -------------------------------- ### Manually Capture Cold Start Metric Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/metrics.md Disable automatic cold start capture via `@FlushMetrics(captureColdStart = false)` and manually invoke `captureColdStartMetric` to gain more control. This method allows for custom dimensions to be added to the cold start metric. ```java import software.amazon.lambda.powertools.metrics.FlushMetrics; import software.amazon.lambda.powertools.metrics.Metrics; import software.amazon.lambda.powertools.metrics.MetricsFactory; public class MetricsColdStartCustomFunction implements RequestHandler { private static final Metrics metrics = MetricsFactory.getMetricsInstance(); @Override @FlushMetrics(captureColdStart = false) public Object handleRequest(Object input, Context context) { metrics.captureColdStartMetric(context, DimensionSet.of("CustomDimension", "CustomValue")); ... } } ``` -------------------------------- ### Build the project with Gradle Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/gradle/README.md Use the Gradle wrapper to bootstrap Gradle and run the build. This command compiles the code, runs tests, and packages the application. ```bash ./gradlew build ``` -------------------------------- ### Bootstrap CDK Environment Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/cdk/README.md Run this command before deploying for the first time to set up the necessary AWS resources for CDK. ```bash cdk bootstrap ``` -------------------------------- ### Example Event 2 for Idempotency Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This is the second example event, differing from the first by a changed amount. This difference triggers the payload validation. ```json { "userDetail": { "username": "User1", "user_email": "user@example.com" }, "productId": 1500, "charge_type": "subscription", "amount": 1 } ``` -------------------------------- ### DynamoDB Stream Example Event Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/batch.md An example of a DynamoDB Stream event payload, illustrating the structure of records for INSERT and MODIFY operations. ```json { "Records": [ { "eventID": "c4ca4238a0b923820dcc509a6f75849b", "eventName": "INSERT", "eventVersion": "1.1", "eventSource": "aws:dynamodb", "awsRegion": "eu-central-1", "dynamodb": { "Keys": { "Id": { "N": "101" } }, "NewImage": { "Message": { "S": "New item!" }, "Id": { "N": "101" } }, "ApproximateCreationDateTime": 1428537600, "SequenceNumber": "4421584500000000017450439091", "SizeBytes": 26, "StreamViewType": "NEW_AND_OLD_IMAGES" }, "eventSourceARN": "arn:aws:dynamodb:eu-central-1:123456789012:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899", "userIdentity": { "principalId": "dynamodb.amazonaws.com", "type": "Service" } }, { "eventID": "c81e728d9d4c2f636f067f89cc14862c", "eventName": "MODIFY", "eventVersion": "1.1", "eventSource": "aws:dynamodb", "awsRegion": "eu-central-1", "dynamodb": { "Keys": { "Id": { "N": "101" } }, "NewImage": { "Message": { "S": "This item has changed" }, "Id": { "N": "101" } }, "OldImage": { "Message": { "S": "New item!" }, "Id": { "N": "101" } }, "ApproximateCreationDateTime": 1428537600, "SequenceNumber": "4421584500000000017450439092", "SizeBytes": 59, "StreamViewType": "NEW_AND_OLD_IMAGES" }, "eventSourceARN": "arn:aws:dynamodb:eu-central-1:123456789012:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899" } ] } ``` -------------------------------- ### SQS Example Event Structure Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/batch.md An example of an SQS event structure, showing the 'Records' array containing individual SQS messages with their bodies. ```json { "Records": [ { "messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54", "receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==", "body": "{\n \"id\": 1234,\n \"name\": \"product\",\n \"price\": 42\n}", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1601975706495", "SenderId": "AROAIFU437PVZ5L2J53F5", "ApproximateFirstReceiveTimestamp": "1601975706499" }, "messageAttributes": { }, "md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", "awsRegion": "eu-central-1" }, { "messageId": "e9144555-9a4f-4ec3-99a0-34ce359b4b54", "receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==", "body": "{\n \"id\": 12345,\n \"name\": \"product5\",\n \"price\": 45\n}", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1601975706495", "SenderId": "AROAIFU437PVZ5L2J53F5", "ApproximateFirstReceiveTimestamp": "1601975706499" }, "messageAttributes": { }, "md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", "awsRegion": "eu-central-1" }] } ``` -------------------------------- ### Package and Deploy Application Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/serverless/README.md Use this command to package the Java application and deploy it using Serverless Framework. ```bash mvn package && sls deploy ``` -------------------------------- ### Example Event with API Gateway request context Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/logging.md This is an example of an event payload from API Gateway, showing the 'requestContext.requestId' field which can be used as a correlation ID. ```json { "requestContext": { "requestId": "correlation_id_value" } } ``` -------------------------------- ### Example of Deserialization Failure Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/kafka.md This example illustrates the type of runtime exception thrown when a Kafka record fails deserialization. The handler method is not invoked in such cases. ```java // If any record in the batch has invalid Avro data, you'll see: // RuntimeException: Failed to deserialize Kafka record: Invalid Avro schema for record at offset 12345 ``` -------------------------------- ### Example CloudWatch Logs with correlation ID Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/logging.md This is an example of a CloudWatch log entry generated by AWS Lambda Powertools for Java, including the 'correlation_id' field. ```json { "level": "INFO", "message": "Collecting payment", "timestamp": "2023-12-01T14:49:19.293Z", "service": "payment", "correlation_id": "correlation_id_value" } ``` -------------------------------- ### Setup DynamoDB Local and Invoke Lambda with SAM Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This shell script demonstrates how to set up a DynamoDB Local instance using Docker, create the necessary idempotency table, and then invoke a Lambda function locally using SAM CLI with environment variables. ```shell # use or create a docker network docker network inspect sam-local || docker network create sam-local # start dynamodb-local with docker docker run -d --rm -p 8000:8000 \ --network sam-local \ --name dynamo \ amazon/dynamodb-local # create the idempotency table aws dynamodb create-table --table-name idempotency --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST --endpoint-url http://localhost:8000 # invoke the function locally sam local invoke IdempotentFunction \ --event event.json \ --env-vars env.json \ --docker-network sam-local ``` ```json { "IdempotentFunction": { "TABLE_NAME": "idempotency" } } ``` -------------------------------- ### SQS Message Body Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-serialization/sam/README.md This example demonstrates sending a message to an SQS queue, which will be processed and deserialized by a Lambda function using Powertools for AWS Lambda (Java). ```bash aws sqs send-message --queue-url "https://sqs.[REGION].amazonaws.com/[ACCOUNT-ID]/sqs-event-deserialization-queue" --message-body '{"id": 1234, "name": "product", "price": 123}' ``` -------------------------------- ### Build with all serialization formats Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-kafka/README.md Build the application with Maven, including all serialization formats (JSON, Avro, Protobuf). This is the default behavior. ```bash mvn clean package -P full ``` -------------------------------- ### Idempotency Payload Subset Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This example shows a subset of the Lambda event payload that can be used for idempotency checks. It includes fields like requestId, routeKey, and stage. ```json { "requestId":"id", "routeKey":"ANY /createpayment", "stage":"$default", "time":"10/Feb/2021:13:40:43 +0000", "timeEpoch":1612964443723 }, "isBase64Encoded":false } ``` -------------------------------- ### Build Locally using Docker Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-idempotency/sam-graalvm/README.md Recommended for macOS and Windows users to cross-compile using Docker, matching the target platform of Lambda. This command builds the Docker image, runs a container to build the Maven package with GraalVM native image, and then uses SAM to package the pre-built binary. ```shell docker build --platform linux/amd64 . -t powertools-examples-idempotency-sam-graalvm docker run --platform linux/amd64 -it -v `pwd`:`pwd` -w `pwd` -v ~/.m2:/root/.m2 powertools-examples-idempotency-sam-graalvm mvn clean -Pnative-image package -DskipTests sam build --use-container --build-image powertools-examples-idempotency-sam-graalvm ``` -------------------------------- ### Example HTTP Event with custom correlation ID header Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/logging.md This is an example of an HTTP event payload that includes a custom header 'my_request_id_header' which can be used to extract the correlation ID. ```json { "headers": { "my_request_id_header": "correlation_id_value" } } ``` -------------------------------- ### Capture Cold Start Metric with Custom Function Name Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/metrics.md To specify a custom function name for the cold start metric, use the `functionName` parameter within the `@FlushMetrics` annotation. ```java import software.amazon.lambda.powertools.metrics.FlushMetrics; public class MetricsColdStartCustomFunction implements RequestHandler { @Override @FlushMetrics(captureColdStart = true, functionName = "CustomFunction") public Object handleRequest(Object input, Context context) { ... } } ``` -------------------------------- ### Example API Gateway Event Payload Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This is an example of an API Gateway proxy integration event payload. The 'body' field contains the actual request payload, which can be used for idempotency checks. ```json { "version":"2.0", "body":"{\"username\":\"xyz\",\"productId\":\"123456789\"}", "routeKey":"ANY /createpayment", "rawPath":"/createpayment", "rawQueryString":"", "headers": { "Header1": "value1", "Header2": "value2" }, "requestContext":{ "accountId":"123456789012", "apiId":"api-id", "domainName":"id.execute-api.us-east-1.amazonaws.com", "domainPrefix":"id", "http":{ "method":"POST", "path":"/createpayment", "protocol":"HTTP/1.1", "sourceIp":"ip", "userAgent":"agent" }, ``` -------------------------------- ### Build with Protobuf serialization Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-kafka/README.md Build the application with Maven, including only Protobuf serialization. This uses the 'protobuf-only' Maven profile. ```bash mvn clean package -P protobuf-only ``` -------------------------------- ### Kinesis Batch Handler Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/batch.md Implement a Kinesis batch handler using BatchMessageHandlerBuilder. This example shows how to configure the handler for Kinesis events and process individual messages with custom deserialization. ```java import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import software.amazon.lambda.powertools.batch.BatchMessageHandlerBuilder; import software.amazon.lambda.powertools.batch.handler.BatchMessageHandler; public class KinesisBatchHandler implements RequestHandler { private final BatchMessageHandler handler; public KinesisBatchHandler() { handler = new BatchMessageHandlerBuilder() .withKinesisBatchHandler() .buildWithMessageHandler(this::processMessage, Product.class); } @Override public StreamsEventResponse handleRequest(KinesisEvent kinesisEvent, Context context) { return handler.processBatch(kinesisEvent, context); } private void processMessage(Product p, Context c) { // process the product } } ``` -------------------------------- ### Lambda Function Log Output Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-parameters/sam-graalvm/README.md Example log output from the Lambda function, showing the injected secret in JSON format. This helps in verifying the successful retrieval and injection of sensitive data. ```json { "...": "...", "thread": "main", "level": "INFO", "loggerName": "org.demo.parameters.ParametersFunction", "message": "secretjsonobj=MyObject{id=23443, code='hk38543oj24kn796kp67bkb234gkj679l68'}\n", "...": "..." } ``` -------------------------------- ### Kinesis Example Event Structure Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/batch.md An example JSON structure for a Kinesis event, demonstrating the format of 'Records' with nested 'kinesis' objects containing event data like 'data', 'partitionKey', and 'sequenceNumber'. ```json { "Records": [ { "kinesis": { "partitionKey": "partitionKey-03", "kinesisSchemaVersion": "1.0", "data": "eyJpZCI6MTIzNCwgIm5hbWUiOiJwcm9kdWN0IiwgInByaWNlIjo0Mn0=", "sequenceNumber": "49545115243490985018280067714973144582180062593244200961", "approximateArrivalTimestamp": 1428537600, "encryptionType": "NONE" }, "eventSource": "aws:kinesis", "eventID": "shardId-000000000000:49545115243490985018280067714973144582180062593244200961", "invokeIdentityArn": "arn:aws:iam::EXAMPLE", "eventVersion": "1.0", "eventName": "aws:kinesis:record", "eventSourceARN": "arn:aws:kinesis:EXAMPLE", "awsRegion": "eu-central-1" }, { "kinesis": { "partitionKey": "partitionKey-03", "kinesisSchemaVersion": "1.0", "data": "eyJpZCI6MTIzNDUsICJuYW1lIjoicHJvZHVjdDUiLCAicHJpY2UiOjQ1fQ==", "sequenceNumber": "49545115243490985018280067714973144582180062593244200962", "approximateArrivalTimestamp": 1428537600, "encryptionType": "NONE" }, "eventSource": "aws:kinesis", "eventID": "shardId-000000000000:49545115243490985018280067714973144582180062593244200961", "invokeIdentityArn": "arn:aws:iam::EXAMPLE", "eventVersion": "1.0", "eventName": "aws:kinesis:record", "eventSourceARN": "arn:aws:kinesis:EXAMPLE", "awsRegion": "eu-central-1" } ] } ``` -------------------------------- ### Useful CDK Commands Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/cdk/README.md A list of common commands for managing your CDK application, including packaging, synthesizing, deploying, and comparing changes. ```bash mvn package cdk synth cdk deploy cdk diff cdk docs ``` -------------------------------- ### API Gateway Request Example Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-serialization/sam/README.md This example shows how to deserialize an API Gateway request body using Powertools for AWS Lambda (Java). It's useful for handling incoming HTTP requests in Lambda functions. ```json { "id":1234, "name":"product", "price":42 } ``` -------------------------------- ### Example Event for Idempotency Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md This JSON object represents a sample event that can be used with the idempotency utilities. ```json { "username": "xyz", "product_id": "123456789" } ``` -------------------------------- ### SQS Event Structure Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/serialization.md This is an example of an SQS event structure that can be processed by the EventDeserializer. It includes message details, attributes, and metadata. ```json { "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", "awsRegion": "eu-central-1" }, { "messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54", "receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==", "body": "{ \"id\": 12345, \"name\": \"product5\", \"price\": 45}", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1601975706495", "SenderId": "AROAIFU437PVZ5L2J53F5", "ApproximateFirstReceiveTimestamp": "1601975706499" }, "messageAttributes": { }, "md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", "awsRegion": "eu-central-1" } ] } ``` -------------------------------- ### Create Native Image with Docker Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-serialization/sam-graalvm/README.md Use Docker to create a native image of the application, mounting the current directory and Maven's local repository. This is useful when working with SNAPSHOT versions of PowerTools. ```shell docker run --platform linux/amd64 -it -v `pwd`:`pwd` -w `pwd` -v ~/.m2:/root/.m2 powertools-examples-serialization-sam-graalvm mvn clean -Pnative-image package -DskipTests ``` -------------------------------- ### Generate classesloaded.txt File with Maven Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/Priming.md Run tests with the specified Maven profile to generate the `classesloaded.txt` file in the module's target directory. ```shell mvn -Pgenerate-classesloaded-file clean test ``` -------------------------------- ### Set GraalVM Home Directory Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/FAQs.md Set the JAVA_HOME environment variable to point to your GraalVM installation directory. This is a prerequisite for using GraalVM. ```shell export JAVA_HOME= ``` -------------------------------- ### Initialize TracingUtils in Lambda Static Initializer for SnapStart Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/core/tracing.md Reference TracingUtils in a static initializer block within your Lambda handler to ensure it's loaded for SnapStart priming. This is an alternative to using the constructor. ```java import software.amazon.lambda.powertools.validation.Validation; import software.amazon.lambda.powertools.validation.ValidationConfig; public class MyFunctionHandler implements RequestHandler { static { TracingUtils.init(); // Ensure TracingUtils is loaded for SnapStart } @Override @Validation(inboundSchema = "classpath:/schema_in.json", outboundSchema = "classpath:/schema_out.json") public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) { // ... return something; } } ``` -------------------------------- ### Build Docker Image for SAM Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/sam-graalvm/README.md Build the Docker image that will serve as the build environment for your SAM project. Ensure the platform is set to linux/amd64. ```shell docker build --platform linux/amd64 . -t powertools-examples-core-sam-graalvm ``` -------------------------------- ### Build SAM Project with Docker Container Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-serialization/sam-graalvm/README.md Build the SAM project using the previously created Docker image. The --use-container flag ensures the build happens within the specified image. ```shell sam build --use-container --build-image powertools-examples-serialization-sam-graalvm ``` -------------------------------- ### Implement Custom XML Transformer Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/parameters.md Provides an example of creating a custom transformer by implementing the `Transformer` interface to deserialize XML strings into Java objects. ```java public class XmlTransformer implements Transformer { private final XmlMapper mapper = new XmlMapper(); @Override public T applyTransformation(String value, Class targetClass) throws TransformationException { try { return mapper.readValue(value, targetClass); } catch (IOException e) { throw new TransformationException(e); } } } ``` -------------------------------- ### Install Large Messages Utility with Maven Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/large_messages.md Add the large-messages dependency to your Maven project. Configure the aspectj-maven-plugin for compile-time weaving if not using the functional approach. ```xml ... software.amazon.lambda powertools-large-messages {{ powertools.version }} ... ... ... dev.aspectj aspectj-maven-plugin 1.14 11 11 11 software.amazon.lambda powertools-large-messages org.aspectj aspectjtools 1.9.22 compile ... ``` -------------------------------- ### Build Locally using Docker Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-cloudformation/infra/sam-graalvm/README.md Recommended for macOS and Windows users. Cross-compiles using Docker to match the target platform of Lambda. ```shell docker build --platform linux/amd64 . -t powertools-examples-cloudformation-sam-graalvm docker run --platform linux/amd64 -it -v `pwd`/../..:`pwd`/../.. -w `pwd`/../.. -v ~/.m2:/root/.m2 powertools-examples-cloudformation-sam-graalvm mvn clean -Pnative-image package -DskipTests sam build --use-container --build-image powertools-examples-cloudformation-sam-graalvm ``` -------------------------------- ### Build SAM Project with Docker Container Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/examples/powertools-examples-core-utilities/sam-graalvm/README.md Build the SAM project using the previously created Docker image. The --use-container flag ensures the build process runs within the specified container. ```shell sam build --use-container --build-image powertools-examples-core-sam-graalvm ``` -------------------------------- ### Java Unit Test Setup with DynamoDB Local Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/idempotency.md Initializes DynamoDB Local in memory and configures a DynamoDB client to point to the local endpoint. It also creates a table named 'idempotency' with a primary key 'id'. ```java public class AppTest { @Mock private Context context; private App app; private static DynamoDbClient client; @BeforeAll public static void setupDynamoLocal() { int port = getFreePort(); // Initialize DynamoDBLocal try { DynamoDBProxyServer dynamoProxy = ServerRunner.createServerFromCommandLineArgs(new String[]{ "-inMemory", "-port", Integer.toString(port) }); dynamoProxy.start(); } catch (Exception e) { throw new RuntimeException(); } // Initialize DynamoDBClient client = DynamoDbClient.builder() .httpClient(UrlConnectionHttpClient.builder().build()) .region(Region.EU_WEST_1) .endpointOverride(URI.create("http://localhost:" + port)) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("FAKE", "FAKE"))) .build(); // create the table (use same table name as in pom.xml) client.createTable(CreateTableRequest.builder() .tableName("idempotency") .keySchema(KeySchemaElement.builder().keyType(KeyType.HASH).attributeName("id").build()) .attributeDefinitions( AttributeDefinition.builder().attributeName("id").attributeType(ScalarAttributeType.S).build() ) .billingMode(BillingMode.PAY_PER_REQUEST) .build()); } private static int getFreePort() { try { ServerSocket socket = new ServerSocket(0); ``` -------------------------------- ### Install Large Messages Utility with Gradle Source: https://github.com/aws-powertools/powertools-lambda-java/blob/main/docs/utilities/large_messages.md Add the large-messages dependency to your Gradle project using the 'aspect' configuration. Ensure AspectJ post-compile weaving is enabled. ```groovy plugins { id 'java' id 'io.freefair.aspectj.post-compile-weaving' version '8.1.0' // Not needed when using the functional approach } repositories { mavenCentral() } dependencies { aspect 'software.amazon.lambda:powertools-large-messages:{{ powertools.version }}' // Use 'implementation' instead of 'aspect' when using the functional approach } sourceCompatibility = 11 // or higher targetCompatibility = 11 // or higher ```