diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index ae6486f..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,16 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "maven" - directory: "/java/SqsBatchProcessing/Functions" - schedule: - interval: "daily" - labels: - - "maven" - - "dependencies" - - package-ecosystem: "maven" - directory: "/java/CoreUtilities/Functions" - schedule: - interval: "daily" - labels: - - "maven" - - "dependencies" \ No newline at end of file diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml deleted file mode 100644 index 2f1cc34..0000000 --- a/.github/workflows/auto-merge.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: Auto merge if dependabot PR - -on: - workflow_run: - workflows: ["Build"] - types: [completed] - -jobs: - merge-me: - name: Merge me! - runs-on: ubuntu-latest - if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' && github.actor == 'dependabot[bot]' - steps: - - name: 'Download artifact' - uses: actions/github-script@v3.1.0 - with: - script: | - var artifacts = await github.actions.listWorkflowRunArtifacts({ - owner: context.repo.owner, - repo: context.repo.repo, - run_id: ${{github.event.workflow_run.id }}, - }); - var matchArtifact = artifacts.data.artifacts.filter((artifact) => { - return artifact.name == "pr" - })[0]; - var download = await github.actions.downloadArtifact({ - owner: context.repo.owner, - repo: context.repo.repo, - artifact_id: matchArtifact.id, - archive_format: 'zip', - }); - var fs = require('fs'); - fs.writeFileSync('${{github.workspace}}/pr.zip', Buffer.from(download.data)); - - run: unzip pr.zip - - name: Merge me! - uses: actions/github-script@v3 - with: - script: | - var fs = require('fs'); - var issue_number = Number(fs.readFileSync('./NR')); - - github.pulls.createReview({ - owner: context.payload.repository.owner.login, - repo: context.payload.repository.name, - pull_number: issue_number, - event: 'APPROVE' - }) - github.pulls.merge({ - owner: context.payload.repository.owner.login, - repo: context.payload.repository.name, - pull_number: issue_number, - merge_method: 'squash' - }) - github-token: ${{ secrets.AUTOMERGE }} \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 20da16f..0000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: Build - -on: - pull_request: - branches: - - main - paths: - - 'manifest.json' - - 'java/**' - - '.github/workflows/**' - push: - branches: - - main - paths: - - 'manifest.json' - - 'java/**' - - '.github/workflows/**' - -jobs: - prepare: - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.set-matrix.outputs.matrix }} - steps: - - uses: actions/checkout@v2 - - id: set-matrix - run: | - JSON=$(cat ./manifest.json | jq [.[][]]) - JSON="${JSON//'%'/'%25'}" - JSON="{\"include\":$JSON}" - JSON="${JSON//$'\n'/'%0A'}" - JSON="${JSON//$'\r'/'%0D'}" - echo $JSON - echo "-----------------------" - echo "::set-output name=matrix::$JSON" - - build: - needs: prepare - runs-on: ubuntu-latest - strategy: - matrix: ${{fromJson(needs.prepare.outputs.matrix)}} - env: - OS: ${{ matrix.os }} - JAVA: ${{ matrix.java-version }} - AWS_REGION: eu-west-1 - steps: - - uses: actions/checkout@v2 - - name: Setup java - uses: actions/setup-java@v1 - with: - java-version: ${{ matrix.javaVersion }} - - name: Build with Maven - if: ${{ matrix.dependencyManager == 'maven' }} - run: mvn -B package --file ${{ matrix.directory }}/pom.xml - - name: Build with Gradle - if: ${{ matrix.dependencyManager == 'gradle' }} - run: | - cd ./${{ matrix.directory }}/ - ./gradlew build - - savepr: - runs-on: ubuntu-latest - name: Save PR number if running on PR by dependabot - if: github.actor == 'dependabot[bot]' - steps: - - name: Create Directory and save issue - run: | - mkdir -p ./pr - echo ${{ github.event.number }} - echo ${{ github.event.number }} > ./pr/NR - - uses: actions/upload-artifact@v2 - name: Updload artifact - with: - name: pr - path: pr/ diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 87af344..0000000 --- a/.gitignore +++ /dev/null @@ -1,248 +0,0 @@ - -# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode - -### Linux ### -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -### OSX ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -### PyCharm ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/dictionaries - -# Sensitive or high-churn files: -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.xml -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml - -# Gradle: -.idea/**/gradle.xml -.idea/**/libraries - -# CMake -cmake-build-debug/ - -# Mongo Explorer plugin: -.idea/**/mongoSettings.xml - -## File-based project format: -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Ruby plugin and RubyMine -/.rakeTasks - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -### PyCharm Patch ### -# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 - -# *.iml -# modules.xml -# .idea/misc.xml -# *.ipr - -# Sonarlint plugin -.idea/sonarlint - -### Python ### -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -.pytest_cache/ -nosetests.xml -coverage.xml -*.cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ -.idea/ - -*.iml -*dependency-reduced-pom.xml -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule.* - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ - -### VisualStudioCode ### -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -.history - -### Windows ### -# Windows thumbnail cache files -Thumbs.db -ehthumbs.db -ehthumbs_vista.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk - -# Build folder - -*/build/* - -.aws-sam -*.toml \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 5b627cf..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index c4b6a1c..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,59 +0,0 @@ -# Contributing Guidelines - -Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional -documentation, we greatly value feedback and contributions from our community. - -Please read through this document before submitting any issues or pull requests to ensure we have all the necessary -information to effectively respond to your bug report or contribution. - - -## Reporting Bugs/Feature Requests - -We welcome you to use the GitHub issue tracker to report bugs or suggest features. - -When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already -reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: - -* A reproducible test case or series of steps -* The version of our code being used -* Any modifications you've made relevant to the bug -* Anything unusual about your environment or deployment - - -## Contributing via Pull Requests -Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: - -1. You are working against the latest source on the *main* branch. -2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. -3. You open an issue to discuss any significant work - we would hate for your time to be wasted. - -To send us a pull request, please: - -1. Fork the repository. -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. -3. Ensure local tests pass. -4. Commit to your fork using clear commit messages. -5. Send us a pull request, answering any default questions in the pull request interface. -6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. - -GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and -[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). - - -## Finding contributions to work on -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. - - -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. - - -## Security issue notifications -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. - - -## Licensing - -See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. diff --git a/README.md b/README.md index 2af0aea..226fb41 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,3 @@ ## aws-lambda-powertools-examples -This repo holds example projects demoing different types of utilities provided by aws-lambda-powertools project for different -runtimes. - -## Security - -See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. - -## License - -This library is licensed under the MIT-0 License. See the LICENSE file. - +⚠️⚠️ The samples previously stored here have moved to [the main AWS Lambda Powertools for Java repository](https://github.com/awslabs/aws-lambda-powertools-java). To get started, you can check them out in their new home and find the documentation [here](https://awslabs.github.io/aws-lambda-powertools-java/) ⚠️⚠️ diff --git a/java/CoreUtilities/.gitignore b/java/CoreUtilities/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/java/CoreUtilities/Function/pom.xml b/java/CoreUtilities/Function/pom.xml deleted file mode 100644 index cc2da8a..0000000 --- a/java/CoreUtilities/Function/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - 4.0.0 - powertools - Function - 1.0 - jar - A sample Hello World created for SAM CLI using powertools core utilities - - 11 - 11 - 2.17.1 - UTF-8 - - - - - software.amazon.lambda - powertools-tracing - 1.10.2 - - - software.amazon.lambda - powertools-logging - 1.10.2 - - - software.amazon.lambda - powertools-metrics - 1.10.2 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - com.amazonaws - aws-lambda-java-events - 3.11.0 - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - - - org.apache.logging.log4j - log4j-api - ${log4j.version} - - - - junit - junit - 4.13.2 - test - - - - - - - org.codehaus.mojo - aspectj-maven-plugin - 1.14.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.target} - - - software.amazon.lambda - powertools-tracing - - - software.amazon.lambda - powertools-logging - - - software.amazon.lambda - powertools-metrics - - - - - - - compile - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.4 - - - package - - shade - - - - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.15 - - - - - - diff --git a/java/CoreUtilities/Function/src/main/java/helloworld/App.java b/java/CoreUtilities/Function/src/main/java/helloworld/App.java deleted file mode 100644 index b454401..0000000 --- a/java/CoreUtilities/Function/src/main/java/helloworld/App.java +++ /dev/null @@ -1,115 +0,0 @@ -package helloworld; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import com.amazonaws.xray.AWSXRay; -import com.amazonaws.xray.entities.Entity; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import software.amazon.cloudwatchlogs.emf.model.DimensionSet; -import software.amazon.cloudwatchlogs.emf.model.Unit; -import software.amazon.lambda.powertools.logging.LoggingUtils; -import software.amazon.lambda.powertools.logging.Logging; -import software.amazon.lambda.powertools.metrics.Metrics; -import software.amazon.lambda.powertools.tracing.CaptureMode; -import software.amazon.lambda.powertools.tracing.TracingUtils; -import software.amazon.lambda.powertools.tracing.Tracing; - -import static software.amazon.lambda.powertools.metrics.MetricsUtils.metricsLogger; -import static software.amazon.lambda.powertools.metrics.MetricsUtils.withSingleMetric; -import static software.amazon.lambda.powertools.tracing.TracingUtils.putMetadata; -import static software.amazon.lambda.powertools.tracing.TracingUtils.withEntitySubsegment; - -/** - * Handler for requests to Lambda function. - */ -public class App implements RequestHandler { - private final static Logger log = LogManager.getLogger(App.class); - - @Logging(logEvent = true, samplingRate = 0.7) - @Tracing(captureMode = CaptureMode.RESPONSE_AND_ERROR) - @Metrics(namespace = "ServerlessAirline", service = "payment", captureColdStart = true) - public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { - Map headers = new HashMap<>(); - - headers.put("Content-Type", "application/json"); - headers.put("X-Custom-Header", "application/json"); - - metricsLogger().putMetric("CustomMetric1", 1, Unit.COUNT); - - withSingleMetric("CustomMetrics2", 1, Unit.COUNT, "Another", (metric) -> { - metric.setDimensions(DimensionSet.of("AnotherService", "CustomService")); - metric.setDimensions(DimensionSet.of("AnotherService1", "CustomService1")); - }); - - LoggingUtils.appendKey("test", "willBeLogged"); - - APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() - .withHeaders(headers); - try { - final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); - log.info(pageContents); - TracingUtils.putAnnotation("Test", "New"); - String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); - - TracingUtils.withSubsegment("loggingResponse", subsegment -> { - String sampled = "log something out"; - log.info(sampled); - log.info(output); - }); - - threadOption1(); - - threadOption2(); - - log.info("After output"); - return response - .withStatusCode(200) - .withBody(output); - } catch (IOException | InterruptedException e) { - return response - .withBody("{}") - .withStatusCode(500); - } - } - - private void threadOption1() throws InterruptedException { - final Entity traceEntity = AWSXRay.getTraceEntity(); - assert traceEntity != null; - traceEntity.run(new Thread(this::log)); - } - - private void threadOption2() throws InterruptedException { - Entity traceEntity = AWSXRay.getTraceEntity(); - Thread anotherThread = new Thread(() -> withEntitySubsegment("inlineLog", traceEntity, subsegment -> { - String var = "somethingToProcess"; - log.info("inside threaded logging inline {}", var); - })); - anotherThread.start(); - anotherThread.join(); - } - - @Tracing - private void log() { - log.info("inside threaded logging for function"); - } - - @Tracing(namespace = "getPageContents", captureMode = CaptureMode.DISABLED) - private String getPageContents(String address) throws IOException { - URL url = new URL(address); - putMetadata("getPageContents", address); - try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { - return br.lines().collect(Collectors.joining(System.lineSeparator())); - } - } -} diff --git a/java/CoreUtilities/Function/src/main/java/helloworld/AppStream.java b/java/CoreUtilities/Function/src/main/java/helloworld/AppStream.java deleted file mode 100644 index aed048e..0000000 --- a/java/CoreUtilities/Function/src/main/java/helloworld/AppStream.java +++ /dev/null @@ -1,25 +0,0 @@ -package helloworld; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestStreamHandler; -import com.fasterxml.jackson.databind.ObjectMapper; -import software.amazon.lambda.powertools.logging.Logging; -import software.amazon.lambda.powertools.metrics.Metrics; - -public class AppStream implements RequestStreamHandler { - private static final ObjectMapper mapper = new ObjectMapper(); - - @Override - @Logging(logEvent = true) - @Metrics(namespace = "ServerlessAirline", service = "payment", captureColdStart = true) - public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { - Map map = mapper.readValue(input, Map.class); - - System.out.println(map.size()); - } -} diff --git a/java/CoreUtilities/Function/src/main/resources/log4j2.xml b/java/CoreUtilities/Function/src/main/resources/log4j2.xml deleted file mode 100644 index e1fd14c..0000000 --- a/java/CoreUtilities/Function/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java/CoreUtilities/Function/src/test/java/helloworld/AppTest.java b/java/CoreUtilities/Function/src/test/java/helloworld/AppTest.java deleted file mode 100644 index b584ee9..0000000 --- a/java/CoreUtilities/Function/src/test/java/helloworld/AppTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package helloworld; - -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import com.amazonaws.xray.AWSXRay; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class AppTest { - - @Before - public void setup() { - if(null == System.getenv("LAMBDA_TASK_ROOT")) { - AWSXRay.beginSegment("test"); - } - } - - @After - public void tearDown() { - if (AWSXRay.getCurrentSubsegmentOptional().isPresent()) { - AWSXRay.endSubsegment(); - } - - if(null == System.getenv("LAMBDA_TASK_ROOT")) { - AWSXRay.endSegment(); - } - } - - @Test - public void successfulResponse() { - App app = new App(); - APIGatewayProxyResponseEvent result = app.handleRequest(null, null); - assertEquals(result.getStatusCode().intValue(), 200); - assertEquals(result.getHeaders().get("Content-Type"), "application/json"); - String content = result.getBody(); - assertNotNull(content); - assertTrue(content.contains("\"message\"")); - assertTrue(content.contains("\"hello world\"")); - assertTrue(content.contains("\"location\"")); - } -} diff --git a/java/CoreUtilities/README.md b/java/CoreUtilities/README.md deleted file mode 100644 index f4bdc39..0000000 --- a/java/CoreUtilities/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# CoreUtilities - -This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes [Lambda Powertools for operational best practices](https://github.com/awslabs/aws-lambda-powertools-java), and the following files and folders. - -- HelloWorldFunction/src/main - Code for the application's Lambda function. -- events - Invocation events that you can use to invoke the function. -- HelloWorldFunction/src/test - Unit tests for the application code. -- template.yaml - A template that defines the application's AWS resources. - -The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. - -If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. -The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. - -* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) -* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) - -## Deploy the sample application - -The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. - -To use the SAM CLI, you need the following tools. - -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) -* Maven - [Install Maven](https://maven.apache.org/install.html) -* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -Coreutilities$ sam build -Coreutilities$ sam deploy --guided -``` - -The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts: - -* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. -* **AWS Region**: The AWS region you want to deploy your app to. -* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. -* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modified IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. -* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. - -You can find your API Gateway Endpoint URL in the output values displayed after deployment. - -## Use the SAM CLI to build and test locally - -Build your application with the `sam build` command. - -```bash -Coreutilities$ sam build -``` - -The SAM CLI installs dependencies defined in `HelloWorldFunction/pom.xml`, creates a deployment package, and saves it in the `.aws-sam/build` folder. - -Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. - -Run functions locally and invoke them with the `sam local invoke` command. - -```bash -Coreutilities$ sam local invoke HelloWorldFunction --event events/event.json -``` - -The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. - -```bash -Coreutilities$ sam local start-api -Coreutilities$ curl http://localhost:3000/ -``` - -The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. - -```yaml - Events: - HelloWorld: - Type: Api - Properties: - Path: /hello - Method: get -``` - -## Add a resource to your application -The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. - -## Fetch, tail, and filter Lambda function logs - -To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. - -`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. - -```bash -Coreutilities$ sam logs -n HelloWorldFunction --stack-name --tail -``` - -You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). - -## Unit tests - -Tests are defined in the `HelloWorldFunction/src/test` folder in this project. - -```bash -Coreutilities$ cd HelloWorldFunction -HelloWorldFunction$ mvn test -``` - -## Cleanup - -To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: - -```bash -aws cloudformation delete-stack --stack-name -``` - -# Appendix - -## Powertools - -**Tracing** - -[Tracing utility](https://awslabs.github.io/aws-lambda-powertools-java/core/tracing/) provides functionality to reduce the overhead of performing common tracing tasks. It traces the execution of this sample code including the response and exceptions as tracing metadata - You can visualize them in AWS X-Ray. - -**Logger** - -[Logging utility](https://awslabs.github.io/aws-lambda-powertools-java/core/logging/) creates an opinionated application Logger with structured logging as the output, dynamically samples a percentage (samplingRate) of your logs in DEBUG mode for concurrent invocations, log incoming events as your function is invoked, and injects key information from Lambda context object into your Logger - You can visualize them in Amazon CloudWatch Logs. - -**Metrics** - -[Metrics utility](https://awslabs.github.io/aws-lambda-powertools-java/core/metrics/) captures cold start metric of your Lambda invocation, and could add additional metrics to help you understand your application KPIs - You can visualize them in Amazon CloudWatch. - -## Resources - -See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. - -Check the [AWS Lambda Powertools Java](https://awslabs.github.io/aws-lambda-powertools-java/) for more information on how to use and configure such tools - -Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/java/CoreUtilities/events/event.json b/java/CoreUtilities/events/event.json deleted file mode 100644 index 3822fad..0000000 --- a/java/CoreUtilities/events/event.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "body": "{\"message\": \"hello world\"}", - "resource": "/{proxy+}", - "path": "/path/to/resource", - "httpMethod": "POST", - "isBase64Encoded": false, - "queryStringParameters": { - "foo": "bar" - }, - "pathParameters": { - "proxy": "/path/to/resource" - }, - "stageVariables": { - "baz": "qux" - }, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Accept-Encoding": "gzip, deflate, sdch", - "Accept-Language": "en-US,en;q=0.8", - "Cache-Control": "max-age=0", - "CloudFront-Forwarded-Proto": "https", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-Mobile-Viewer": "false", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Tablet-Viewer": "false", - "CloudFront-Viewer-Country": "US", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "Upgrade-Insecure-Requests": "1", - "User-Agent": "Custom User Agent String", - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "X-Forwarded-Port": "443", - "X-Forwarded-Proto": "https" - }, - "requestContext": { - "accountId": "123456789012", - "resourceId": "123456", - "stage": "prod", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "requestTime": "09/Apr/2015:12:34:56 +0000", - "requestTimeEpoch": 1428582896000, - "identity": { - "cognitoIdentityPoolId": null, - "accountId": null, - "cognitoIdentityId": null, - "caller": null, - "accessKey": null, - "sourceIp": "127.0.0.1", - "cognitoAuthenticationType": null, - "cognitoAuthenticationProvider": null, - "userArn": null, - "userAgent": "Custom User Agent String", - "user": null - }, - "path": "/prod/path/to/resource", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "apiId": "1234567890", - "protocol": "HTTP/1.1" - } - } - \ No newline at end of file diff --git a/java/CoreUtilities/template.yaml b/java/CoreUtilities/template.yaml deleted file mode 100644 index ed05286..0000000 --- a/java/CoreUtilities/template.yaml +++ /dev/null @@ -1,66 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - CoreUtilities - -# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active # https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html - Environment: - Variables: - # Powertools env vars: https://awslabs.github.io/aws-lambda-powertools-python/#environment-variables - POWERTOOLS_LOG_LEVEL: INFO - POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1 - POWERTOOLS_LOGGER_LOG_EVENT: true - POWERTOOLS_METRICS_NAMESPACE: Coreutilities - -Resources: - HelloWorldFunction: - Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Properties: - CodeUri: Function - Handler: helloworld.App::handleRequest - Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object - Variables: - POWERTOOLS_SERVICE_NAME: hello - Events: - HelloWorld: - Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api - Properties: - Path: /hello - Method: get - - HelloWorldStreamFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: helloworld.AppStream::handleRequest - MemorySize: 512 - Tracing: Active - Environment: - Variables: - POWERTOOLS_LOGGER_SAMPLE_RATE: 0.7 - Events: - HelloWorld: - Type: Api - Properties: - Path: /hellostream - Method: get - -Outputs: - # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function - # Find out more about other implicit resources you can reference within SAM - # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api - HelloWorldApi: - Description: "API Gateway endpoint URL for Prod stage for Hello World function" - Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" - HelloWorldFunction: - Description: "Hello World Lambda Function ARN" - Value: !GetAtt HelloWorldFunction.Arn - HelloWorldFunctionIamRole: - Description: "Implicit IAM Role created for Hello World function" - Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/java/Idempotency/Function/pom.xml b/java/Idempotency/Function/pom.xml deleted file mode 100644 index 499f30e..0000000 --- a/java/Idempotency/Function/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - 4.0.0 - powertools - Function - 1.0 - jar - A sample Hello World using powertools idempotency - - 11 - 11 - 2.17.1 - UTF-8 - - - - - software.amazon.lambda - powertools-tracing - 1.11.0 - - - software.amazon.lambda - powertools-logging - 1.11.0 - - - software.amazon.lambda - powertools-idempotency - 1.11.0 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - com.amazonaws - aws-lambda-java-events - 3.11.0 - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - - - org.apache.logging.log4j - log4j-api - ${log4j.version} - - - - org.mockito - mockito-core - 4.3.1 - test - - - org.junit.jupiter - junit-jupiter-api - 5.8.2 - test - - - com.amazonaws - DynamoDBLocal - [1.12,2.0) - test - - - com.amazonaws - aws-lambda-java-tests - 1.1.1 - - - - - - - org.codehaus.mojo - aspectj-maven-plugin - 1.14.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.target} - - - software.amazon.lambda - powertools-tracing - - - software.amazon.lambda - powertools-logging - - - software.amazon.lambda - powertools-idempotency - - - - - - - compile - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy - test-compile - - copy-dependencies - - - test - so,dll,dylib - ${project.build.directory}/native-libs - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M5 - - - ${project.build.directory}/native-libs - - - idempotency - eu-central-1 - LOG_ERROR - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.4 - - - package - - shade - - - - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.15 - - - - - - - - dynamodb-local-oregon - DynamoDB Local Release Repository - https://s3.eu-central-1.amazonaws.com/dynamodb-local-frankfurt/release - - - diff --git a/java/Idempotency/Function/src/main/java/helloworld/App.java b/java/Idempotency/Function/src/main/java/helloworld/App.java deleted file mode 100644 index 3fe3fc4..0000000 --- a/java/Idempotency/Function/src/main/java/helloworld/App.java +++ /dev/null @@ -1,92 +0,0 @@ -package helloworld; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.lambda.powertools.idempotency.Idempotency; -import software.amazon.lambda.powertools.idempotency.IdempotencyConfig; -import software.amazon.lambda.powertools.idempotency.Idempotent; -import software.amazon.lambda.powertools.idempotency.persistence.DynamoDBPersistenceStore; -import software.amazon.lambda.powertools.logging.Logging; -import software.amazon.lambda.powertools.utilities.JsonConfig; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -public class App implements RequestHandler { - private final static Logger log = LogManager.getLogger(App.class); - - public App() { - this(null); - } - - public App(DynamoDbClient client) { - Idempotency.config().withConfig( - IdempotencyConfig.builder() - .withEventKeyJMESPath("powertools_json(body).address") // will retrieve the address field in the body which is a string transformed to json with `powertools_json` - .build()) - .withPersistenceStore( - DynamoDBPersistenceStore.builder() - .withDynamoDbClient(client) - .withTableName(System.getenv("IDEMPOTENCY_TABLE")) - .build() - ).configure(); - } - - /** - * Try with: - *
-     *     curl -X POST https://[REST-API-ID].execute-api.[REGION].amazonaws.com/Prod/helloidem/ -H "Content-Type: application/json" -d '{"address": "https://checkip.amazonaws.com"}'
-     * 
- *
    - *
  • First call will execute the handleRequest normally, and store the response in the idempotency table (Look into DynamoDB)
  • - *
  • Second call (and next ones) will retrieve from the cache (if cache is enabled, which is by default) or from the store, the handler won't be called. Until the expiration happens (by default 1 hour).
  • - *
