├── .github └── workflows │ ├── graalvm.yml │ └── maven.yml ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── imgs ├── diagram.png ├── execution-environment.png ├── performance_results.png ├── xray-cold.png └── xray-warm.png ├── infrastructure ├── .gitignore ├── Dockerfile ├── README.md ├── cdk.context.json ├── cdk.json ├── pom.xml └── src │ └── main │ └── java │ └── software │ └── amazonaws │ └── example │ └── infrastructure │ ├── DashboardStack.java │ ├── InfrastructureApp.java │ └── InfrastructureStack.java ├── load-test ├── generator.js ├── load-test.yml └── run-load-test.sh ├── mvnw ├── mvnw.cmd ├── pom.xml └── software └── products ├── pom.xml └── src ├── assembly └── zip.xml ├── main ├── config │ └── bootstrap ├── java │ └── software │ │ └── amazonaws │ │ └── example │ │ └── product │ │ ├── entrypoints │ │ ├── ApiGatewayDeleteProductRequestHandler.java │ │ ├── ApiGatewayGetAllProductRequestHandler.java │ │ ├── ApiGatewayGetProductRequestHandler.java │ │ └── ApiGatewayPutProductRequestHandler.java │ │ ├── model │ │ ├── Product.java │ │ └── Products.java │ │ └── store │ │ ├── ProductStore.java │ │ └── dynamodb │ │ ├── DynamoDbProductStore.java │ │ └── ProductMapper.java └── resources │ ├── META-INF │ └── native-image │ │ ├── com.amazonaws │ │ ├── aws-lambda-java-core │ │ │ └── reflect-config.json │ │ ├── aws-lambda-java-events │ │ │ └── reflect-config.json │ │ ├── aws-lambda-java-runtime-interface-client │ │ │ ├── jni-config.json │ │ │ ├── reflect-config.json │ │ │ └── resource-config.json │ │ └── aws-lambda-java-serialization │ │ │ └── reflect-config.json │ │ └── reflect-config.json │ └── simplelogger.properties └── test └── java └── software └── amazonaws └── example └── product └── entrypoints ├── ApiGatewayGetAllProductRequestHandlerTest.java ├── ApiGatewayGetProductRequestHandlerTest.java ├── ApiGatewayPutProductRequestHandlerTest.java ├── StandardOutLambdaLogger.java └── TestContext.java /.github/workflows/graalvm.yml: -------------------------------------------------------------------------------- 1 | name: GraalVM Community Edition build 2 | on: [ push, pull_request ] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - uses: graalvm/setup-graalvm@v1 9 | with: 10 | version: 'latest' 11 | java-version: '17' 12 | components: 'native-image' 13 | github-token: ${{ secrets.GITHUB_TOKEN }} 14 | - name: Using versions 15 | run: | 16 | echo "GRAALVM_HOME: $GRAALVM_HOME" 17 | echo "JAVA_HOME: $JAVA_HOME" 18 | java --version 19 | gu --version 20 | native-image --version 21 | - name: Compile function 22 | run: | 23 | mvn -B package --file software/products/pom.xml -P native-image -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 17 20 | uses: actions/setup-java@v2 21 | with: 22 | java-version: '17' 23 | distribution: 'adopt' 24 | cache: maven 25 | - name: Build with Maven 26 | run: mvn -B package --file software/products/pom.xml 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .classpath.txt 3 | target 4 | .classpath 5 | .project 6 | .idea 7 | .settings 8 | .vscode 9 | *.iml 10 | 11 | # CDK asset staging directory 12 | .cdk.staging 13 | cdk.out -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar 19 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Serverless GraalVM Demo 2 | 3 | ![build](https://github.com/aws-samples/serverless-graalvm-demo/actions/workflows/maven.yml/badge.svg) 4 | 5 |

6 | Architecture diagram 7 |

