├── .gitignore ├── LICENSE ├── README.md ├── buildAndDeploy.sh ├── buildAndDeployDontAsk.sh ├── cdk ├── README.md ├── cdk.json ├── pom.xml └── src │ ├── main │ └── java │ │ └── airhacks │ │ ├── CDKApp.java │ │ └── LambdaStack.java │ └── test │ └── java │ └── airhacks │ └── CDKAppTest.java ├── destroy.sh └── lambda ├── pom.xml └── src ├── main └── java │ └── airhacks │ └── lambda │ └── boundary │ └── POJOLambda.java └── test └── java └── airhacks └── InvokeLambdaIT.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | dependency-reduced-pom.xml 8 | buildNumber.properties 9 | .mvn/timing.properties 10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 11 | .mvn/wrapper/maven-wrapper.jar 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Adam Bien 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simplest Possible AWS Lambda Function with Cloud Development Kit (CDK) Boilerplate 2 | 3 | A lean starting point for building, testing and deploying AWS Lambdas with Java. 4 | 5 | # TL;DR 6 | 7 | A simple Java AWS Lambda without any AWS dependencies: 8 | 9 | ```java 10 | 11 | public class Greetings{ 12 | 13 | public String onEvent(Map input) { 14 | System.out.println("received: " + input); 15 | return input 16 | .entrySet() 17 | .stream() 18 | .map(e -> e.getKey() + "->" + e.getValue()) 19 | .collect(Collectors.joining(",")); 20 | } 21 | 22 | } 23 | 24 | ``` 25 | 26 | ...deployed with AWS Cloud Development Kit: 27 | 28 | 29 | ```java 30 | 31 | import software.amazon.awscdk.services.lambda.Code; 32 | import software.amazon.awscdk.services.lambda.Function; 33 | import software.amazon.awscdk.services.lambda.Runtime; 34 | 35 | //... 36 | 37 | Function createUserListenerFunction(String functionName,String functionHandler, int memory, int timeout) { 38 | return Function.Builder.create(this, id(functionName)) 39 | .runtime(Runtime.JAVA_11) //https://aws.amazon.com/corretto 40 | .code(Code.fromAsset("../target/function.jar")) 41 | .handler(functionHandler) 42 | .memorySize(memory) 43 | .functionName(functionName) 44 | .timeout(Duration.seconds(timeout)) 45 | .build(); 46 | } 47 | 48 | ``` 49 | 50 | ...provisioned with maven and cdk: 51 | 52 | ``` 53 | mvn clean package 54 | cd cdk && mvn clean package && cdk deploy 55 | ``` 56 | 57 | ...and (blackbox) tested with [AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide): 58 | 59 | ```java 60 | 61 | @BeforeEach 62 | public void initClient() { 63 | var credentials = DefaultCredentialsProvider 64 | .builder() 65 | .profileName("airhacks.live") 66 | .build(); 67 | 68 | this.client = LambdaClient.builder() 69 | .credentialsProvider(credentials) 70 | .build(); 71 | } 72 | 73 | @Test 74 | public void invokeLambdaAsynchronously() { 75 | String json = "{\"user \":\"duke\"}"; 76 | SdkBytes payload = SdkBytes.fromUtf8String(json); 77 | 78 | InvokeRequest request = InvokeRequest.builder() 79 | .functionName("airhacks_lambda_greetings_boundary_Greetings") 80 | .payload(payload) 81 | .invocationType(InvocationType.REQUEST_RESPONSE) 82 | .build(); 83 | 84 | var response = this.client.invoke(request); 85 | var error = response.functionError(); 86 | assertNull(error); 87 | var value = response.payload().asUtf8String(); 88 | System.out.println("Function executed. Response: " + value); 89 | } 90 | 91 | ``` 92 | 93 | ## In Action 94 | 95 | [![Plain Java POJOs as AWS Lambdas](https://i.ytimg.com/vi/rHq514-1aHM/mqdefault.jpg)](https://www.youtube.com/embed/rHq514-1aHM?rel=0) 96 | 97 | ## Java "vs." JavaScript 98 | 99 | Cold and "warm" starts of JavaScript and Java Lambdas: 100 | 101 | [![Java vs. JavaScript comparison](https://i.ytimg.com/vi/28Da0l0MFms/mqdefault.jpg)](https://www.youtube.com/embed/28Da0l0MFms?rel=0) 102 | 103 | ## AWS Lambda on Java: How Good / Bad Is The Cold Start? 104 | 105 | [![Coldstart with Java](https://i.ytimg.com/vi/EXSZ5TFgUKU/mqdefault.jpg)](https://www.youtube.com/embed/EXSZ5TFgUKU?rel=0) 106 | 107 | ## Lambda Configuration 108 | 109 | [![AWS Lambda Configuration with Java CDK](https://i.ytimg.com/vi/Z3Ir-AQEsKk/mqdefault.jpg)](https://www.youtube.com/embed/Z3Ir-AQEsKk?rel=0) 110 | 111 | ## References 112 | 113 | The deployment is borrowed from: ["Slightly Streamlined AWS Cloud Development Kit (CDK) Boilerplate"](https://github.com/AdamBien/aws-cdk-plain) 114 | -------------------------------------------------------------------------------- /buildAndDeploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | echo "building functions" 4 | cd lambda && mvn clean package 5 | echo "building CDK" 6 | cd ../cdk && mvn clean package && cdk deploy -------------------------------------------------------------------------------- /buildAndDeployDontAsk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | echo "building functions" 4 | cd lambda && mvn clean package 5 | echo "building CDK" 6 | cd ../cdk && mvn clean package && cdk deploy --all --require-approval=never -------------------------------------------------------------------------------- /cdk/README.md: -------------------------------------------------------------------------------- 1 | # Slightly Streamlined AWS Cloud Development Kit (CDK) Boilerplate 2 | 3 | This module is based on [aws-cdk-plain](https://github.com/AdamBien/aws-cdk-plain) 4 | which fully relies on [AWS CDK for Java](https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-java.html). 5 | 6 | ## Installation 7 | 8 | 1. Install [AWS CDK CLI](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) 9 | 2. [`cdk boostrap --profile YOUR_AWS_PROFILE`](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) 10 | 11 | ## Useful commands 12 | 13 | * `mvn package` compile and run tests 14 | * `cdk ls` list all stacks in the app 15 | * `cdk synth` emits the synthesized CloudFormation template 16 | * `cdk deploy` deploy this stack to your default AWS account/region 17 | * `cdk diff` compare deployed stack with current state 18 | * `cdk docs` open CDK documentation 19 | 20 | Enjoy! 21 | 22 | ## in action 23 | 24 | [![Infrastructure as Java Code (IaJC): Setting AWS System Manager Parameter](https://i.ytimg.com/vi/eTG7EV1ThqQ/mqdefault.jpg)](https://www.youtube.com/embed/eTG7EV1ThqQ?rel=0) 25 | 26 | 27 | 28 | See you at: [airhacks.live](https://airhacks.live) -------------------------------------------------------------------------------- /cdk/cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "mvn -e -q compile exec:java", 3 | "watch":{ 4 | "include":[ 5 | "../target/function.jar" 6 | ] 7 | }, 8 | "context": { 9 | "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true, 10 | "@aws-cdk/core:stackRelativeExports": true, 11 | "@aws-cdk/aws-rds:lowercaseDbIdentifier": true, 12 | "@aws-cdk/aws-lambda:recognizeVersionProps": true, 13 | "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true 14 | } 15 | } -------------------------------------------------------------------------------- /cdk/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | airhacks 8 | aws-lambda-cdk-plain 9 | 0.1 10 | 11 | 12 | 13 | org.codehaus.mojo 14 | exec-maven-plugin 15 | 3.1.0 16 | 17 | airhacks.CDKApp 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | software.amazon.awscdk 27 | aws-cdk-lib 28 | 2.182.0 29 | 30 | 31 | software.constructs 32 | constructs 33 | 3.4.344 34 | 35 | 36 | org.junit.jupiter 37 | junit-jupiter-api 38 | 5.10.2 39 | test 40 | 41 | 42 | org.junit.jupiter 43 | junit-jupiter-engine 44 | 5.10.2 45 | test 46 | 47 | 48 | org.assertj 49 | assertj-core 50 | 3.25.3 51 | test 52 | 53 | 54 | 55 | UTF-8 56 | 21 57 | 21 58 | 21 59 | 60 | 61 | -------------------------------------------------------------------------------- /cdk/src/main/java/airhacks/CDKApp.java: -------------------------------------------------------------------------------- 1 | package airhacks; 2 | 3 | import java.util.Map; 4 | 5 | import software.amazon.awscdk.App; 6 | import software.amazon.awscdk.Tags; 7 | 8 | public class CDKApp { 9 | public static void main(final String[] args) { 10 | 11 | var app = new App(); 12 | var appName = "aws-lambda-cdk-plain"; 13 | Tags.of(app).add("project", "airhacks.live"); 14 | Tags.of(app).add("environment", "workshops"); 15 | Tags.of(app).add("application", appName); 16 | 17 | new LambdaStack.Builder(app, appName) 18 | .functionHandler("airhacks.lambda.boundary.POJOLambda::onEvent") 19 | .functionName("airhacks_POJOLambda") 20 | .configuration(Map.of("message", "hello,duke")) 21 | .build(); 22 | app.synth(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cdk/src/main/java/airhacks/LambdaStack.java: -------------------------------------------------------------------------------- 1 | package airhacks; 2 | 3 | import java.util.Map; 4 | import java.util.Objects; 5 | 6 | import software.amazon.awscdk.CfnOutput; 7 | import software.amazon.awscdk.Duration; 8 | import software.amazon.awscdk.Stack; 9 | import software.amazon.awscdk.services.events.targets.EventBus; 10 | import software.amazon.awscdk.services.lambda.Architecture; 11 | import software.amazon.awscdk.services.lambda.Code; 12 | import software.amazon.awscdk.services.lambda.Function; 13 | import software.amazon.awscdk.services.lambda.Runtime; 14 | import software.amazon.awscdk.services.lambda.Tracing; 15 | import software.constructs.Construct; 16 | 17 | public class LambdaStack extends Stack { 18 | 19 | public static class Builder { 20 | 21 | private Construct construct; 22 | private String stackId; 23 | private String functionName; 24 | private String functionHandler; 25 | private Map configuration = Map.of(); 26 | private final int ONE_CPU = 1700; 27 | private int ram = ONE_CPU; 28 | 29 | public Builder(Construct construct, String stackNamePrefix) { 30 | this.construct = construct; 31 | this.stackId = stackNamePrefix.toLowerCase() + "-stack"; 32 | } 33 | 34 | public Builder functionName(String functionName) { 35 | this.functionName = functionName; 36 | return this; 37 | } 38 | 39 | public Builder functionHandler(String handler) { 40 | this.functionHandler = handler; 41 | return this; 42 | } 43 | 44 | public Builder ram(int ram) { 45 | this.ram = ram; 46 | return this; 47 | } 48 | 49 | public Builder withOneCPU() { 50 | this.ram = ONE_CPU; 51 | return this; 52 | } 53 | 54 | public Builder withHalfCPU() { 55 | this.ram = ONE_CPU / 2; 56 | return this; 57 | } 58 | 59 | public Builder withTwoCPUs() { 60 | this.ram = ONE_CPU * 2; 61 | return this; 62 | } 63 | 64 | public Builder configuration(Map configuration) { 65 | this.configuration = configuration; 66 | return this; 67 | } 68 | 69 | public LambdaStack build() { 70 | Objects.requireNonNull(this.functionName, "Function name is required"); 71 | Objects.requireNonNull(this.functionHandler, "Function handler (fqn::methodName) is required"); 72 | return new LambdaStack(this); 73 | } 74 | 75 | } 76 | 77 | 78 | public LambdaStack(Builder builder) { 79 | super(builder.construct, builder.stackId); 80 | var timeout = 10; 81 | 82 | var function = createFunction(builder.functionName, builder.functionHandler, builder.configuration, builder.ram, timeout); 83 | CfnOutput.Builder.create(this, "FunctionARN").value(function.getFunctionArn()).build(); 84 | } 85 | 86 | 87 | Function createFunction(String functionName,String functionHandler, Map configuration, int memory, int timeout) { 88 | return Function.Builder.create(this, functionName) 89 | .runtime(Runtime.JAVA_21) 90 | .architecture(Architecture.ARM_64) 91 | .code(Code.fromAsset("../lambda/target/function.jar")) 92 | .handler(functionHandler) 93 | .memorySize(memory) 94 | .functionName(functionName) 95 | .environment(configuration) 96 | .timeout(Duration.seconds(timeout)) 97 | .tracing(Tracing.ACTIVE) 98 | .build(); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /cdk/src/test/java/airhacks/CDKAppTest.java: -------------------------------------------------------------------------------- 1 | package airhacks; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import java.io.IOException; 6 | import java.util.Map; 7 | 8 | import com.fasterxml.jackson.databind.ObjectMapper; 9 | import com.fasterxml.jackson.databind.SerializationFeature; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import software.amazon.awscdk.App; 14 | 15 | public class CDKAppTest { 16 | private final static ObjectMapper JSON = 17 | new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); 18 | 19 | @Test 20 | public void testStack() throws IOException { 21 | App app = new App(); 22 | var stack = new LambdaStack.Builder(app, "test") 23 | .functionHandler("airhacks.lambda.greetings.boundary.Greetings::onEvent") 24 | .functionName("airhacks_POJOGreetings") 25 | .configuration(Map.of("message", "hello,duke")) 26 | .build(); 27 | 28 | // synthesize the stack to a CloudFormation template 29 | var actual = JSON.valueToTree(app.synth().getStackArtifact(stack.getArtifactId()).getTemplate()); 30 | 31 | // Update once resources have been added to the stack 32 | assertThat(actual.get("Resources")).isNotEmpty(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /destroy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cd cdk && cdk destroy -------------------------------------------------------------------------------- /lambda/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | airhacks 6 | aws-lambda-cdk-plain 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | 11 | 12 | maven-shade-plugin 13 | 3.5.1 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | function 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | software.amazon.awssdk 32 | bom 33 | 2.30.36 34 | pom 35 | import 36 | 37 | 38 | 39 | 40 | 47 | 48 | com.amazonaws 49 | aws-lambda-java-events 50 | 3.15.0 51 | 52 | 53 | 54 | software.amazon.awssdk 55 | lambda 56 | test 57 | 58 | 59 | org.junit.jupiter 60 | junit-jupiter 61 | 5.10.1 62 | test 63 | 64 | 65 | 66 | UTF-8 67 | 21 68 | 21 69 | 21 70 | 71 | -------------------------------------------------------------------------------- /lambda/src/main/java/airhacks/lambda/boundary/POJOLambda.java: -------------------------------------------------------------------------------- 1 | package airhacks.lambda.boundary; 2 | 3 | public class POJOLambda { 4 | 5 | static String message = System.getenv("message"); 6 | 7 | public POJOLambda() { 8 | System.out.println("initialized with configuration: " + message); 9 | } 10 | 11 | public void onEvent(Object event) { 12 | System.out.println("event received: %s".formatted(event)); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /lambda/src/test/java/airhacks/InvokeLambdaIT.java: -------------------------------------------------------------------------------- 1 | package airhacks; 2 | import static org.junit.jupiter.api.Assertions.assertNull; 3 | 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.junit.jupiter.api.Test; 6 | import software.amazon.awssdk.services.lambda.LambdaClient; 7 | import software.amazon.awssdk.services.lambda.model.InvocationType; 8 | import software.amazon.awssdk.services.lambda.model.InvokeRequest; 9 | import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; 10 | import software.amazon.awssdk.core.SdkBytes; 11 | 12 | public class InvokeLambdaIT { 13 | LambdaClient client; 14 | 15 | @BeforeEach 16 | public void initClient() { 17 | var credentials = DefaultCredentialsProvider.builder().build(); 18 | this.client = LambdaClient.builder() 19 | .credentialsProvider(credentials) 20 | .build(); 21 | } 22 | 23 | @Test 24 | public void invokeLambdaAsynchronously() { 25 | String json = "{\"user\":\"duke\"}"; 26 | SdkBytes payload = SdkBytes.fromUtf8String(json); 27 | 28 | InvokeRequest request = InvokeRequest.builder() 29 | .functionName("airhacks_lambda_greetings_boundary_Greetings") 30 | .payload(payload) 31 | .invocationType(InvocationType.REQUEST_RESPONSE) 32 | .build(); 33 | 34 | var response = this.client.invoke(request); 35 | var error = response.functionError(); 36 | assertNull(error); 37 | var value = response.payload().asUtf8String(); 38 | System.out.println("Function executed. Response: " + value); 39 | } 40 | } 41 | --------------------------------------------------------------------------------