- */ - @Idempotent // *** THE MAGIC IS HERE *** - @Logging(logEvent = true) - public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { - Map headers = new HashMap<>(); - - headers.put("Content-Type", "application/json"); - headers.put("Access-Control-Allow-Origin", "*"); - headers.put("Access-Control-Allow-Methods", "GET, OPTIONS"); - headers.put("Access-Control-Allow-Headers", "*"); - - APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() - .withHeaders(headers); - try { - String address = JsonConfig.get().getObjectMapper().readTree(input.getBody()).get("address").asText(); - final String pageContents = this.getPageContents(address); - String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); - - log.info("ip is {}", pageContents); - return response - .withStatusCode(200) - .withBody(output); - - } catch (IOException e) { - return response - .withBody("{}") - .withStatusCode(500); - } - } - - // we could also put the @Idempotent annotation here, but using it on the handler avoids executing the handler (cost reduction). - // Use it on other methods to handle multiple items (with SQS batch processing for example) - private String getPageContents(String address) throws IOException { - URL url = new URL(address); - try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { - return br.lines().collect(Collectors.joining(System.lineSeparator())); - } - } -} \ No newline at end of file diff --git a/java/Idempotency/Function/src/test/java/helloworld/AppTest.java b/java/Idempotency/Function/src/test/java/helloworld/AppTest.java deleted file mode 100644 index 7a5304e..0000000 --- a/java/Idempotency/Function/src/test/java/helloworld/AppTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package helloworld; - -import com.amazonaws.services.dynamodbv2.local.main.ServerRunner; -import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer; -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import com.amazonaws.services.lambda.runtime.tests.EventLoader; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; -import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; -import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.*; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.URI; - -public class AppTest { - @Mock - private Context context; - private App app; - private static DynamoDbClient client; - - @BeforeAll - public static void setupDynamoLocal() { - int port = getFreePort(); - try { - DynamoDBProxyServer dynamoProxy = ServerRunner.createServerFromCommandLineArgs(new String[]{ - "-inMemory", - "-port", - Integer.toString(port) - }); - dynamoProxy.start(); - } catch (Exception e) { - throw new RuntimeException(); - } - - client = DynamoDbClient.builder() - .httpClient(UrlConnectionHttpClient.builder().build()) - .region(Region.EU_WEST_1) - .endpointOverride(URI.create("http://localhost:" + port)) - .credentialsProvider(StaticCredentialsProvider.create( - AwsBasicCredentials.create("FAKE", "FAKE"))) - .build(); - - client.createTable(CreateTableRequest.builder() - .tableName("idempotency") - .keySchema(KeySchemaElement.builder().keyType(KeyType.HASH).attributeName("id").build()) - .attributeDefinitions( - AttributeDefinition.builder().attributeName("id").attributeType(ScalarAttributeType.S).build() - ) - .billingMode(BillingMode.PAY_PER_REQUEST) - .build()); - } - - private static int getFreePort() { - try { - ServerSocket socket = new ServerSocket(0); - int port = socket.getLocalPort(); - socket.close(); - return port; - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - } - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - app = new App(client); - } - - @Test - public void testApp() { - APIGatewayProxyResponseEvent response = app.handleRequest(EventLoader.loadApiGatewayRestEvent("event.json"), context); - Assertions.assertNotNull(response); - Assertions.assertTrue(response.getBody().contains("hello world")); - } -} diff --git a/java/Idempotency/Function/src/test/resources/event.json b/java/Idempotency/Function/src/test/resources/event.json deleted file mode 100644 index fd7f5ac..0000000 --- a/java/Idempotency/Function/src/test/resources/event.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "body": "{\"address\": \"https://checkip.amazonaws.com\"}", - "resource": "/{proxy+}", - "path": "/path/to/resource", - "httpMethod": "POST", - "isBase64Encoded": false, - "queryStringParameters": { - "foo": "bar" - }, - "pathParameters": { - "proxy": "/path/to/resource" - }, - "stageVariables": { - "baz": "qux" - }, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Accept-Encoding": "gzip, deflate, sdch", - "Accept-Language": "en-US,en;q=0.8", - "Cache-Control": "max-age=0", - "CloudFront-Forwarded-Proto": "https", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-Mobile-Viewer": "false", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Tablet-Viewer": "false", - "CloudFront-Viewer-Country": "US", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "Upgrade-Insecure-Requests": "1", - "User-Agent": "Custom User Agent String", - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "X-Forwarded-Port": "443", - "X-Forwarded-Proto": "https" - }, - "requestContext": { - "accountId": "123456789012", - "resourceId": "123456", - "stage": "prod", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "requestTime": "09/Apr/2015:12:34:56 +0000", - "requestTimeEpoch": 1428582896000, - "identity": { - "cognitoIdentityPoolId": null, - "accountId": null, - "cognitoIdentityId": null, - "caller": null, - "accessKey": null, - "sourceIp": "127.0.0.1", - "cognitoAuthenticationType": null, - "cognitoAuthenticationProvider": null, - "userArn": null, - "userAgent": "Custom User Agent String", - "user": null - }, - "path": "/prod/path/to/resource", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "apiId": "1234567890", - "protocol": "HTTP/1.1" - } - } - \ No newline at end of file diff --git a/java/Idempotency/README.md b/java/Idempotency/README.md deleted file mode 100644 index a919f0c..0000000 --- a/java/Idempotency/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Idempotency - -This project contains an example of Lambda function using the idempotency module of Lambda Powertools for Java. For more information on this module, please refer to the [documentation](https://awslabs.github.io/aws-lambda-powertools-java/utilities/idempotency/). - -## Deploy the sample application - -This sample is based on Serverless Application Model (SAM) and you can use the SAM Command Line Interface (SAM CLI) to build it and deploy it to AWS. - -To use the SAM CLI, you need the following tools. - -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) -* Maven - [Install Maven](https://maven.apache.org/install.html) -* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -Coreutilities$ sam build -Coreutilities$ sam deploy --guided -``` diff --git a/java/Idempotency/template.yaml b/java/Idempotency/template.yaml deleted file mode 100644 index d0708c6..0000000 --- a/java/Idempotency/template.yaml +++ /dev/null @@ -1,59 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - Idempotency demo - -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active - Environment: - Variables: - POWERTOOLS_LOG_LEVEL: INFO - POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1 - POWERTOOLS_LOGGER_LOG_EVENT: true - -Resources: - IdempotencyTable: - Type: AWS::DynamoDB::Table - Properties: - AttributeDefinitions: - - AttributeName: id - AttributeType: S - KeySchema: - - AttributeName: id - KeyType: HASH - TimeToLiveSpecification: - AttributeName: expiration - Enabled: true - BillingMode: PAY_PER_REQUEST - - IdempotencyFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: helloworld.App::handleRequest - Policies: - - DynamoDBCrudPolicy: - TableName: !Ref IdempotencyTable - Environment: - Variables: - POWERTOOLS_SERVICE_NAME: idempotency - IDEMPOTENCY_TABLE: !Ref IdempotencyTable - Events: - HelloWorld: - Type: Api - Properties: - Path: /helloidem - Method: post - -Outputs: - HelloWorldApi: - Description: "API Gateway endpoint URL for Prod stage for Idempotent function" - Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/helloidem/" - HelloWorldFunction: - Description: "Idempotent Lambda Function ARN" - Value: !GetAtt IdempotencyFunction.Arn - diff --git a/java/Parameters/Function/pom.xml b/java/Parameters/Function/pom.xml deleted file mode 100644 index f8e9704..0000000 --- a/java/Parameters/Function/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - demo - Functions - 1.0 - jar - Sample app demoing parameters utility of Powertools. - - 11 - 11 - 2.17.1 - UTF-8 - - - - - software.amazon.lambda - powertools-logging - 1.11.0 - - - software.amazon.lambda - powertools-parameters - 1.11.0 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - com.amazonaws - aws-lambda-java-events - 3.11.0 - - - - - org.mockito - mockito-core - 4.3.1 - test - - - org.junit.jupiter - junit-jupiter-api - 5.8.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.8.2 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 2.22.0 - - - org.codehaus.mojo - aspectj-maven-plugin - 1.14.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.target} - - - software.amazon.lambda - powertools-parameters - - - - - - - compile - - - - - - - diff --git a/java/Parameters/Function/src/main/java/org/demo/parameters/MyObject.java b/java/Parameters/Function/src/main/java/org/demo/parameters/MyObject.java deleted file mode 100644 index 2cf1452..0000000 --- a/java/Parameters/Function/src/main/java/org/demo/parameters/MyObject.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.demo.parameters; - -public class MyObject { - - private long id; - private String code; - - public MyObject() { - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - @Override - public String toString() { - return "MyObject{" + - "id=" + id + - ", code='" + code + '\'' + - '}'; - } -} diff --git a/java/Parameters/Function/src/main/java/org/demo/parameters/ParametersFunction.java b/java/Parameters/Function/src/main/java/org/demo/parameters/ParametersFunction.java deleted file mode 100644 index f5d98a4..0000000 --- a/java/Parameters/Function/src/main/java/org/demo/parameters/ParametersFunction.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.demo.parameters; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import software.amazon.lambda.powertools.parameters.ParamManager; -import software.amazon.lambda.powertools.parameters.SSMProvider; -import software.amazon.lambda.powertools.parameters.SecretsProvider; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -import static java.time.temporal.ChronoUnit.SECONDS; -import static software.amazon.lambda.powertools.parameters.transform.Transformer.base64; -import static software.amazon.lambda.powertools.parameters.transform.Transformer.json; - -public class ParametersFunction implements RequestHandler { - private final static Logger log = LogManager.getLogger(); - - SSMProvider ssmProvider = ParamManager.getSsmProvider(); - SecretsProvider secretsProvider = ParamManager.getSecretsProvider(); - - String simpleValue = ssmProvider.defaultMaxAge(30, SECONDS).get("/powertools-java/sample/simplekey"); - String listValue = ssmProvider.withMaxAge(60, SECONDS).get("/powertools-java/sample/keylist"); - MyObject jsonObj = ssmProvider.withTransformation(json).get("/powertools-java/sample/keyjson", MyObject.class); - Map allValues = ssmProvider.getMultiple("/powertools-java/sample"); - String b64value = ssmProvider.withTransformation(base64).get("/powertools-java/sample/keybase64"); - - Map secretJson = secretsProvider.withTransformation(json).get("/powertools-java/userpwd", Map.class); - MyObject secretJsonObj = secretsProvider.withMaxAge(42, SECONDS).withTransformation(json).get("/powertools-java/secretcode", MyObject.class); - - @Override - public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) { - - log.info("\n=============== SSM Parameter Store ==============="); - log.info("simplevalue={}, listvalue={}, b64value={}\n", simpleValue, listValue, b64value); - log.info("jsonobj={}\n", jsonObj); - - log.info("allvalues (multiple):"); - allValues.forEach((key, value) -> log.info("- {}={}\n", key, value)); - - log.info("\n=============== Secrets Manager ==============="); - log.info("secretjson:"); - secretJson.forEach((key, value) -> log.info("- {}={}\n", key, value)); - log.info("secretjsonobj={}\n", secretJsonObj); - - Map headers = new HashMap<>(); - headers.put("Content-Type", "application/json"); - headers.put("X-Custom-Header", "application/json"); - - APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() - .withHeaders(headers); - try { - final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); - String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); - - return response - .withStatusCode(200) - .withBody(output); - } catch (IOException e) { - return response - .withBody("{}") - .withStatusCode(500); - } - } - - private String getPageContents(String address) throws IOException{ - URL url = new URL(address); - try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { - return br.lines().collect(Collectors.joining(System.lineSeparator())); - } - } -} diff --git a/java/Parameters/Function/src/main/resources/log4j2.xml b/java/Parameters/Function/src/main/resources/log4j2.xml deleted file mode 100644 index 033da8a..0000000 --- a/java/Parameters/Function/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java/Parameters/README.md b/java/Parameters/README.md deleted file mode 100644 index c03f407..0000000 --- a/java/Parameters/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Parameters - -This project contains an example of Lambda function using the parameters module of Lambda Powertools for Java. For more information on this module, please refer to the [documentation](https://awslabs.github.io/aws-lambda-powertools-java/utilities/parameters/). - -## Deploy the sample application - -This sample is based on Serverless Application Model (SAM) and you can use the SAM Command Line Interface (SAM CLI) to build it and deploy it to AWS. - -To use the SAM CLI, you need the following tools. - -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) -* Maven - [Install Maven](https://maven.apache.org/install.html) -* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -sam build -sam deploy --guided -``` diff --git a/java/Parameters/template.yaml b/java/Parameters/template.yaml deleted file mode 100644 index d9038d3..0000000 --- a/java/Parameters/template.yaml +++ /dev/null @@ -1,97 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - validation demo - -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active - - -Resources: - ParametersFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: org.demo.parameters.ParametersFunction::handleRequest - MemorySize: 512 - Tracing: Active - Policies: - - AWSSecretsManagerGetSecretValuePolicy: - SecretArn: !Ref UserPwd - - AWSSecretsManagerGetSecretValuePolicy: - SecretArn: !Ref SecretConfig - - Statement: - - Sid: SSMGetParameterPolicy - Effect: Allow - Action: - - ssm:GetParameter - - ssm:GetParameters - - ssm:GetParametersByPath - Resource: '*' - Events: - HelloWorld: - Type: Api - Properties: - Path: /params - Method: get - - UserPwd: - Type: AWS::SecretsManager::Secret - Properties: - Name: /powertools-java/userpwd - Description: Generated secret for lambda-powertools-java powertools-parameters - module - GenerateSecretString: - SecretStringTemplate: '{"username": "test-user"}' - GenerateStringKey: password - PasswordLength: 15 - ExcludeCharacters: '"@/\' - SecretConfig: - Type: AWS::SecretsManager::Secret - Properties: - Name: /powertools-java/secretcode - Description: Json secret for lambda-powertools-java powertools-parameters module - SecretString: '{"id":23443,"code":"hk38543oj24kn796kp67bkb234gkj679l68"}' - BasicParameter: - Type: AWS::SSM::Parameter - Properties: - Name: /powertools-java/sample/simplekey - Type: String - Value: simplevalue - Description: Simple SSM Parameter for lambda-powertools-java powertools-parameters - module - ParameterList: - Type: AWS::SSM::Parameter - Properties: - Name: /powertools-java/sample/keylist - Type: StringList - Value: value1,value2,value3 - Description: SSM Parameter List for lambda-powertools-java powertools-parameters - module - JsonParameter: - Type: AWS::SSM::Parameter - Properties: - Name: /powertools-java/sample/keyjson - Type: String - Value: '{"id":23443,"code":"hk38543oj24kn796kp67bkb234gkj679l68"}' - Description: Json SSM Parameter for lambda-powertools-java powertools-parameters - module - Base64Parameter: - Type: AWS::SSM::Parameter - Properties: - Name: /powertools-java/sample/keybase64 - Type: String - Value: aGVsbG8gd29ybGQ= - Description: Base64 SSM Parameter for lambda-powertools-java powertools-parameters module - -Outputs: - ParametersApi: - Description: "API Gateway endpoint URL for Prod stage for Parameters function" - Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/params/" - ParametersFunction: - Description: "Parameters Lambda Function ARN" - Value: !GetAtt ParametersFunction.Arn \ No newline at end of file diff --git a/java/SerializationUtilities/Function/pom.xml b/java/SerializationUtilities/Function/pom.xml deleted file mode 100644 index 706d4e5..0000000 --- a/java/SerializationUtilities/Function/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - 4.0.0 - demo - Functions - 1.0 - jar - Sample app demoing serialization utility of Powertools. - - 11 - 11 - 2.17.1 - UTF-8 - - - - - software.amazon.lambda - powertools-logging - 1.12.0 - - - software.amazon.lambda - powertools-serialization - 1.12.0 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - com.amazonaws - aws-lambda-java-events - 3.11.0 - - - - - org.mockito - mockito-core - 4.3.1 - test - - - org.junit.jupiter - junit-jupiter-api - 5.8.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.8.2 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 2.22.0 - - - - diff --git a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/APIGatewayRequestDeserializationFunction.java b/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/APIGatewayRequestDeserializationFunction.java deleted file mode 100644 index 4df9374..0000000 --- a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/APIGatewayRequestDeserializationFunction.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.demo.serialization; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Map; - -import static software.amazon.lambda.powertools.utilities.EventDeserializer.extractDataFrom; - - -public class APIGatewayRequestDeserializationFunction implements RequestHandler { - - private final static Logger LOGGER = LogManager.getLogger(APIGatewayRequestDeserializationFunction.class); - private static final Map HEADERS = Map.of( - "Content-Type", "application/json", - "X-Custom-Header", "application/json"); - - public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { - - Product product = extractDataFrom(event).as(Product.class); - LOGGER.info("\n=============== Deserialized request body: ==============="); - LOGGER.info("product={}\n", product); - - return new APIGatewayProxyResponseEvent() - .withHeaders(HEADERS) - .withStatusCode(200) - .withBody("Received request for productId: " + product.getId()); - } -} - diff --git a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/Product.java b/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/Product.java deleted file mode 100644 index fb94a99..0000000 --- a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/Product.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.demo.serialization; - -public class Product { - private long id; - private String name; - private double price; - - public Product() { - } - - public Product(long id, String name, double price) { - this.id = id; - this.name = name; - this.price = price; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - @Override - public String toString() { - return "Product{" + - "id=" + id + - ", name='" + name + '\'' + - ", price=" + price + - '}'; - } -} diff --git a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/SQSEventDeserializationFunction.java b/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/SQSEventDeserializationFunction.java deleted file mode 100644 index 129fe02..0000000 --- a/java/SerializationUtilities/Function/src/main/java/org/demo/serialization/SQSEventDeserializationFunction.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.demo.serialization; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.List; - -import static software.amazon.lambda.powertools.utilities.EventDeserializer.extractDataFrom; - - -public class SQSEventDeserializationFunction implements RequestHandler { - - private final static Logger LOGGER = LogManager.getLogger(SQSEventDeserializationFunction.class); - - public String handleRequest(SQSEvent event, Context context) { - List products = extractDataFrom(event).asListOf(Product.class); - - LOGGER.info("\n=============== Deserialized messages: ==============="); - LOGGER.info("products={}\n", products); - - return "Number of received messages: " + products.size(); - } -} - diff --git a/java/SerializationUtilities/Function/src/main/resources/log4j2.xml b/java/SerializationUtilities/Function/src/main/resources/log4j2.xml deleted file mode 100644 index 033da8a..0000000 --- a/java/SerializationUtilities/Function/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/APIGatewayRequestDeserializationFunctionTest.java b/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/APIGatewayRequestDeserializationFunctionTest.java deleted file mode 100644 index 5d5da7e..0000000 --- a/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/APIGatewayRequestDeserializationFunctionTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.demo.serialization; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class APIGatewayRequestDeserializationFunctionTest { - - @Mock - private Context context; - private APIGatewayRequestDeserializationFunction deserializationFunction; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - deserializationFunction = new APIGatewayRequestDeserializationFunction(); - } - - @Test - public void shouldReturnOkStatusWithProductId() { - String body = "{\"id\":1234, \"name\":\"product\", \"price\":42}"; - APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent().withBody(body); - - APIGatewayProxyResponseEvent response = deserializationFunction.handleRequest(request, context); - - assertEquals(200, response.getStatusCode()); - assertEquals("Received request for productId: 1234", response.getBody()); - } -} \ No newline at end of file diff --git a/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/SQSEventDeserializationFunctionTest.java b/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/SQSEventDeserializationFunctionTest.java deleted file mode 100644 index 393aa9a..0000000 --- a/java/SerializationUtilities/Function/src/test/java/org/demo/serialization/SQSEventDeserializationFunctionTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.demo.serialization; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class SQSEventDeserializationFunctionTest { - - @Mock - private Context context; - private SQSEventDeserializationFunction deserializationFunction; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - deserializationFunction = new SQSEventDeserializationFunction(); - } - - @Test - public void shouldReturnNumberOfReceivedMessages() { - SQSEvent.SQSMessage message1 = messageWithBody("{ \"id\": 1234, \"name\": \"product\", \"price\": 42}"); - SQSEvent.SQSMessage message2 = messageWithBody("{ \"id\": 12345, \"name\": \"product5\", \"price\": 45}"); - SQSEvent event = new SQSEvent(); - event.setRecords(List.of(message1, message2)); - - String response = deserializationFunction.handleRequest(event, context); - - assertEquals("Number of received messages: 2", response); - } - - private SQSEvent.SQSMessage messageWithBody(String body) { - SQSEvent.SQSMessage record1 = new SQSEvent.SQSMessage(); - record1.setBody(body); - return record1; - } -} \ No newline at end of file diff --git a/java/SerializationUtilities/README.md b/java/SerializationUtilities/README.md deleted file mode 100644 index 68c4b4a..0000000 --- a/java/SerializationUtilities/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Deserialization - -This project contains an example of Lambda function using the serialization utilities module of Lambda Powertools for Java. For more information on this module, please refer to the [documentation](https://awslabs.github.io/aws-lambda-powertools-java/utilities/serialization/). - -## Deploy the sample application - -This sample is based on Serverless Application Model (SAM) and you can use the SAM Command Line Interface (SAM CLI) to build it and deploy it to AWS. - -To use the SAM CLI, you need the following tools. - -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) -* Maven - [Install Maven](https://maven.apache.org/install.html) -* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -sam build -sam deploy --guided -``` diff --git a/java/SerializationUtilities/events/APIGatewayEvent.json b/java/SerializationUtilities/events/APIGatewayEvent.json deleted file mode 100644 index cb38a34..0000000 --- a/java/SerializationUtilities/events/APIGatewayEvent.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "body": "{\"id\":1234, \"name\":\"product\", \"price\":42}", - "resource": "/{proxy+}", - "path": "/path/to/resource", - "httpMethod": "POST", - "isBase64Encoded": false, - "queryStringParameters": { - "foo": "bar" - }, - "pathParameters": { - "proxy": "/path/to/resource" - }, - "stageVariables": { - "baz": "qux" - }, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Accept-Encoding": "gzip, deflate, sdch", - "Accept-Language": "en-US,en;q=0.8", - "Cache-Control": "max-age=0", - "CloudFront-Forwarded-Proto": "https", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-Mobile-Viewer": "false", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Tablet-Viewer": "false", - "CloudFront-Viewer-Country": "US", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "Upgrade-Insecure-Requests": "1", - "User-Agent": "Custom User Agent String", - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "X-Forwarded-Port": "443", - "X-Forwarded-Proto": "https" - }, - "requestContext": { - "accountId": "123456789012", - "resourceId": "123456", - "stage": "prod", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "requestTime": "09/Apr/2015:12:34:56 +0000", - "requestTimeEpoch": 1428582896000, - "identity": { - "cognitoIdentityPoolId": null, - "accountId": null, - "cognitoIdentityId": null, - "caller": null, - "accessKey": null, - "sourceIp": "127.0.0.1", - "cognitoAuthenticationType": null, - "cognitoAuthenticationProvider": null, - "userArn": null, - "userAgent": "Custom User Agent String", - "user": null - }, - "path": "/prod/path/to/resource", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "apiId": "1234567890", - "protocol": "HTTP/1.1" - } - } - \ No newline at end of file diff --git a/java/SerializationUtilities/events/SQSEvent.json b/java/SerializationUtilities/events/SQSEvent.json deleted file mode 100644 index 9056d3e..0000000 --- a/java/SerializationUtilities/events/SQSEvent.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Records": [ - { - "messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54", - "receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==", - "body": "{ \"id\": 1234, \"name\": \"product\", \"price\": 42}", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1601975706495", - "SenderId": "AROAIFU437PVZ5L2J53F5", - "ApproximateFirstReceiveTimestamp": "1601975706499" - }, - "messageAttributes": { - }, - "md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", - "awsRegion": "eu-central-1" - }, - { - "messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54", - "receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==", - "body": "{ \"id\": 12345, \"name\": \"product5\", \"price\": 45}", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1601975706495", - "SenderId": "AROAIFU437PVZ5L2J53F5", - "ApproximateFirstReceiveTimestamp": "1601975706499" - }, - "messageAttributes": { - - }, - "md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda", - "awsRegion": "eu-central-1" - } - ] -} \ No newline at end of file diff --git a/java/SerializationUtilities/template.yaml b/java/SerializationUtilities/template.yaml deleted file mode 100644 index 66033bd..0000000 --- a/java/SerializationUtilities/template.yaml +++ /dev/null @@ -1,63 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - serialization utils demo - -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active - - -Resources: - APIGatewayDeserializationFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: org.demo.serialization.APIGatewayRequestDeserializationFunction::handleRequest - Events: - Product: - Type: Api - Properties: - Path: /product - Method: post - - DemoSqsQueue: - Type: AWS::SQS::Queue - Properties: - QueueName: "sqs-event-deserialization-queue" - - SQSEventDeserializationFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: org.demo.serialization.SQSEventDeserializationFunction::handleRequest - Policies: - - Statement: - - Sid: SQSSendMessageBatch - Effect: Allow - Action: - - sqs:SendMessageBatch - - sqs:SendMessage - Resource: !GetAtt DemoSqsQueue.Arn - Events: - SQSEvent: - Type: SQS - Properties: - Queue: !GetAtt DemoSqsQueue.Arn - BatchSize: 2 - MaximumBatchingWindowInSeconds: 30 - - -Outputs: - Api: - Description: "API Gateway endpoint URL for Prod stage for Serialization function" - Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/product/" - Function: - Description: "Serialization Lambda Function ARN" - Value: !GetAtt APIGatewayDeserializationFunction.Arn - DemoSqsQueue: - Description: "ARN for SQS queue" - Value: !GetAtt DemoSqsQueue.Arn \ No newline at end of file diff --git a/java/SqsBatchProcessing/Functions/pom.xml b/java/SqsBatchProcessing/Functions/pom.xml deleted file mode 100644 index 7969328..0000000 --- a/java/SqsBatchProcessing/Functions/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - 4.0.0 - demo - Functions - 1.0 - jar - Sample app demoing SQS Batch Processing utility of Powertools. - - 11 - 11 - 2.19.0 - UTF-8 - - - - - software.amazon.lambda - powertools-logging - 1.12.3 - - - software.amazon.lambda - powertools-sqs - 1.12.3 - - - software.amazon.awssdk - url-connection-client - 2.17.285 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - com.amazonaws - aws-lambda-java-events - 3.11.0 - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - - - org.apache.logging.log4j - log4j-api - ${log4j.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.13.4 - - - - junit - junit - 4.13.2 - test - - - - - - - org.codehaus.mojo - aspectj-maven-plugin - 1.14.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.target} - - - software.amazon.lambda - powertools-logging - - - software.amazon.lambda - powertools-sqs - - - - - - - compile - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.4.0 - - - package - - shade - - - - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.15 - - - - - - diff --git a/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsMessageSender.java b/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsMessageSender.java deleted file mode 100644 index bd49d64..0000000 --- a/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsMessageSender.java +++ /dev/null @@ -1,78 +0,0 @@ - -package org.demo.sqs; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.ScheduledEvent; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.joda.JodaModule; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; -import software.amazon.awssdk.services.sqs.SqsClient; -import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; -import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; -import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; -import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; -import software.amazon.lambda.powertools.logging.Logging; -import software.amazon.lambda.powertools.logging.LoggingUtils; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.stream.IntStream; - -import static java.util.stream.Collectors.toList; - -public class SqsMessageSender implements RequestHandler { - - private static final Logger log = LogManager.getLogger(SqsMessageSender.class); - - private static final SqsClient sqsClient = SqsClient.builder() - .httpClient(UrlConnectionHttpClient.create()) - .build(); - - private static final Random random = new Random(); - - private static final ObjectMapper objectMapper; - - static { - objectMapper = new ObjectMapper(); - objectMapper.registerModule(new JodaModule()); - LoggingUtils.defaultObjectMapper(objectMapper); - } - - @Logging(logEvent = true) - public String handleRequest(final ScheduledEvent input, final Context context) { - String queueUrl = System.getenv("QUEUE_URL"); - - // Push 5 messages on each invoke. - List batchRequestEntries = IntStream.range(0, 5) - .mapToObj(value -> { - Map attributeValueHashMap = new HashMap<>(); - attributeValueHashMap.put("Key" + value, MessageAttributeValue.builder() - .dataType("String") - .stringValue("Value" + value) - .build()); - - byte[] array = new byte[7]; - random.nextBytes(array); - - return SendMessageBatchRequestEntry.builder() - .messageAttributes(attributeValueHashMap) - .id(input.getId() + value) - .messageBody("Sample Message " + value) - .build(); - }).collect(toList()); - - SendMessageBatchResponse sendMessageBatchResponse = sqsClient.sendMessageBatch(SendMessageBatchRequest.builder() - .queueUrl(queueUrl) - .entries(batchRequestEntries) - .build()); - - log.info("Sent Message {}", sendMessageBatchResponse); - - return "Success"; - } -} \ No newline at end of file diff --git a/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsPoller.java b/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsPoller.java deleted file mode 100644 index 04e4d48..0000000 --- a/java/SqsBatchProcessing/Functions/src/main/java/org/demo/sqs/SqsPoller.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.demo.sqs; - -import java.util.Random; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; -import software.amazon.awssdk.services.sqs.SqsClient; -import software.amazon.lambda.powertools.logging.Logging; -import software.amazon.lambda.powertools.sqs.SqsBatch; -import software.amazon.lambda.powertools.sqs.SqsMessageHandler; -import software.amazon.lambda.powertools.sqs.SqsUtils; - -import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; - -/** - * Handler for requests to Lambda function. - */ -public class SqsPoller implements RequestHandler { - - Logger log = LogManager.getLogger(SqsPoller.class); - Random random = new Random(100); - - static { - // https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/lambda-optimize-starttime.html - SqsUtils.overrideSqsClient(SqsClient.builder() - .httpClient(UrlConnectionHttpClient.create()) - .build()); - } - - @SqsBatch(value = BatchProcessor.class, nonRetryableExceptions = {IllegalArgumentException.class}) - @Logging(logEvent = true) - public String handleRequest(final SQSEvent input, final Context context) { - return "Success"; - } - - private class BatchProcessor implements SqsMessageHandler { - @Override - public String process(SQSMessage message) { - log.info("Processing message with id {}", message.getMessageId()); - - int nextInt = random.nextInt(100); - - if(nextInt <= 10) { - log.info("Randomly picked message with id {} as business validation failure.", message.getMessageId()); - throw new IllegalArgumentException("Failed business validation. No point of retrying. Move me to DLQ." + message.getMessageId()); - } - - if(nextInt > 90) { - log.info("Randomly picked message with id {} as intermittent failure.", message.getMessageId()); - throw new RuntimeException("Failed due to intermittent issue. Will be sent back for retry." + message.getMessageId()); - } - - return "Success"; - } - } -} \ No newline at end of file diff --git a/java/SqsBatchProcessing/Functions/src/main/resources/log4j2.xml b/java/SqsBatchProcessing/Functions/src/main/resources/log4j2.xml deleted file mode 100644 index e1fd14c..0000000 --- a/java/SqsBatchProcessing/Functions/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java/SqsBatchProcessing/Functions/src/test/java/org/demo/sqs/SqsPollerTest.java b/java/SqsBatchProcessing/Functions/src/test/java/org/demo/sqs/SqsPollerTest.java deleted file mode 100644 index 4d1e859..0000000 --- a/java/SqsBatchProcessing/Functions/src/test/java/org/demo/sqs/SqsPollerTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.demo.sqs; - -import org.junit.Test; - -public class SqsPollerTest { - - @Test - public void successfulResponse() { - SqsPoller app = new SqsPoller(); - app.handleRequest(null, null); - } -} diff --git a/java/SqsBatchProcessing/README.md b/java/SqsBatchProcessing/README.md deleted file mode 100644 index 2b6da65..0000000 --- a/java/SqsBatchProcessing/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## SqsBatchProcessingDemo - -Demos setup of SQS Batch processing via Powertools diff --git a/java/SqsBatchProcessing/events/event.json b/java/SqsBatchProcessing/events/event.json deleted file mode 100644 index 3822fad..0000000 --- a/java/SqsBatchProcessing/events/event.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "body": "{\"message\": \"hello world\"}", - "resource": "/{proxy+}", - "path": "/path/to/resource", - "httpMethod": "POST", - "isBase64Encoded": false, - "queryStringParameters": { - "foo": "bar" - }, - "pathParameters": { - "proxy": "/path/to/resource" - }, - "stageVariables": { - "baz": "qux" - }, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Accept-Encoding": "gzip, deflate, sdch", - "Accept-Language": "en-US,en;q=0.8", - "Cache-Control": "max-age=0", - "CloudFront-Forwarded-Proto": "https", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-Mobile-Viewer": "false", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Tablet-Viewer": "false", - "CloudFront-Viewer-Country": "US", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "Upgrade-Insecure-Requests": "1", - "User-Agent": "Custom User Agent String", - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "X-Forwarded-Port": "443", - "X-Forwarded-Proto": "https" - }, - "requestContext": { - "accountId": "123456789012", - "resourceId": "123456", - "stage": "prod", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "requestTime": "09/Apr/2015:12:34:56 +0000", - "requestTimeEpoch": 1428582896000, - "identity": { - "cognitoIdentityPoolId": null, - "accountId": null, - "cognitoIdentityId": null, - "caller": null, - "accessKey": null, - "sourceIp": "127.0.0.1", - "cognitoAuthenticationType": null, - "cognitoAuthenticationProvider": null, - "userArn": null, - "userAgent": "Custom User Agent String", - "user": null - }, - "path": "/prod/path/to/resource", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "apiId": "1234567890", - "protocol": "HTTP/1.1" - } - } - \ No newline at end of file diff --git a/java/SqsBatchProcessing/template.yaml b/java/SqsBatchProcessing/template.yaml deleted file mode 100644 index cb99213..0000000 --- a/java/SqsBatchProcessing/template.yaml +++ /dev/null @@ -1,148 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - sqs batch processing demo - -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active - Environment: - Variables: - # Powertools env vars: https://awslabs.github.io/aws-lambda-powertools-python/#environment-variables - POWERTOOLS_LOG_LEVEL: INFO - POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1 - POWERTOOLS_LOGGER_LOG_EVENT: true - -Resources: - CustomerKey: - Type: AWS::KMS::Key - Properties: - Description: KMS key for encrypted queues - Enabled: true - KeyPolicy: - Version: '2012-10-17' - Statement: - - Sid: Enable IAM User Permissions - Effect: Allow - Principal: - AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root' - Action: 'kms:*' - Resource: '*' - - Sid: Allow use of the key - Effect: Allow - Principal: - Service: lambda.amazonaws.com - Action: - - kms:Decrypt - - kms:GenerateDataKey - Resource: '*' - - CustomerKeyAlias: - Type: AWS::KMS::Alias - Properties: - AliasName: alias/sqs-key - TargetKeyId: !Ref CustomerKey - - DemoDlqSqsQueue: - Type: AWS::SQS::Queue - Properties: - KmsMasterKeyId: !Ref CustomerKey - - DemoSqsQueue: - Type: AWS::SQS::Queue - Properties: - RedrivePolicy: - deadLetterTargetArn: - Fn::GetAtt: - - "DemoDlqSqsQueue" - - "Arn" - maxReceiveCount: 2 - KmsMasterKeyId: !Ref CustomerKey - - DemoSQSSenderFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Functions - Handler: org.demo.sqs.SqsMessageSender::handleRequest - Environment: - Variables: - POWERTOOLS_SERVICE_NAME: sqs-demo - QUEUE_URL: !Ref DemoSqsQueue - Policies: - - Statement: - - Sid: SQSSendMessageBatch - Effect: Allow - Action: - - sqs:SendMessageBatch - - sqs:SendMessage - Resource: !GetAtt DemoSqsQueue.Arn - - Sid: SQSKMSKey - Effect: Allow - Action: - - kms:GenerateDataKey - - kms:Decrypt - Resource: !GetAtt CustomerKey.Arn - Events: - CWSchedule: - Type: Schedule - Properties: - Schedule: 'rate(5 minutes)' - Name: !Join ["-", ["message-producer-schedule", !Select [0, !Split [-, !Select [2, !Split [/, !Ref AWS::StackId ]]]]]] - Description: Produce message to SQS via a Lambda function - Enabled: true - - DemoSQSConsumerFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Functions - Handler: org.demo.sqs.SqsPoller::handleRequest - Environment: - Variables: - POWERTOOLS_SERVICE_NAME: sqs-demo - Policies: - - Statement: - - Sid: SQSDeleteGetAttribute - Effect: Allow - Action: - - sqs:DeleteMessageBatch - - sqs:GetQueueAttributes - Resource: !GetAtt DemoSqsQueue.Arn - - Sid: SQSSendMessageBatch - Effect: Allow - Action: - - sqs:SendMessageBatch - - sqs:SendMessage - Resource: !GetAtt DemoDlqSqsQueue.Arn - - Sid: SQSKMSKey - Effect: Allow - Action: - - kms:GenerateDataKey - - kms:Decrypt - Resource: !GetAtt CustomerKey.Arn - Events: - MySQSEvent: - Type: SQS - Properties: - Queue: !GetAtt DemoSqsQueue.Arn - BatchSize: 2 - MaximumBatchingWindowInSeconds: 300 - -Outputs: - DemoSqsQueue: - Description: "ARN for main SQS queue" - Value: !GetAtt DemoSqsQueue.Arn - DemoDlqSqsQueue: - Description: "ARN for DLQ" - Value: !GetAtt DemoDlqSqsQueue.Arn - DemoSQSSenderFunction: - Description: "Sender SQS Lambda Function ARN" - Value: !GetAtt DemoSQSSenderFunction.Arn - DemoSQSConsumerFunction: - Description: "Consumer SQS Lambda Function ARN" - Value: !GetAtt DemoSQSConsumerFunction.Arn - DemoSQSConsumerFunctionRole: - Description: "Implicit IAM Role created for SQS Lambda Function ARN" - Value: !GetAtt DemoSQSConsumerFunctionRole.Arn diff --git a/java/Validation/Function/pom.xml b/java/Validation/Function/pom.xml deleted file mode 100644 index b552c77..0000000 --- a/java/Validation/Function/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - 4.0.0 - demo - Functions - 1.0 - jar - Sample app demoing validation utility of Powertools. - - 11 - 11 - 2.17.1 - UTF-8 - - - - - software.amazon.lambda - powertools-logging - 1.11.0 - - - software.amazon.lambda - powertools-validation - 1.11.0 - - - com.amazonaws - aws-lambda-java-core - 1.2.1 - - - - - org.mockito - mockito-core - 4.3.1 - test - - - org.junit.jupiter - junit-jupiter-api - 5.8.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.8.2 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 2.22.0 - - - org.codehaus.mojo - aspectj-maven-plugin - 1.14.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.target} - - - software.amazon.lambda - powertools-validation - - - - - - - compile - - - - - - - diff --git a/java/Validation/Function/src/main/java/org/demo/validation/InboundValidation.java b/java/Validation/Function/src/main/java/org/demo/validation/InboundValidation.java deleted file mode 100644 index 184fbbc..0000000 --- a/java/Validation/Function/src/main/java/org/demo/validation/InboundValidation.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.demo.validation; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import software.amazon.lambda.powertools.validation.Validation; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Request handler for Lambda function which demonstrates validation of request message. - */ -public class InboundValidation implements RequestHandler { - - @Validation(inboundSchema = "classpath:/schema.json") - public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, Context context) { - Map headers = new HashMap<>(); - - headers.put("Content-Type", "application/json"); - headers.put("X-Custom-Header", "application/json"); - - APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() - .withHeaders(headers); - try { - final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); - String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); - - return response - .withStatusCode(200) - .withBody(output); - } catch (IOException e) { - return response - .withBody("{}") - .withStatusCode(500); - } - } - - private String getPageContents(String address) throws IOException { - URL url = new URL(address); - try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { - return br.lines().collect(Collectors.joining(System.lineSeparator())); - } - } -} diff --git a/java/Validation/Function/src/main/resources/schema.json b/java/Validation/Function/src/main/resources/schema.json deleted file mode 100644 index f38272f..0000000 --- a/java/Validation/Function/src/main/resources/schema.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "$id": "http://example.com/product.json", - "type": "object", - "title": "Product schema", - "description": "JSON schema to validate Products", - "default": {}, - "examples": [ - { - "id": 43242, - "name": "FooBar XY", - "price": 258 - } - ], - "required": [ - "id", - "name", - "price" - ], - "properties": { - "id": { - "$id": "#/properties/id", - "type": "integer", - "title": "Id of the product", - "description": "Unique identifier of the product", - "default": 0, - "examples": [ - 43242 - ] - }, - "name": { - "$id": "#/properties/name", - "type": "string", - "title": "Name of the product", - "description": "Explicit name of the product", - "minLength": 5, - "default": "", - "examples": [ - "FooBar XY" - ] - }, - "price": { - "$id": "#/properties/price", - "type": "number", - "title": "Price of the product", - "description": "Positive price of the product", - "default": 0, - "exclusiveMinimum": 0, - "examples": [ - 258.99 - ] - } - }, - "additionalProperties": true -} \ No newline at end of file diff --git a/java/Validation/Function/src/test/java/org/demo/validation/InboundValidationTest.java b/java/Validation/Function/src/test/java/org/demo/validation/InboundValidationTest.java deleted file mode 100644 index af47d3d..0000000 --- a/java/Validation/Function/src/test/java/org/demo/validation/InboundValidationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.demo.validation; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import software.amazon.lambda.powertools.validation.ValidationException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class InboundValidationTest { - - @Mock - private Context context; - private InboundValidation inboundValidation; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - inboundValidation = new InboundValidation(); - } - - @Test - public void shouldReturnOkStatusWhenInputIsValid() { - String body = "{\n" + - " \"id\": 43242,\n" + - " \"name\": \"FooBar XY\",\n" + - " \"price\": 258\n" + - " }"; - APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent().withBody(body); - - APIGatewayProxyResponseEvent response = inboundValidation.handleRequest(request, context); - - assertEquals(200, response.getStatusCode()); - } - - @Test - public void shouldThrowExceptionWhenRequestInInvalid() { - String bodyWithMissedId = "{\n" + - " \"name\": \"FooBar XY\",\n" + - " \"price\": 258\n" + - " }"; - APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent().withBody(bodyWithMissedId); - - assertThrows(ValidationException.class, () -> inboundValidation.handleRequest(request, context)); - } -} \ No newline at end of file diff --git a/java/Validation/README.md b/java/Validation/README.md deleted file mode 100644 index db631de..0000000 --- a/java/Validation/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Validation - -This project contains an example of Lambda function using the validation module of Lambda Powertools for Java. For more information on this module, please refer to the [documentation](https://awslabs.github.io/aws-lambda-powertools-java/utilities/validation/). - -## Deploy the sample application - -This sample is based on Serverless Application Model (SAM) and you can use the SAM Command Line Interface (SAM CLI) to build it and deploy it to AWS. - -To use the SAM CLI, you need the following tools. - -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) -* Maven - [Install Maven](https://maven.apache.org/install.html) -* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -sam build -sam deploy --guided -``` diff --git a/java/Validation/events/event.json b/java/Validation/events/event.json deleted file mode 100644 index 3822fad..0000000 --- a/java/Validation/events/event.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "body": "{\"message\": \"hello world\"}", - "resource": "/{proxy+}", - "path": "/path/to/resource", - "httpMethod": "POST", - "isBase64Encoded": false, - "queryStringParameters": { - "foo": "bar" - }, - "pathParameters": { - "proxy": "/path/to/resource" - }, - "stageVariables": { - "baz": "qux" - }, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Accept-Encoding": "gzip, deflate, sdch", - "Accept-Language": "en-US,en;q=0.8", - "Cache-Control": "max-age=0", - "CloudFront-Forwarded-Proto": "https", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-Mobile-Viewer": "false", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Tablet-Viewer": "false", - "CloudFront-Viewer-Country": "US", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "Upgrade-Insecure-Requests": "1", - "User-Agent": "Custom User Agent String", - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "X-Forwarded-Port": "443", - "X-Forwarded-Proto": "https" - }, - "requestContext": { - "accountId": "123456789012", - "resourceId": "123456", - "stage": "prod", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "requestTime": "09/Apr/2015:12:34:56 +0000", - "requestTimeEpoch": 1428582896000, - "identity": { - "cognitoIdentityPoolId": null, - "accountId": null, - "cognitoIdentityId": null, - "caller": null, - "accessKey": null, - "sourceIp": "127.0.0.1", - "cognitoAuthenticationType": null, - "cognitoAuthenticationProvider": null, - "userArn": null, - "userAgent": "Custom User Agent String", - "user": null - }, - "path": "/prod/path/to/resource", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "apiId": "1234567890", - "protocol": "HTTP/1.1" - } - } - \ No newline at end of file diff --git a/java/Validation/template.yaml b/java/Validation/template.yaml deleted file mode 100644 index ec3c941..0000000 --- a/java/Validation/template.yaml +++ /dev/null @@ -1,33 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: > - validation demo - -Globals: - Function: - Timeout: 20 - Runtime: java11 - MemorySize: 512 - Tracing: Active - - -Resources: - ValidationFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: Function - Handler: org.demo.validation.InboundValidation::handleRequest - Events: - HelloWorld: - Type: Api - Properties: - Path: /hello - Method: post - -Outputs: - Api: - Description: "API Gateway endpoint URL for Prod stage for Validation function" - Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" - Function: - Description: "Validation Lambda Function ARN" - Value: !GetAtt ValidationFunction.Arn \ No newline at end of file diff --git a/manifest.json b/manifest.json deleted file mode 100644 index 2bbc94d..0000000 --- a/manifest.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "java11": [ - { - "directory": "java/SqsBatchProcessing/Functions", - "displayName": "Demos setup of SQS Batch processing via Powertools", - "dependencyManager": "maven", - "appTemplate": "SqsBatchProcessing", - "javaVersion": "11" - }, - { - "directory": "java/CoreUtilities/Function", - "displayName": "Demos setup of Core utilities with proxies lambda function using api gateway", - "dependencyManager": "maven", - "appTemplate": "CoreUtilities", - "javaVersion": "11" - }, - { - "directory": "java/Idempotency/Function", - "displayName": "Demos setup of an idempotent Lambda function using Powertools", - "dependencyManager": "maven", - "appTemplate": "Idempotency", - "javaVersion": "11" - }, - { - "directory": "java/Validation/Function", - "displayName": "Demos setup of an validation Lambda function using Powertools", - "dependencyManager": "maven", - "appTemplate": "Validation", - "javaVersion": "11" - }, - { - "directory": "java/Parameters/Function", - "displayName": "Demos setup of an parameters Lambda function using Powertools", - "dependencyManager": "maven", - "appTemplate": "Parameters", - "javaVersion": "11" - }, - { - "directory": "java/SerializationUtilities/Function", - "displayName": "Demos setup of a serialization utilities Lambda functions using Powertools", - "dependencyManager": "maven", - "appTemplate": "SerializationUtilities", - "javaVersion": "11" - } - ] -} \ No newline at end of file