8 | 9 | This is a simple serverless application built in Java and uses the GraalVM native-image tool. It consists of an 10 | [Amazon API Gateway](https://aws.amazon.com/api-gateway/) backed by four [AWS Lambda](https://aws.amazon.com/lambda/) 11 | functions and an [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) table for storage. 12 | 13 | ## Requirements 14 | 15 | - [AWS CLI](https://aws.amazon.com/cli/) 16 | - [AWS CDK](https://aws.amazon.com/cdk/) 17 | - Java 21 18 | - Maven 3.5 + 19 | - [Artillery](https://www.artillery.io/) for load-testing the application 20 | 21 | ## Software 22 | 23 | Within the software folder is the products maven project. This single maven project contains all the code for all four 24 | Lambda functions. It uses the hexagonal architecture pattern to decouple the entry points, from the main domain logic 25 | and the storage logic. 26 | 27 | ### Custom Runtime 28 | 29 | The GraalVM native-image tool will produce a stand-alone executable binary. This does not require the JVM to run. To run 30 | our application on Lambda we must make 31 | a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html) 32 | and implement the [Lambda Runtime API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html). This is done by 33 | including the `aws-lambda-java-runtime-interface-client` dependency in our project. 34 | The [maven assembly build plugin](https://github.com/aws-samples/serverless-graalvm-demo/blob/main/software/products/src/assembly/zip.xml) 35 | is used to create a zip file which includes the executable binary as well as the entry 36 | point [bootstrap](https://github.com/aws-samples/serverless-graalvm-demo/blob/main/software/products/src/main/config/bootstrap) 37 | file. 38 | 39 |

40 | AWS Lambda execution environment 41 |

42 | 43 | ## Infrastructure 44 | 45 | ### Deployment 46 | 47 | Deploy the demo to your AWS account using [AWS CDK](https://aws.amazon.com/cdk/). 48 | 49 | ```bash 50 | cdk deploy --all 51 | ``` 52 | 53 | The command `cdk deploy` will first build the products maven project using a docker build image with all the required 54 | GraalVM tools. Then it will use AWS CloudFormation to deploy the resources to your account. 55 | 56 | CDK will create an output of the API Gateway endpoint URL for future use in our load tests. 57 | 58 | ## Load Test 59 | 60 | [Artillery](https://www.artillery.io/) is used to make 300 requests / second for 10 minutes to our API endpoints. You 61 | can run this with the following command. 62 | 63 | ```bash 64 | cd load-test 65 | ./run-load-test.sh 66 | ``` 67 | 68 | This is a demanding load test, to change the rate alter the `arrivalRate` value in `load-test.yml`. 69 | 70 | ### CloudWatch Logs Insights 71 | 72 | Using this CloudWatch Logs Insights query you can analyse the latency of the requests made to the Lambda functions. 73 | 74 | The query separates cold starts from other requests and then gives you p50, p90 and p99 percentiles. 75 | 76 | ``` 77 | filter @type="REPORT" 78 | | fields greatest(@initDuration, 0) + @duration as duration, ispresent(@initDuration) as coldStart 79 | | stats count(*) as count, pct(duration, 50) as p50, pct(duration, 90) as p90, pct(duration, 99) as p99, max(duration) as max by coldStart 80 | ``` 81 | 82 |

83 | CloudWatch Logs Insights results 84 |

85 | 86 | ## AWS X-Ray Tracing 87 | 88 | You can add additional detail to your X-Ray tracing by adding a TracingInterceptor to your AWS SDK clients. Here is the 89 | code for my DynamoDbClient from 90 | the [DynamoDbProductStore](https://github.com/aws-samples/serverless-graalvm-demo/blob/aws-xray-support/software/products/src/main/java/software/amazonaws/example/product/store/dynamodb/DynamoDbProductStore.java) 91 | class. 92 | 93 | ```java 94 | private final DynamoDbClient dynamoDbClient=DynamoDbClient.builder() 95 | .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) 96 | .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) 97 | .overrideConfiguration(ClientOverrideConfiguration.builder() 98 | .addExecutionInterceptor(new TracingInterceptor()) 99 | .build()) 100 | .build(); 101 | ``` 102 | 103 | Example cold start trace 104 | 105 |

106 | Cold start X-Ray trace 107 |

108 | 109 | Example warm start trace 110 | 111 |

112 | Warm start X-Ray trace 113 |

114 | 115 | ## 👀 With other languages 116 | 117 | You can find implementations of this project in other languages here: 118 | 119 | * [🦀 Rust](https://github.com/aws-samples/serverless-rust-demo) 120 | * [🏗️ TypeScript](https://github.com/aws-samples/serverless-typescript-demo) 121 | * [🐿️ Go](https://github.com/aws-samples/serverless-go-demo) 122 | * [⭐ Groovy](https://github.com/aws-samples/serverless-groovy-demo) 123 | * [🤖 Kotlin](https://github.com/aws-samples/serverless-kotlin-demo) 124 | * [🥅 .NET](https://github.com/aws-samples/serverless-dotnet-demo) 125 | 126 | ## Security 127 | 128 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 129 | 130 | ## License 131 | 132 | This library is licensed under the MIT-0 License. See the LICENSE file. 133 | 134 | -------------------------------------------------------------------------------- /imgs/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/imgs/diagram.png -------------------------------------------------------------------------------- /imgs/execution-environment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/imgs/execution-environment.png -------------------------------------------------------------------------------- /imgs/performance_results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/imgs/performance_results.png -------------------------------------------------------------------------------- /imgs/xray-cold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/imgs/xray-cold.png -------------------------------------------------------------------------------- /imgs/xray-warm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-graalvm-demo/8146742a52f9aa749afd42e2af7909e158329641/imgs/xray-warm.png -------------------------------------------------------------------------------- /infrastructure/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath.txt 2 | target 3 | .classpath 4 | .project 5 | .idea 6 | .settings 7 | .vscode 8 | *.iml 9 | 10 | # CDK asset staging directory 11 | .cdk.staging 12 | cdk.out 13 | -------------------------------------------------------------------------------- /infrastructure/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=linux/amd64 amazonlinux:2023 2 | 3 | RUN yum -y update \ 4 | && yum install -y unzip tar gzip bzip2-devel ed gcc gcc-c++ gcc-gfortran \ 5 | less libcurl-devel openssl openssl-devel readline-devel xz-devel \ 6 | zlib-devel glibc-static zlib-static \ 7 | && rm -rf /var/cache/yum 8 | 9 | # Graal VM 10 | ENV GRAAL_VERSION 21.0.2 11 | ENV GRAAL_FILENAME graalvm-community-jdk-${GRAAL_VERSION}_linux-x64_bin.tar.gz 12 | RUN curl -4 -L https://github.com/graalvm/graalvm-ce-builds/releases/download/jdk-${GRAAL_VERSION}/${GRAAL_FILENAME} | tar -xvz 13 | RUN mv graalvm-community-openjdk-${GRAAL_VERSION}* /usr/lib/graalvm 14 | ENV JAVA_HOME /usr/lib/graalvm 15 | 16 | # Maven 17 | ENV MVN_VERSION 3.9.8 18 | ENV MVN_FOLDERNAME apache-maven-${MVN_VERSION} 19 | ENV MVN_FILENAME apache-maven-${MVN_VERSION}-bin.tar.gz 20 | RUN curl -4 -L https://archive.apache.org/dist/maven/maven-3/${MVN_VERSION}/binaries/${MVN_FILENAME} | tar -xvz 21 | RUN mv $MVN_FOLDERNAME /usr/lib/maven 22 | RUN ln -s /usr/lib/maven/bin/mvn /usr/bin/mvn 23 | 24 | # AWS Lambda Builders 25 | #RUN amazon-linux-extras enable python3.8 26 | RUN yum clean metadata && yum -y install python3-pip 27 | RUN pip3 install aws-lambda-builders 28 | 29 | VOLUME /project 30 | WORKDIR /project 31 | 32 | RUN ln -s /usr/lib/graalvm/bin/native-image /usr/bin/native-image 33 | 34 | ENV JAVA_HOME /usr/lib/graalvm 35 | 36 | ENTRYPOINT ["sh"] -------------------------------------------------------------------------------- /infrastructure/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to your CDK Java project! 2 | 3 | This is a blank project for Java development with CDK. 4 | 5 | The `cdk.json` file tells the CDK Toolkit how to execute your app. 6 | 7 | It is a [Maven](https://maven.apache.org/) based project, so you can open this project with any Maven compatible Java IDE to build and run tests. 8 | 9 | ## Useful commands 10 | 11 | * `mvn package` compile and run tests 12 | * `cdk ls` list all stacks in the app 13 | * `cdk synth` emits the synthesized CloudFormation template 14 | * `cdk deploy` deploy this stack to your default AWS account/region 15 | * `cdk diff` compare deployed stack with current state 16 | * `cdk docs` open CDK documentation 17 | 18 | Enjoy! 19 | -------------------------------------------------------------------------------- /infrastructure/cdk.context.json: -------------------------------------------------------------------------------- 1 | { 2 | "acknowledged-issue-numbers": [ 3 | 19836 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /infrastructure/cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "mvn -e -q compile exec:java", 3 | "context": { 4 | "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, 5 | "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, 6 | "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, 7 | "@aws-cdk/core:stackRelativeExports": false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /infrastructure/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | software.amazonaws.example 7 | infrastructure 8 | 0.1 9 | 10 | 11 | UTF-8 12 | 2.151.0 13 | 14 | 15 | 16 | 17 | 18 | org.apache.maven.plugins 19 | maven-compiler-plugin 20 | 3.13.0 21 | 22 | 21 23 | 21 24 | 25 | 26 | 27 | 28 | org.codehaus.mojo 29 | exec-maven-plugin 30 | 3.3.0 31 | 32 | software.amazonaws.example.infrastructure.InfrastructureApp 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | software.amazon.awscdk 42 | aws-cdk-lib 43 | ${cdk.version} 44 | 45 | 46 | software.constructs 47 | constructs 48 | 10.3.0 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /infrastructure/src/main/java/software/amazonaws/example/infrastructure/DashboardStack.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.infrastructure; 5 | 6 | import software.amazon.awscdk.Duration; 7 | import software.amazon.awscdk.Stack; 8 | import software.amazon.awscdk.StackProps; 9 | import software.amazon.awscdk.services.cloudwatch.Dashboard; 10 | import software.amazon.awscdk.services.cloudwatch.GraphWidget; 11 | import software.amazon.awscdk.services.cloudwatch.GraphWidgetView; 12 | import software.amazon.awscdk.services.cloudwatch.IMetric; 13 | import software.amazon.awscdk.services.cloudwatch.IWidget; 14 | import software.amazon.awscdk.services.cloudwatch.MathExpression; 15 | import software.amazon.awscdk.services.cloudwatch.MetricOptions; 16 | import software.amazon.awscdk.services.lambda.Function; 17 | import software.constructs.Construct; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Collections; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.stream.Collectors; 24 | 25 | public class DashboardStack extends Stack { 26 | 27 | public DashboardStack(final Construct parent, final String id, List functions) { 28 | this(parent, id, null, functions); 29 | } 30 | 31 | public DashboardStack(final Construct parent, final String id, final StackProps props, final List functions) { 32 | super(parent, id, props); 33 | 34 | List p50DurationMetrics = functions.stream() 35 | .map(f -> f.metricDuration(MetricOptions.builder() 36 | .label(f.getFunctionName()) 37 | .period(Duration.minutes(1)) 38 | .statistic("p50") 39 | .build())) 40 | .collect(Collectors.toList()); 41 | 42 | IWidget p50DurationGraph = GraphWidget.Builder.create() 43 | .title("P50 Duration") 44 | .left(p50DurationMetrics) 45 | .view(GraphWidgetView.TIME_SERIES) 46 | .build(); 47 | 48 | List p90DurationMetrics = functions.stream() 49 | .map(f -> f.metricDuration(MetricOptions.builder() 50 | .label(f.getFunctionName()) 51 | .period(Duration.minutes(1)) 52 | .statistic("p90") 53 | .build())) 54 | .collect(Collectors.toList()); 55 | 56 | IWidget p90DurationGraph = GraphWidget.Builder.create() 57 | .title("P90 Duration") 58 | .left(p90DurationMetrics) 59 | .view(GraphWidgetView.TIME_SERIES) 60 | .build(); 61 | 62 | Function function; 63 | List errorRates = new ArrayList<>(); 64 | for (int i = 0; i < functions.size(); i++) { 65 | function = functions.get(i); 66 | errorRates.add(MathExpression.Builder.create() 67 | .expression(String.format("(errors%s / invocations%s) * 100", i, i)) 68 | .usingMetrics(Map.of("errors" + i, function.metricErrors(), 69 | "invocations" + i, function.metricInvocations())) 70 | .label(function.getFunctionName() + " Error Rate") 71 | .build()); 72 | } 73 | 74 | IWidget errorRateGraph = GraphWidget.Builder.create() 75 | .title("Error Rates") 76 | .left(errorRates) 77 | .view(GraphWidgetView.TIME_SERIES) 78 | .build(); 79 | 80 | List concurrentExecutionsMetrics = functions.stream() 81 | .map(f -> f.metric("ConcurrentExecutions", MetricOptions.builder() 82 | .label(f.getFunctionName()) 83 | .period(Duration.minutes(1)) 84 | .statistic("Average") 85 | .build())) 86 | .collect(Collectors.toList()); 87 | 88 | IWidget concurrentExecutionsGraph = GraphWidget.Builder.create() 89 | .title("ConcurrentExecutions") 90 | .left(concurrentExecutionsMetrics) 91 | .view(GraphWidgetView.TIME_SERIES) 92 | .build(); 93 | 94 | List widgets = List.of(p90DurationGraph, p50DurationGraph, errorRateGraph, concurrentExecutionsGraph); 95 | Dashboard dashboard = Dashboard.Builder.create(this, "ProductsDashboard") 96 | .dashboardName("ProductsDashboard") 97 | .widgets(Collections.singletonList(widgets)) 98 | .build(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /infrastructure/src/main/java/software/amazonaws/example/infrastructure/InfrastructureApp.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.infrastructure; 5 | 6 | import software.amazon.awscdk.App; 7 | import software.amazon.awscdk.Environment; 8 | import software.amazon.awscdk.StackProps; 9 | import software.amazon.awscdk.services.lambda.Function; 10 | 11 | import java.util.List; 12 | 13 | public class InfrastructureApp { 14 | public static void main(final String[] args) { 15 | App app = new App(); 16 | 17 | InfrastructureStack infrastructureStack = new InfrastructureStack(app, "GraalVMPerfTestStack", StackProps.builder() 18 | .env(Environment.builder() 19 | .account(System.getenv("CDK_DEFAULT_ACCOUNT")) 20 | .region(System.getenv("CDK_DEFAULT_REGION")) 21 | .build()) 22 | .build()); 23 | 24 | List functions = infrastructureStack.getFunctions(); 25 | 26 | new DashboardStack(app, "GraalVMDashboard", StackProps.builder() 27 | .env(Environment.builder() 28 | .account(System.getenv("CDK_DEFAULT_ACCOUNT")) 29 | .region(System.getenv("CDK_DEFAULT_REGION")) 30 | .build()) 31 | .build(), 32 | functions); 33 | 34 | app.synth(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /infrastructure/src/main/java/software/amazonaws/example/infrastructure/InfrastructureStack.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.infrastructure; 5 | 6 | import software.amazon.awscdk.Stack; 7 | import software.amazon.awscdk.*; 8 | import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpLambdaIntegration; 9 | import software.amazon.awscdk.services.apigatewayv2.AddRoutesOptions; 10 | import software.amazon.awscdk.services.apigatewayv2.HttpApi; 11 | import software.amazon.awscdk.services.apigatewayv2.HttpMethod; 12 | import software.amazon.awscdk.services.dynamodb.Attribute; 13 | import software.amazon.awscdk.services.dynamodb.AttributeType; 14 | import software.amazon.awscdk.services.dynamodb.BillingMode; 15 | import software.amazon.awscdk.services.dynamodb.Table; 16 | import software.amazon.awscdk.services.lambda.Code; 17 | import software.amazon.awscdk.services.lambda.Function; 18 | import software.amazon.awscdk.services.lambda.Runtime; 19 | import software.amazon.awscdk.services.lambda.Tracing; 20 | import software.amazon.awscdk.services.logs.RetentionDays; 21 | import software.amazon.awscdk.services.s3.assets.AssetOptions; 22 | import software.constructs.Construct; 23 | 24 | import java.util.*; 25 | 26 | import static java.util.Collections.singletonList; 27 | import static software.amazon.awscdk.BundlingOutput.ARCHIVED; 28 | 29 | public class InfrastructureStack extends Stack { 30 | 31 | List functions = new ArrayList<>(); 32 | 33 | public InfrastructureStack(final Construct parent, final String id) { 34 | this(parent, id, null); 35 | } 36 | 37 | public InfrastructureStack(final Construct parent, final String id, final StackProps props) { 38 | super(parent, id, props); 39 | 40 | Table productsTable = Table.Builder.create(this, "Products") 41 | .tableName("Products") 42 | .partitionKey(Attribute.builder() 43 | .type(AttributeType.STRING) 44 | .name("PK") 45 | .build()) 46 | .billingMode(BillingMode.PAY_PER_REQUEST) 47 | .build(); 48 | 49 | List functionOnePackagingInstructions = Arrays.asList( 50 | "-c", 51 | "cd products " + 52 | "&& mvn clean install -P native-image " 53 | + "&& cp /asset-input/products/target/function.zip /asset-output/" 54 | ); 55 | 56 | BundlingOptions builderOptions = BundlingOptions.builder() 57 | .command(functionOnePackagingInstructions) 58 | //Use local Dockerfile in infrastructure folder with GraalVM build tools 59 | .image(DockerImage.fromBuild(".")) 60 | .volumes(singletonList( 61 | DockerVolume.builder() 62 | .hostPath(System.getProperty("user.home") + "/.m2/") 63 | .containerPath("/root/.m2/") 64 | .build() 65 | )) 66 | .user("root") 67 | .outputType(ARCHIVED) 68 | .build(); 69 | 70 | Map environmentVariables = new HashMap<>(); 71 | environmentVariables.put("PRODUCT_TABLE_NAME", productsTable.getTableName()); 72 | 73 | Function getProductFunction = Function.Builder.create(this, "GetProductFunction") 74 | .runtime(Runtime.PROVIDED_AL2023) 75 | .code(Code.fromAsset("../software/", AssetOptions.builder() 76 | .bundling(builderOptions) 77 | .build())) 78 | .handler("software.amazonaws.example.product.entrypoints.ApiGatewayGetProductRequestHandler") 79 | .memorySize(256) 80 | .environment(environmentVariables) 81 | .logRetention(RetentionDays.ONE_WEEK) 82 | .tracing(Tracing.ACTIVE) 83 | // .architecture(Architecture.ARM_64) 84 | .build(); 85 | 86 | Function getAllProductFunction = Function.Builder.create(this, "GetAllProductFunction") 87 | .runtime(Runtime.PROVIDED_AL2023) 88 | .code(Code.fromAsset("../software/", AssetOptions.builder() 89 | .bundling(builderOptions) 90 | .build())) 91 | .handler("software.amazonaws.example.product.entrypoints.ApiGatewayGetAllProductRequestHandler") 92 | .memorySize(256) 93 | .environment(environmentVariables) 94 | .logRetention(RetentionDays.ONE_WEEK) 95 | .tracing(Tracing.ACTIVE) 96 | // .architecture(Architecture.ARM_64) 97 | .build(); 98 | 99 | Function putProductFunction = Function.Builder.create(this, "PutProductFunction") 100 | .runtime(Runtime.PROVIDED_AL2023) 101 | .code(Code.fromAsset("../software/", AssetOptions.builder() 102 | .bundling(builderOptions) 103 | .build())) 104 | .handler("software.amazonaws.example.product.entrypoints.ApiGatewayPutProductRequestHandler") 105 | .memorySize(256) 106 | .environment(environmentVariables) 107 | .logRetention(RetentionDays.ONE_WEEK) 108 | .tracing(Tracing.ACTIVE) 109 | // .architecture(Architecture.ARM_64) 110 | .build(); 111 | 112 | Function deleteProductFunction = Function.Builder.create(this, "DeleteProductFunction") 113 | .runtime(Runtime.PROVIDED_AL2023) 114 | .code(Code.fromAsset("../software/", AssetOptions.builder() 115 | .bundling(builderOptions) 116 | .build())) 117 | .handler("software.amazonaws.example.product.entrypoints.ApiGatewayDeleteProductRequestHandler") 118 | .memorySize(256) 119 | .environment(environmentVariables) 120 | .logRetention(RetentionDays.ONE_WEEK) 121 | .tracing(Tracing.ACTIVE) 122 | // .architecture(Architecture.ARM_64) 123 | .build(); 124 | 125 | productsTable.grantReadData(getProductFunction); 126 | productsTable.grantReadData(getAllProductFunction); 127 | productsTable.grantWriteData(putProductFunction); 128 | productsTable.grantWriteData(deleteProductFunction); 129 | 130 | HttpApi httpApi = HttpApi.Builder.create(this, "ProductsApi") 131 | .apiName("ProductsApi") 132 | .build(); 133 | 134 | httpApi.addRoutes(AddRoutesOptions.builder() 135 | .path("/{id}") 136 | .methods(singletonList(HttpMethod.GET)) 137 | .integration(new HttpLambdaIntegration("HttpApiGatewayGetProductFunction", getProductFunction)) 138 | .build()); 139 | 140 | httpApi.addRoutes(AddRoutesOptions.builder() 141 | .path("/") 142 | .methods(singletonList(HttpMethod.GET)) 143 | .integration(new HttpLambdaIntegration("HttpApiGatewayGetAllProductsFunction", getAllProductFunction)) 144 | .build()); 145 | 146 | httpApi.addRoutes(AddRoutesOptions.builder() 147 | .path("/{id}") 148 | .methods(singletonList(HttpMethod.PUT)) 149 | .integration(new HttpLambdaIntegration("HttpApiGatewayPutProductFunction", putProductFunction)) 150 | .build()); 151 | 152 | httpApi.addRoutes(AddRoutesOptions.builder() 153 | .path("/{id}") 154 | .methods(singletonList(HttpMethod.DELETE)) 155 | .integration(new HttpLambdaIntegration("HttpApiGatewayDeleteProductFunction", deleteProductFunction)) 156 | .build()); 157 | 158 | functions.add(getAllProductFunction); 159 | functions.add(getProductFunction); 160 | functions.add(putProductFunction); 161 | functions.add(deleteProductFunction); 162 | 163 | CfnOutput apiUrl = CfnOutput.Builder.create(this, "ApiUrl") 164 | .exportName("ApiUrl") 165 | .value(httpApi.getApiEndpoint()) 166 | .build(); 167 | } 168 | 169 | public List getFunctions() { 170 | return Collections.unmodifiableList(functions); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /load-test/generator.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | 3 | const COLORS = [ 4 | "Red", "Green", "Blue", "Yellow", "Orange", "Purple", "Pink", "Brown", 5 | "Black", "White", "Gray", "Silver", "Gold", "Cyan", "Magenta", "Maroon", 6 | "Navy", "Olive", "Teal", "Aqua", "Lime", "Coral", "Aquamarine", 7 | "Turquoise", "Violet", "Indigo", "Plum", "Crimson", "Salmon", "Coral", 8 | "Khaki", "Beige", 9 | ]; 10 | 11 | const PRODUCTS = [ 12 | "Shoes", "Sweatshirts", "Hats", "Pants", "Shirts", "T-Shirts", "Trousers", 13 | "Jackets", "Shorts", "Skirts", "Dresses", "Coats", "Jeans", "Blazers", 14 | "Socks", "Gloves", "Belts", "Bags", "Shoes", "Sunglasses", "Watches", 15 | "Jewelry", "Ties", "Hair Accessories", "Makeup", "Accessories", 16 | ]; 17 | 18 | module.exports = { 19 | generateProduct: function(context, events, done) { 20 | const color = COLORS[Math.floor(Math.random() * COLORS.length)]; 21 | const name = PRODUCTS[Math.floor(Math.random() * PRODUCTS.length)]; 22 | 23 | context.vars.id = crypto.randomUUID(); 24 | context.vars.name = `${color} ${name}`; 25 | context.vars.price = Math.round(Math.random() * 10000) / 100; 26 | 27 | return done(); 28 | }, 29 | }; -------------------------------------------------------------------------------- /load-test/load-test.yml: -------------------------------------------------------------------------------- 1 | config: 2 | target: "{{ $processEnvironment.API_URL }}" 3 | processor: "generator.js" 4 | phases: 5 | - duration: 60 6 | arrivalRate: 50 7 | name: "Generating products, retrieving & deleting them" 8 | 9 | scenarios: 10 | - name: "Generate products" 11 | weight: 8 12 | flow: 13 | - function: "generateProduct" 14 | - put: 15 | url: "/{{ id }}" 16 | headers: 17 | Content-Type: "application/json" 18 | json: 19 | id: "{{ id }}" 20 | name: "{{ name }}" 21 | price: "{{ price }}" 22 | - get: 23 | url: "/{{ id }}" 24 | - think: 3 25 | - delete: 26 | url: "/{{ id }}" 27 | - name: "Get products" 28 | weight: 2 29 | flow: 30 | - get: 31 | url: "/" -------------------------------------------------------------------------------- /load-test/run-load-test.sh: -------------------------------------------------------------------------------- 1 | STACK_NAME=GraalVMPerfTestStack 2 | 3 | API_URL=$(aws cloudformation describe-stacks --stack-name $STACK_NAME \ 4 | --query 'Stacks[0].Outputs[?OutputKey==`ApiUrl`].OutputValue' \ 5 | --output text) 6 | 7 | artillery run load-test.yml --target "$API_URL" -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | software.amazonaws.example 5 | serverless-graalvm-demo 6 | 1.0 7 | pom 8 | Serverless GraalVM Demo 9 | 10 | 11 | infrastructure 12 | software/products 13 | 14 | 15 | -------------------------------------------------------------------------------- /software/products/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | software.amazonaws.example 5 | products 6 | 1.0 7 | jar 8 | Products 9 | 10 | 17 11 | 17 12 | UTF-8 13 | 2.28.7 14 | 15 | 16 | 17 | 18 | 19 | software.amazon.awssdk 20 | bom 21 | ${aws.java.sdk.version} 22 | pom 23 | import 24 | 25 | 26 | com.amazonaws 27 | aws-xray-recorder-sdk-bom 28 | 2.17.0 29 | pom 30 | import 31 | 32 | 33 | 34 | 35 | 36 | 37 | com.amazonaws 38 | aws-lambda-java-core 39 | 1.2.3 40 | 41 | 42 | com.amazonaws 43 | aws-lambda-java-events 44 | 3.13.0 45 | 46 | 47 | com.amazonaws 48 | aws-lambda-java-runtime-interface-client 49 | 2.5.1 50 | 51 | 52 | 53 | software.amazon.awssdk 54 | dynamodb 55 | 56 | 57 | software.amazon.awssdk 58 | netty-nio-client 59 | 60 | 61 | software.amazon.awssdk 62 | apache-client 63 | 64 | 65 | 66 | 67 | software.amazon.awssdk 68 | aws-crt-client 69 | 70 | 71 | org.slf4j 72 | slf4j-simple 73 | 2.0.13 74 | 75 | 76 | org.graalvm.sdk 77 | nativeimage 78 | 24.0.2 79 | provided 80 | 81 | 82 | com.amazonaws 83 | aws-xray-recorder-sdk-core 84 | 85 | 86 | com.amazonaws 87 | aws-xray-recorder-sdk-apache-http 88 | 89 | 90 | com.amazonaws 91 | aws-xray-recorder-sdk-aws-sdk 92 | 93 | 94 | com.amazonaws 95 | aws-xray-recorder-sdk-aws-sdk-instrumentor 96 | 97 | 98 | com.amazonaws 99 | aws-xray-recorder-sdk-aws-sdk-v2 100 | 101 | 102 | 103 | org.junit.jupiter 104 | junit-jupiter 105 | 5.10.3 106 | test 107 | 108 | 109 | org.assertj 110 | assertj-core 111 | 3.26.3 112 | test 113 | 114 | 115 | org.mockito 116 | mockito-core 117 | 5.12.0 118 | test 119 | 120 | 121 | org.skyscreamer 122 | jsonassert 123 | 1.5.3 124 | test 125 | 126 | 127 | 128 | 129 | 130 | 131 | org.apache.maven.plugins 132 | maven-shade-plugin 133 | 3.6.0 134 | 135 | false 136 | product 137 | 138 | 140 | com.amazonaws.services.lambda.runtime.api.client.AWSLambda 141 | 142 | 143 | 144 | 145 | 146 | package 147 | 148 | shade 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | native-image 159 | 160 | 161 | 162 | org.graalvm.buildtools 163 | native-maven-plugin 164 | 0.10.2 165 | true 166 | 167 | 168 | build-native 169 | 170 | build 171 | 172 | package 173 | 174 | 175 | 176 | product-binary 177 | com.amazonaws.services.lambda.runtime.api.client.AWSLambda 178 | 179 | --enable-url-protocols=http 180 | 181 | 182 | 183 | 184 | org.apache.maven.plugins 185 | maven-assembly-plugin 186 | 3.7.1 187 | 188 | 189 | zip-assembly 190 | package 191 | 192 | single 193 | 194 | 195 | function 196 | 197 | src/assembly/zip.xml 198 | 199 | false 200 | false 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | -------------------------------------------------------------------------------- /software/products/src/assembly/zip.xml: -------------------------------------------------------------------------------- 1 | 4 | lambda-package 5 | 6 | zip 7 | 8 | false 9 | 10 | 11 | ${project.build.directory}${file.separator}product-binary 12 | ${file.separator} 13 | product-binary 14 | 777 15 | 16 | 17 | src${file.separator}main${file.separator}config${file.separator}bootstrap 18 | ${file.separator} 19 | bootstrap 20 | 777 21 | 22 | 23 | ${project.build.directory}${file.separator}libaws-crt-jni.so 24 | ${file.separator} 25 | libaws-crt-jni.so 26 | 777 27 | 28 | 29 | -------------------------------------------------------------------------------- /software/products/src/main/config/bootstrap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ./product-binary $_HANDLER -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/entrypoints/ApiGatewayDeleteProductRequestHandler.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.Context; 7 | import com.amazonaws.services.lambda.runtime.RequestHandler; 8 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 9 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import software.amazonaws.example.product.store.ProductStore; 13 | import software.amazonaws.example.product.store.dynamodb.DynamoDbProductStore; 14 | 15 | import java.util.Map; 16 | 17 | import static software.amazon.awssdk.http.Header.CONTENT_TYPE; 18 | 19 | public class ApiGatewayDeleteProductRequestHandler implements RequestHandler { 20 | 21 | private static final Logger logger = LoggerFactory.getLogger(ApiGatewayDeleteProductRequestHandler.class); 22 | private final ProductStore productStore = new DynamoDbProductStore(); 23 | 24 | @Override 25 | public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { 26 | String id = event.getPathParameters().get("id"); 27 | if (id == null) { 28 | logger.warn("Missing 'id' parameter in path"); 29 | return APIGatewayV2HTTPResponse.builder() 30 | .withStatusCode(400) 31 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 32 | .withBody("{ \"message\": \"Missing 'id' parameter in path\" }") 33 | .build(); 34 | } 35 | 36 | try { 37 | productStore.deleteProduct(id); 38 | } catch (Exception e) { 39 | logger.error(e.getMessage()); 40 | return APIGatewayV2HTTPResponse.builder() 41 | .withStatusCode(500) 42 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 43 | .withBody("{\"message\": \"Failed to delete product\"}") 44 | .build(); 45 | } 46 | 47 | return APIGatewayV2HTTPResponse.builder() 48 | .withStatusCode(200) 49 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 50 | .withBody("{\"message\": \"Product deleted\"}") 51 | .build(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/entrypoints/ApiGatewayGetAllProductRequestHandler.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.Context; 7 | import com.amazonaws.services.lambda.runtime.RequestHandler; 8 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 9 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 10 | import com.fasterxml.jackson.core.JsonProcessingException; 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import software.amazonaws.example.product.model.Products; 15 | import software.amazonaws.example.product.store.ProductStore; 16 | import software.amazonaws.example.product.store.dynamodb.DynamoDbProductStore; 17 | 18 | import java.util.Map; 19 | 20 | import static software.amazon.awssdk.http.Header.CONTENT_TYPE; 21 | 22 | public class ApiGatewayGetAllProductRequestHandler implements RequestHandler { 23 | 24 | private static final Logger logger = LoggerFactory.getLogger(ApiGatewayGetAllProductRequestHandler.class); 25 | private final ObjectMapper objectMapper = new ObjectMapper(); 26 | private final ProductStore productStore; 27 | 28 | public ApiGatewayGetAllProductRequestHandler() { 29 | this(new DynamoDbProductStore()); 30 | } 31 | 32 | public ApiGatewayGetAllProductRequestHandler(ProductStore productStore) { 33 | this.productStore = productStore; 34 | } 35 | 36 | @Override 37 | public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { 38 | Products products; 39 | try { 40 | products = productStore.getAllProduct(); 41 | } catch (Exception e) { 42 | logger.error(e.getMessage(), e); 43 | return APIGatewayV2HTTPResponse.builder() 44 | .withStatusCode(500) 45 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 46 | .withBody("{\"message\": \"Failed to get products\"}") 47 | .build(); 48 | } 49 | 50 | try { 51 | return APIGatewayV2HTTPResponse.builder() 52 | .withStatusCode(200) 53 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 54 | .withBody(objectMapper.writeValueAsString(products)) 55 | .build(); 56 | } catch (JsonProcessingException e) { 57 | logger.error(e.getMessage(), e); 58 | return APIGatewayV2HTTPResponse.builder() 59 | .withStatusCode(500) 60 | .build(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/entrypoints/ApiGatewayGetProductRequestHandler.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.Context; 7 | import com.amazonaws.services.lambda.runtime.RequestHandler; 8 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 9 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 10 | import com.fasterxml.jackson.core.JsonProcessingException; 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import software.amazonaws.example.product.store.dynamodb.DynamoDbProductStore; 15 | import software.amazonaws.example.product.model.Product; 16 | import software.amazonaws.example.product.store.ProductStore; 17 | 18 | import java.util.Map; 19 | import java.util.Optional; 20 | 21 | import static software.amazon.awssdk.http.Header.CONTENT_TYPE; 22 | 23 | public class ApiGatewayGetProductRequestHandler implements RequestHandler { 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(ApiGatewayGetProductRequestHandler.class); 26 | private final ObjectMapper objectMapper = new ObjectMapper(); 27 | private final ProductStore productStore; 28 | 29 | public ApiGatewayGetProductRequestHandler() { 30 | this(new DynamoDbProductStore()); 31 | } 32 | 33 | public ApiGatewayGetProductRequestHandler(ProductStore productStore) { 34 | this.productStore = productStore; 35 | } 36 | 37 | @Override 38 | public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { 39 | String id = event.getPathParameters().get("id"); 40 | if (id == null) { 41 | logger.warn("Missing 'id' parameter in path"); 42 | return APIGatewayV2HTTPResponse.builder() 43 | .withStatusCode(400) 44 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 45 | .withBody("{ \"message\": \"Missing 'id' parameter in path\" }") 46 | .build(); 47 | } 48 | 49 | logger.info("Fetching product {}", id); 50 | 51 | Optional product = productStore.getProduct(id); 52 | if (product.isEmpty()) { 53 | logger.warn("No product with id: {}", id); 54 | return APIGatewayV2HTTPResponse.builder() 55 | .withStatusCode(404) 56 | .withBody("{\"message\": \"Product not found\"}") 57 | .build(); 58 | } 59 | 60 | logger.info(product.toString()); 61 | 62 | try { 63 | return APIGatewayV2HTTPResponse.builder() 64 | .withStatusCode(200) 65 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 66 | .withBody(objectMapper.writeValueAsString(product.get())) 67 | .build(); 68 | } catch (JsonProcessingException e) { 69 | return APIGatewayV2HTTPResponse.builder() 70 | .withStatusCode(500) 71 | .build(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/entrypoints/ApiGatewayPutProductRequestHandler.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.Context; 7 | import com.amazonaws.services.lambda.runtime.RequestHandler; 8 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 9 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import software.amazonaws.example.product.model.Product; 14 | import software.amazonaws.example.product.store.ProductStore; 15 | import software.amazonaws.example.product.store.dynamodb.DynamoDbProductStore; 16 | 17 | import java.io.IOException; 18 | import java.util.Map; 19 | 20 | import static software.amazon.awssdk.http.Header.CONTENT_TYPE; 21 | 22 | public class ApiGatewayPutProductRequestHandler implements RequestHandler { 23 | 24 | private static final Logger logger = LoggerFactory.getLogger(ApiGatewayPutProductRequestHandler.class); 25 | private final ObjectMapper objectMapper = new ObjectMapper(); 26 | private final ProductStore productStore; 27 | 28 | public ApiGatewayPutProductRequestHandler() { 29 | this(new DynamoDbProductStore()); 30 | } 31 | 32 | public ApiGatewayPutProductRequestHandler(ProductStore productStore) { 33 | this.productStore = productStore; 34 | } 35 | 36 | @Override 37 | public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { 38 | logger.info("Event body: " + event.getBody()); 39 | 40 | String id = event.getPathParameters().get("id"); 41 | if (id == null) { 42 | logger.warn("Missing 'id' parameter in path"); 43 | return APIGatewayV2HTTPResponse.builder() 44 | .withStatusCode(400) 45 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 46 | .withBody("{ \"message\": \"Missing 'id' parameter in path\" }") 47 | .build(); 48 | } 49 | 50 | if (event.getBody() == null || event.getBody().isEmpty()) { 51 | return APIGatewayV2HTTPResponse.builder() 52 | .withStatusCode(400) 53 | .withBody("{\"message\": \"Empty request body\"}") 54 | .build(); 55 | } 56 | 57 | Product product; 58 | try { 59 | product = objectMapper.readValue(event.getBody(), Product.class); 60 | } catch (IOException e) { 61 | logger.error(e.getMessage()); 62 | return APIGatewayV2HTTPResponse.builder() 63 | .withBody("{\"message\": \"Failed to parse product from request body\"}") 64 | .withStatusCode(400) 65 | .build(); 66 | } 67 | 68 | if (!id.equals(product.getId())) { 69 | logger.error("Product ID in path ({}) does not match product ID in body ({})", id, product.getId()); 70 | return APIGatewayV2HTTPResponse.builder() 71 | .withStatusCode(400) 72 | .withBody("{\"message\": \"Product ID in path does not match product ID in body\"}") 73 | .build(); 74 | } 75 | 76 | logger.info("Parsed: " + product); 77 | 78 | try { 79 | productStore.putProduct(product); 80 | } catch (Exception e) { 81 | logger.error(e.getMessage()); 82 | return APIGatewayV2HTTPResponse.builder() 83 | .withStatusCode(500) 84 | .build(); 85 | } 86 | 87 | return APIGatewayV2HTTPResponse.builder() 88 | .withStatusCode(201) 89 | .withHeaders(Map.of(CONTENT_TYPE, "application/json")) 90 | .withBody("{\"message\": \"Product created\"}") 91 | .build(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/model/Product.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.model; 5 | 6 | import java.math.BigDecimal; 7 | import java.math.RoundingMode; 8 | 9 | public class Product { 10 | 11 | private String id; 12 | private String name; 13 | private BigDecimal price; 14 | 15 | public Product() { 16 | } 17 | 18 | public Product(String id, String name, BigDecimal price) { 19 | this.id = id; 20 | this.name = name; 21 | setPrice(this.price = price); 22 | } 23 | 24 | public String getId() { 25 | return id; 26 | } 27 | 28 | public void setId(String id) { 29 | this.id = id; 30 | } 31 | 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | 40 | public BigDecimal getPrice() { 41 | return price; 42 | } 43 | 44 | public void setPrice(BigDecimal price) { 45 | this.price = price.setScale(2, RoundingMode.HALF_UP); 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Product{" + 51 | "id='" + id + '\'' + 52 | ", name='" + name + '\'' + 53 | ", price=" + price + 54 | '}'; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/model/Products.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.model; 5 | 6 | import java.util.List; 7 | 8 | public class Products { 9 | 10 | private List products; 11 | 12 | public Products() { 13 | } 14 | 15 | public Products(List products) { 16 | this.products = products; 17 | } 18 | 19 | public List getProducts() { 20 | return products; 21 | } 22 | 23 | public void setProducts(List products) { 24 | this.products = products; 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/store/ProductStore.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.store; 5 | 6 | import software.amazonaws.example.product.model.Product; 7 | import software.amazonaws.example.product.model.Products; 8 | 9 | import java.util.Optional; 10 | 11 | public interface ProductStore { 12 | 13 | Optional getProduct(String id); 14 | 15 | void putProduct(Product product); 16 | 17 | void deleteProduct(String id); 18 | 19 | Products getAllProduct(); 20 | } 21 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/store/dynamodb/DynamoDbProductStore.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.store.dynamodb; 5 | 6 | import com.amazonaws.xray.interceptors.TracingInterceptor; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; 10 | import software.amazon.awssdk.core.SdkSystemSetting; 11 | import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; 12 | import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; 13 | import software.amazon.awssdk.regions.Region; 14 | import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; 15 | import software.amazon.awssdk.services.dynamodb.model.AttributeValue; 16 | import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; 17 | import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; 18 | import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; 19 | import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; 20 | import software.amazon.awssdk.services.dynamodb.model.ScanRequest; 21 | import software.amazon.awssdk.services.dynamodb.model.ScanResponse; 22 | import software.amazonaws.example.product.model.Product; 23 | import software.amazonaws.example.product.model.Products; 24 | import software.amazonaws.example.product.store.ProductStore; 25 | 26 | import java.util.ArrayList; 27 | import java.util.Collections; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.Optional; 31 | import java.util.concurrent.ExecutionException; 32 | 33 | public class DynamoDbProductStore implements ProductStore { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(DynamoDbProductStore.class); 36 | private static final String PRODUCT_TABLE_NAME = System.getenv("PRODUCT_TABLE_NAME"); 37 | 38 | private final DynamoDbAsyncClient dynamoDbClient = DynamoDbAsyncClient.builder() 39 | .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) 40 | .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) 41 | .overrideConfiguration(ClientOverrideConfiguration.builder() 42 | .addExecutionInterceptor(new TracingInterceptor()) 43 | .build()) 44 | .httpClientBuilder(AwsCrtAsyncHttpClient.builder()) 45 | .build(); 46 | 47 | @Override 48 | public Optional getProduct(String id) { 49 | try { 50 | GetItemResponse getItemResponse = dynamoDbClient.getItem(GetItemRequest.builder() 51 | .key(Map.of("PK", AttributeValue.builder().s(id).build())) 52 | .tableName(PRODUCT_TABLE_NAME) 53 | .build()) 54 | .get(); 55 | if (getItemResponse.hasItem()) { 56 | return Optional.of(ProductMapper.productFromDynamoDB(getItemResponse.item())); 57 | } else { 58 | return Optional.empty(); 59 | } 60 | } catch (InterruptedException | ExecutionException e) { 61 | logger.error("getItem failed with message {}", e.getMessage()); 62 | return Optional.empty(); 63 | } 64 | } 65 | 66 | @Override 67 | public void putProduct(Product product) { 68 | try { 69 | dynamoDbClient.putItem(PutItemRequest.builder() 70 | .tableName(PRODUCT_TABLE_NAME) 71 | .item(ProductMapper.productToDynamoDb(product)) 72 | .build()).get(); 73 | } catch (InterruptedException | ExecutionException e) { 74 | logger.error("putItem failed with stacktrace", e); 75 | } 76 | } 77 | 78 | @Override 79 | public void deleteProduct(String id) { 80 | try { 81 | dynamoDbClient.deleteItem(DeleteItemRequest.builder() 82 | .tableName(PRODUCT_TABLE_NAME) 83 | .key(Map.of("PK", AttributeValue.builder().s(id).build())) 84 | .build()).get(); 85 | } catch (InterruptedException | ExecutionException e) { 86 | logger.error("Deleting item with Id {} failed with message {}", id, e.getMessage()); 87 | } 88 | } 89 | 90 | @Override 91 | public Products getAllProduct() { 92 | try { 93 | ScanResponse scanResponse = dynamoDbClient.scan(ScanRequest.builder() 94 | .tableName(PRODUCT_TABLE_NAME) 95 | .limit(20) 96 | .build()) 97 | .get(); 98 | 99 | logger.info("Scan returned: {} item(s)", scanResponse.count()); 100 | 101 | List productList = new ArrayList<>(); 102 | 103 | for (Map item : scanResponse.items()) { 104 | productList.add(ProductMapper.productFromDynamoDB(item)); 105 | } 106 | 107 | return new Products(productList); 108 | } catch (InterruptedException | ExecutionException e) { 109 | logger.error("scan failed with message {}", e.getMessage()); 110 | return new Products(Collections.emptyList()); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /software/products/src/main/java/software/amazonaws/example/product/store/dynamodb/ProductMapper.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.store.dynamodb; 5 | 6 | import software.amazon.awssdk.services.dynamodb.model.AttributeValue; 7 | import software.amazonaws.example.product.model.Product; 8 | 9 | import java.math.BigDecimal; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | public class ProductMapper { 14 | 15 | private static final String PK = "PK"; 16 | private static final String NAME = "name"; 17 | private static final String PRICE = "price"; 18 | 19 | public static Product productFromDynamoDB(Map items) { 20 | Product product = new Product(); 21 | product.setId(items.get(PK).s()); 22 | product.setName(items.get(NAME).s()); 23 | product.setPrice(new BigDecimal(items.get(PRICE).n())); 24 | 25 | return product; 26 | } 27 | 28 | public static Map productToDynamoDb(Product product) { 29 | Map item = new HashMap<>(); 30 | item.put(PK, AttributeValue.builder().s(product.getId()).build()); 31 | item.put(NAME, AttributeValue.builder().s(product.getName()).build()); 32 | item.put(PRICE, AttributeValue.builder().n(product.getPrice().toString()).build()); 33 | 34 | return item; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-core/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"com.amazonaws.services.lambda.runtime.LambdaRuntime", 4 | "methods":[{"name":"","parameterTypes":[] }], 5 | "fields":[{"name":"logger"}], 6 | "allPublicMethods":true 7 | }, 8 | { 9 | "name":"com.amazonaws.services.lambda.runtime.LambdaRuntimeInternal", 10 | "methods":[{"name":"","parameterTypes":[] }], 11 | "allPublicMethods":true 12 | } 13 | ] -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-events/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent", 4 | "allDeclaredFields": true, 5 | "allDeclaredMethods": true, 6 | "allDeclaredConstructors": true 7 | }, 8 | { 9 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent$RequestContext", 10 | "allDeclaredFields": true, 11 | "allDeclaredMethods": true, 12 | "allDeclaredConstructors": true 13 | }, 14 | { 15 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent$RequestContext$Authorizer", 16 | "allDeclaredFields": true, 17 | "allDeclaredMethods": true, 18 | "allDeclaredConstructors": true 19 | }, 20 | { 21 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent$RequestContext$Authorizer$JWT", 22 | "allDeclaredFields": true, 23 | "allDeclaredMethods": true, 24 | "allDeclaredConstructors": true 25 | }, 26 | { 27 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent$RequestContext$CognitoIdentity", 28 | "allDeclaredFields": true, 29 | "allDeclaredMethods": true, 30 | "allDeclaredConstructors": true 31 | }, 32 | { 33 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent$RequestContext$Http", 34 | "allDeclaredFields": true, 35 | "allDeclaredMethods": true, 36 | "allDeclaredConstructors": true 37 | }, 38 | { 39 | "name": "com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse", 40 | "allDeclaredFields": true, 41 | "allDeclaredMethods": true, 42 | "allDeclaredConstructors": true 43 | } 44 | ] 45 | -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-runtime-interface-client/jni-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"com.amazonaws.services.lambda.runtime.api.client.runtimeapi.LambdaRuntimeClientException", 4 | "methods":[{"name":"","parameterTypes":["java.lang.String","int"] }] 5 | }, 6 | { 7 | "name":"com.amazonaws.services.lambda.runtime.api.client.runtimeapi.dto.InvocationRequest", 8 | "fields":[{"name":"id"}, {"name":"invokedFunctionArn"}, {"name":"deadlineTimeInMs"}, {"name":"xrayTraceId"}, {"name":"clientContext"}, {"name":"cognitoIdentity"}, {"name":"content"}], 9 | "allPublicMethods":true 10 | }, 11 | { 12 | "name":"java.lang.Boolean", 13 | "methods":[{"name":"getBoolean","parameterTypes":["java.lang.String"] }] 14 | } 15 | 16 | ] -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-runtime-interface-client/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.deser.Deserializers[]" 4 | }, 5 | { 6 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.ext.Java7SupportImpl", 7 | "methods":[{"name":"","parameterTypes":[] }] 8 | }, 9 | { 10 | "name":"com.amazonaws.services.lambda.runtime.LambdaRuntime", 11 | "fields":[{"name":"logger"}] 12 | }, 13 | { 14 | "name":"java.lang.Void", 15 | "methods":[{"name":"","parameterTypes":[] }] 16 | }, 17 | { 18 | "name":"java.util.Collections$UnmodifiableMap", 19 | "fields":[{"name":"m"}] 20 | }, 21 | { 22 | "name":"jdk.internal.module.IllegalAccessLogger", 23 | "fields":[{"name":"logger"}] 24 | }, 25 | { 26 | "name":"sun.misc.Unsafe", 27 | "fields":[{"name":"theUnsafe"}] 28 | }, 29 | { 30 | "name":"com.amazonaws.services.lambda.runtime.api.client.runtimeapi.dto.InvocationRequest", 31 | "fields":[{"name":"id"}, {"name":"invokedFunctionArn"}, {"name":"deadlineTimeInMs"}, {"name":"xrayTraceId"}, {"name":"clientContext"}, {"name":"cognitoIdentity"}, {"name":"content"}], 32 | "allPublicMethods":true 33 | } 34 | ] -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-runtime-interface-client/resource-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "resources": { 3 | "includes": [ 4 | { 5 | "pattern": "\\Qjni/libaws-lambda-jni.linux-aarch_64.so\\E" 6 | }, 7 | { 8 | "pattern": "\\Qjni/libaws-lambda-jni.linux_musl-aarch_64.so\\E" 9 | }, 10 | { 11 | "pattern": "\\Qjni/libaws-lambda-jni.linux-x86_64.so\\E" 12 | }, 13 | { 14 | "pattern": "\\Qjni/libaws-lambda-jni.linux_musl-x86_64.so\\E" 15 | } 16 | ] 17 | }, 18 | "bundles": [] 19 | } -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/com.amazonaws/aws-lambda-java-serialization/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.deser.Deserializers[]" 4 | }, 5 | { 6 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.ext.Java7HandlersImpl", 7 | "methods":[{"name":"","parameterTypes":[] }] 8 | }, 9 | { 10 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.ext.Java7SupportImpl", 11 | "methods":[{"name":"","parameterTypes":[] }] 12 | }, 13 | { 14 | "name":"com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.ser.Serializers[]" 15 | } 16 | ] -------------------------------------------------------------------------------- /software/products/src/main/resources/META-INF/native-image/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "software.amazonaws.example.product.entrypoints.ApiGatewayGetProductRequestHandler", 4 | "allDeclaredConstructors": true, 5 | "allPublicConstructors": true, 6 | "allDeclaredMethods": true, 7 | "allPublicMethods": true, 8 | "allDeclaredClasses": true, 9 | "allPublicClasses": true 10 | }, 11 | { 12 | "name": "software.amazonaws.example.product.entrypoints.ApiGatewayGetAllProductRequestHandler", 13 | "allDeclaredConstructors": true, 14 | "allPublicConstructors": true, 15 | "allDeclaredMethods": true, 16 | "allPublicMethods": true, 17 | "allDeclaredClasses": true, 18 | "allPublicClasses": true 19 | }, 20 | { 21 | "name": "software.amazonaws.example.product.entrypoints.ApiGatewayPutProductRequestHandler", 22 | "allDeclaredConstructors": true, 23 | "allPublicConstructors": true, 24 | "allDeclaredMethods": true, 25 | "allPublicMethods": true, 26 | "allDeclaredClasses": true, 27 | "allPublicClasses": true 28 | }, 29 | { 30 | "name": "software.amazonaws.example.product.entrypoints.ApiGatewayDeleteProductRequestHandler", 31 | "allDeclaredConstructors": true, 32 | "allPublicConstructors": true, 33 | "allDeclaredMethods": true, 34 | "allPublicMethods": true, 35 | "allDeclaredClasses": true, 36 | "allPublicClasses": true 37 | }, 38 | { 39 | "name": "software.amazonaws.example.product.model.Product", 40 | "allDeclaredConstructors": true, 41 | "allPublicConstructors": true, 42 | "allDeclaredMethods": true, 43 | "allPublicMethods": true, 44 | "allDeclaredClasses": true, 45 | "allPublicClasses": true 46 | }, 47 | { 48 | "name": "software.amazonaws.example.product.model.Products", 49 | "allDeclaredConstructors": true, 50 | "allPublicConstructors": true, 51 | "allDeclaredMethods": true, 52 | "allPublicMethods": true, 53 | "allDeclaredClasses": true, 54 | "allPublicClasses": true 55 | }, 56 | { 57 | "name":"com.fasterxml.jackson.databind.ext.Java7HandlersImpl", 58 | "methods":[{"name":"","parameterTypes":[] }]}, 59 | { 60 | "name":"com.fasterxml.jackson.databind.ext.Java7SupportImpl", 61 | "methods":[{"name":"","parameterTypes":[] }]}, 62 | { 63 | "name" : "org.apache.commons.logging.impl.LogFactoryImpl", 64 | "allDeclaredConstructors" : true, 65 | "allPublicConstructors" : true, 66 | "allDeclaredMethods" : true, 67 | "allPublicMethods" : true, 68 | "allDeclaredClasses" : true, 69 | "allPublicClasses" : true 70 | }, 71 | { 72 | "name" : "java.lang.String", 73 | "allDeclaredConstructors" : true, 74 | "allPublicConstructors" : true, 75 | "allDeclaredMethods" : true, 76 | "allPublicMethods" : true, 77 | "allDeclaredClasses" : true, 78 | "allPublicClasses" : true 79 | }, 80 | { 81 | "name" : "org.apache.commons.logging.LogFactory", 82 | "allDeclaredConstructors" : true, 83 | "allPublicConstructors" : true, 84 | "allDeclaredMethods" : true, 85 | "allPublicMethods" : true, 86 | "allDeclaredClasses" : true, 87 | "allPublicClasses" : true 88 | }, 89 | { 90 | "name" : "org.apache.commons.logging.impl.SimpleLog", 91 | "allDeclaredConstructors" : true, 92 | "allPublicConstructors" : true, 93 | "allDeclaredMethods" : true, 94 | "allPublicMethods" : true, 95 | "allDeclaredClasses" : true, 96 | "allPublicClasses" : true 97 | } 98 | ] 99 | -------------------------------------------------------------------------------- /software/products/src/main/resources/simplelogger.properties: -------------------------------------------------------------------------------- 1 | # Default logging detail level for all instances of SimpleLogger. Must be one of ("trace", "debug", "info", "warn", or "error"). 2 | org.slf4j.simpleLogger.defaultLogLevel=info 3 | 4 | # Set to true if you want the current date and time to be included in output messages. 5 | org.slf4j.simpleLogger.showDateTime=true 6 | 7 | # The date and time format to be used in the output messages. The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. If the format is not specified or is invalid, will output the number of milliseconds elapsed since startup. 8 | org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd'T'HH:mm:ss.SSS 9 | 10 | # Set to true if you want to output the current thread name. 11 | org.slf4j.simpleLogger.showThreadName=false 12 | # Set to true if you want the Logger instance name to be included in output messages. 13 | org.slf4j.simpleLogger.showLogName=true 14 | # Set to true if you want the last component of the name to be included in output messages. 15 | org.slf4j.simpleLogger.showShortLogName=true 16 | org.slf4j.simpleLogger.levelInBrackets=true 17 | org.slf4j.simpleLogger.logFile=System.out -------------------------------------------------------------------------------- /software/products/src/test/java/software/amazonaws/example/product/entrypoints/ApiGatewayGetAllProductRequestHandlerTest.java: -------------------------------------------------------------------------------- 1 | package software.amazonaws.example.product.entrypoints; 2 | 3 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 4 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 5 | import org.json.JSONException; 6 | import org.junit.jupiter.api.Test; 7 | import org.skyscreamer.jsonassert.JSONAssert; 8 | import org.skyscreamer.jsonassert.JSONCompareMode; 9 | import software.amazonaws.example.product.model.Product; 10 | import software.amazonaws.example.product.model.Products; 11 | import software.amazonaws.example.product.store.ProductStore; 12 | 13 | import java.math.BigDecimal; 14 | import java.util.List; 15 | 16 | import static org.junit.jupiter.api.Assertions.assertEquals; 17 | import static org.mockito.Mockito.mock; 18 | import static org.mockito.Mockito.timeout; 19 | import static org.mockito.Mockito.verify; 20 | import static org.mockito.Mockito.when; 21 | 22 | public class ApiGatewayGetAllProductRequestHandlerTest { 23 | 24 | private ApiGatewayGetAllProductRequestHandler handler; 25 | 26 | private ProductStore mockProductStore = mock(ProductStore.class); 27 | 28 | @Test 29 | public void test() throws JSONException { 30 | Product product = new Product("Indigo Hats", "3d22f23b-1e74-4291-a6e9-4ab53c15cd77", new BigDecimal("13.3434343")); 31 | 32 | when(mockProductStore.getAllProduct()).thenReturn(new Products(List.of(product))); 33 | 34 | handler = new ApiGatewayGetAllProductRequestHandler(mockProductStore); 35 | 36 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder().build(); 37 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 38 | 39 | assertEquals(200, response.getStatusCode()); 40 | JSONAssert.assertEquals(""" 41 | { 42 | "products": [ 43 | { 44 | "id":"Indigo Hats", 45 | "name":"3d22f23b-1e74-4291-a6e9-4ab53c15cd77", 46 | "price":13.34 47 | }]} 48 | """, response.getBody(), JSONCompareMode.STRICT); 49 | verify(mockProductStore, timeout(1)).getAllProduct(); 50 | } 51 | } -------------------------------------------------------------------------------- /software/products/src/test/java/software/amazonaws/example/product/entrypoints/ApiGatewayGetProductRequestHandlerTest.java: -------------------------------------------------------------------------------- 1 | package software.amazonaws.example.product.entrypoints; 2 | 3 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 4 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 5 | import org.json.JSONException; 6 | import org.junit.jupiter.api.Test; 7 | import org.skyscreamer.jsonassert.JSONAssert; 8 | import org.skyscreamer.jsonassert.JSONCompareMode; 9 | import software.amazonaws.example.product.model.Product; 10 | import software.amazonaws.example.product.store.ProductStore; 11 | 12 | import java.math.BigDecimal; 13 | import java.util.Map; 14 | import java.util.Optional; 15 | 16 | import static org.junit.jupiter.api.Assertions.assertEquals; 17 | import static org.mockito.Mockito.mock; 18 | import static org.mockito.Mockito.timeout; 19 | import static org.mockito.Mockito.verify; 20 | import static org.mockito.Mockito.when; 21 | 22 | public class ApiGatewayGetProductRequestHandlerTest { 23 | 24 | private ApiGatewayGetProductRequestHandler handler; 25 | 26 | @Test 27 | public void testGetForExistingProduct() throws JSONException { 28 | ProductStore mockProductStore = mock(ProductStore.class); 29 | Product product = new Product("Indigo Hats", "3d22f23b-1e74-4291-a6e9-4ab53c15cd77", new BigDecimal("13.3434343")); 30 | 31 | when(mockProductStore.getProduct("3d22f23b-1e74-4291-a6e9-4ab53c15cd77")).thenReturn(Optional.of(product)); 32 | 33 | handler = new ApiGatewayGetProductRequestHandler(mockProductStore); 34 | 35 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder() 36 | .withPathParameters(Map.of("id", "3d22f23b-1e74-4291-a6e9-4ab53c15cd77")) 37 | .build(); 38 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 39 | 40 | assertEquals(200, response.getStatusCode()); 41 | JSONAssert.assertEquals(""" 42 | { 43 | "id":"Indigo Hats", 44 | "name":"3d22f23b-1e74-4291-a6e9-4ab53c15cd77", 45 | "price":13.34 46 | } 47 | """, response.getBody(), JSONCompareMode.STRICT); 48 | verify(mockProductStore, timeout(1)).getProduct("3d22f23b-1e74-4291-a6e9-4ab53c15cd77"); 49 | } 50 | 51 | @Test 52 | public void testGetForNonExistingProduct() throws JSONException { 53 | ProductStore mockProductStore = mock(ProductStore.class); 54 | when(mockProductStore.getProduct("3d22f23b-1e74-4291-a6e9-4ab53c15cd77")).thenReturn(Optional.empty()); 55 | 56 | handler = new ApiGatewayGetProductRequestHandler(mockProductStore); 57 | 58 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder() 59 | .withPathParameters(Map.of("id", "3d22f23b-1e74-4291-a6e9-4ab53c15cd77")) 60 | .build(); 61 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 62 | 63 | assertEquals(404, response.getStatusCode()); 64 | JSONAssert.assertEquals(""" 65 | { 66 | "message": "Product not found" 67 | } 68 | """, response.getBody(), JSONCompareMode.STRICT); 69 | verify(mockProductStore, timeout(1)).getProduct("3d22f23b-1e74-4291-a6e9-4ab53c15cd77"); 70 | } 71 | } -------------------------------------------------------------------------------- /software/products/src/test/java/software/amazonaws/example/product/entrypoints/ApiGatewayPutProductRequestHandlerTest.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; 7 | import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; 8 | import org.junit.jupiter.api.Assertions; 9 | import org.junit.jupiter.api.Test; 10 | import software.amazonaws.example.product.model.Product; 11 | import software.amazonaws.example.product.store.ProductStore; 12 | 13 | import java.util.Map; 14 | 15 | import static org.mockito.Mockito.*; 16 | 17 | public class ApiGatewayPutProductRequestHandlerTest { 18 | 19 | private ApiGatewayPutProductRequestHandler handler; 20 | 21 | private ProductStore mockProductStore = mock(ProductStore.class); 22 | 23 | @Test 24 | public void testValidRequest() { 25 | doNothing().when(mockProductStore).putProduct(any(Product.class)); 26 | 27 | handler = new ApiGatewayPutProductRequestHandler(mockProductStore); 28 | 29 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder() 30 | .withBody(""" 31 | { 32 | \"id\": \"333\", 33 | \"name\": \"test\", 34 | \"price\": 44.55 35 | }""") 36 | .withPathParameters(Map.of("id", "333")) 37 | .build(); 38 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 39 | 40 | Assertions.assertEquals(201, response.getStatusCode()); 41 | verify(mockProductStore, timeout(1)).putProduct(any(Product.class)); 42 | } 43 | 44 | @Test 45 | public void testRequestBodyNull() { 46 | handler = new ApiGatewayPutProductRequestHandler(mockProductStore); 47 | 48 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder() 49 | .withPathParameters(Map.of("id", "333")) 50 | .build(); 51 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 52 | 53 | Assertions.assertEquals(400, response.getStatusCode()); 54 | } 55 | 56 | @Test 57 | public void testRequestBodyEmpty() { 58 | handler = new ApiGatewayPutProductRequestHandler(mockProductStore); 59 | 60 | APIGatewayV2HTTPEvent event = APIGatewayV2HTTPEvent.builder() 61 | .withBody("") 62 | .withPathParameters(Map.of("id", "333")) 63 | .build(); 64 | APIGatewayV2HTTPResponse response = handler.handleRequest(event, new TestContext()); 65 | 66 | Assertions.assertEquals(400, response.getStatusCode()); 67 | } 68 | } -------------------------------------------------------------------------------- /software/products/src/test/java/software/amazonaws/example/product/entrypoints/StandardOutLambdaLogger.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.LambdaLogger; 7 | 8 | public class StandardOutLambdaLogger implements LambdaLogger { 9 | @Override 10 | public void log(String s) { 11 | System.out.println(s); 12 | } 13 | 14 | @Override 15 | public void log(byte[] bytes) { 16 | System.out.println(bytes); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /software/products/src/test/java/software/amazonaws/example/product/entrypoints/TestContext.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | package software.amazonaws.example.product.entrypoints; 5 | 6 | import com.amazonaws.services.lambda.runtime.ClientContext; 7 | import com.amazonaws.services.lambda.runtime.CognitoIdentity; 8 | import com.amazonaws.services.lambda.runtime.Context; 9 | import com.amazonaws.services.lambda.runtime.LambdaLogger; 10 | 11 | public class TestContext implements Context { 12 | 13 | private final StandardOutLambdaLogger lambdaLogger = new StandardOutLambdaLogger(); 14 | 15 | @Override 16 | public String getAwsRequestId() { 17 | return null; 18 | } 19 | 20 | @Override 21 | public String getLogGroupName() { 22 | return null; 23 | } 24 | 25 | @Override 26 | public String getLogStreamName() { 27 | return null; 28 | } 29 | 30 | @Override 31 | public String getFunctionName() { 32 | return null; 33 | } 34 | 35 | @Override 36 | public String getFunctionVersion() { 37 | return null; 38 | } 39 | 40 | @Override 41 | public String getInvokedFunctionArn() { 42 | return null; 43 | } 44 | 45 | @Override 46 | public CognitoIdentity getIdentity() { 47 | return null; 48 | } 49 | 50 | @Override 51 | public ClientContext getClientContext() { 52 | return null; 53 | } 54 | 55 | @Override 56 | public int getRemainingTimeInMillis() { 57 | return 0; 58 | } 59 | 60 | @Override 61 | public int getMemoryLimitInMB() { 62 | return 0; 63 | } 64 | 65 | @Override 66 | public LambdaLogger getLogger() { 67 | return lambdaLogger; 68 | } 69 | } 70 | --------------------------------------------------------------------------------