diff --git a/java11/hello-pt-gradle/README.md b/java11/hello-pt-gradle/README.md new file mode 100644 index 000000000..ec9954e48 --- /dev/null +++ b/java11/hello-pt-gradle/README.md @@ -0,0 +1,42 @@ +# Cookiecutter SAM for Java Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and Java. + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-java`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + + +License +------- + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) diff --git a/java11/hello-pt-gradle/__init__.py b/java11/hello-pt-gradle/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/java11/hello-pt-gradle/cookiecutter.json b/java11/hello-pt-gradle/cookiecutter.json new file mode 100644 index 000000000..6cf641b8f --- /dev/null +++ b/java11/hello-pt-gradle/cookiecutter.json @@ -0,0 +1,10 @@ +{ + "project_name": "sam-app-powertools-java", + "runtime": "java11", + "Powertools for AWS Lambda (Java) Logging": ["enabled","disabled"], + "Powertools for AWS Lambda (Java) Metrics": ["enabled","disabled"], + "Powertools for AWS Lambda (Java) Tracing": ["enabled","disabled"], + "_copy_without_render": [ + ".gitignore" + ] +} diff --git a/java11/hello-pt-gradle/tests/__init__.py b/java11/hello-pt-gradle/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/java11/hello-pt-gradle/tests/test_cookiecutter.py b/java11/hello-pt-gradle/tests/test_cookiecutter.py new file mode 100644 index 000000000..b92ab289a --- /dev/null +++ b/java11/hello-pt-gradle/tests/test_cookiecutter.py @@ -0,0 +1,40 @@ +""" + Tests cookiecutter baking process and rendered content +""" + +def test_project_tree(cookies): + result = cookies.bake(extra_context={ + 'project_name': 'hello sam' + }) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'hello sam' + assert result.project.isdir() + assert result.project.join('template.yaml').isfile() + assert result.project.join('README.md').isfile() + assert result.project.join('src').isdir() + assert result.project.join('src', 'main').isdir() + assert result.project.join('src', 'main', 'java').isdir() + assert result.project.join('src', 'main', 'java', 'helloworld').isdir() + assert result.project.join('src', 'main', 'java', 'helloworld', 'App.java').isfile() + assert result.project.join('src', 'test', 'java').isdir() + assert result.project.join('src', 'test', 'java', 'helloworld').isdir() + assert result.project.join('src', 'test', 'java', 'helloworld', 'AppTest.java').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'my_lambda'}) + app_file = result.project.join('src', 'main', 'java', 'helloworld', 'App.java') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "package helloword", + "class App implements RequestHandler", + "https://checkip.amazonaws.com", + "return new GatewayResponse", + "getPageContents", + ) + + for content in contents: + assert content in app_content diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/build.gradle b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/build.gradle new file mode 100644 index 000000000..07cd382c7 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/build.gradle @@ -0,0 +1,25 @@ +plugins { + id 'java' + id "io.freefair.aspectj.post-compile-weaving" version "8.1.0" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation "org.aspectj:aspectjrt:1.9.8.RC3" + implementation 'com.amazonaws:aws-lambda-java-core:1.2.2' + implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.2' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.2.2' + implementation 'com.amazonaws:aws-lambda-java-events:3.11.0' + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.2' + implementation 'org.aspectj:aspectjtools:1.9.19' + aspect 'software.amazon.lambda:powertools-tracing:1.17.0' + aspect 'software.amazon.lambda:powertools-logging:1.17.0' + aspect 'software.amazon.lambda:powertools-metrics:1.17.0' + testImplementation 'junit:junit:4.13.2' +} + +sourceCompatibility = 11 +targetCompatibility = 11 diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.jar b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..7454180f2 Binary files /dev/null and b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.properties b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..84a0b92f9 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew new file mode 100755 index 000000000..1b6c78733 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew.bat b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java new file mode 100644 index 000000000..f1425c561 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java @@ -0,0 +1,77 @@ +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 org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +{%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} +import software.amazon.lambda.powertools.logging.Logging; +{%- endif %} +{%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} +import software.amazon.lambda.powertools.metrics.Metrics; +{%- endif %} +{%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} +import software.amazon.lambda.powertools.tracing.Tracing; + +import static software.amazon.lambda.powertools.tracing.CaptureMode.*; +{%- endif %} + +/** + * Handler for requests to Lambda function. + */ +public class App implements RequestHandler { + + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} + Logger log = LogManager.getLogger(App.class); + + @Logging(logEvent = true) + {%- endif %} + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} + @Tracing(captureMode = DISABLED) + {%- endif %} + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} + @Metrics(captureColdStart = true) + {%- endif %} + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { + var 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); + } + } + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} + @Tracing(namespace = "getPageContents") + {%- endif %} + private String getPageContents(String address) throws IOException { + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} + log.info("Retrieving {}", address); + {%- endif %} + var url = new URL(address); + try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { + return br.lines().collect(Collectors.joining(System.lineSeparator())); + } + } +} diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/resources/log4j2.xml b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/resources/log4j2.xml new file mode 100644 index 000000000..e1fd14cea --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/resources/log4j2.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java/helloworld/AppTest.java b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java/helloworld/AppTest.java new file mode 100644 index 000000000..0697afb00 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java/helloworld/AppTest.java @@ -0,0 +1,43 @@ +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\"")); + } +} \ No newline at end of file diff --git a/java11/hello-pt-gradle/{{cookiecutter.project_name}}/README.md b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/README.md new file mode 100644 index 000000000..60c15e67f --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,126 @@ +# {{ cookiecutter.project_name }} + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes 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. + +* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [GoLand](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) +* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [DataGrip](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) +* 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 +``` + +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 modifies 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 +{{ cookiecutter.project_name }}$ sam build +``` + +The SAM CLI installs dependencies defined in `HelloWorldFunction/build.gradle`, 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 +{{ cookiecutter.project_name }}$ 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 +{{ cookiecutter.project_name }}$ sam local start-api +{{ cookiecutter.project_name }}$ 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 +{{ cookiecutter.project_name }}$ sam logs -n HelloWorldFunction --stack-name {{ cookiecutter.project_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 +{{ cookiecutter.project_name }}$ cd HelloWorldFunction +HelloWorldFunction$ gradle 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 +sam delete --stack-name {{ cookiecutter.project_name }} +``` + +## 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. + +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/java11/hello-pt-gradle/{{cookiecutter.project_name}}/events/event.json b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/events/event.json new file mode 100644 index 000000000..3822fadaa --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/events/event.json @@ -0,0 +1,63 @@ +{ + "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/java11/hello-pt-gradle/{{cookiecutter.project_name}}/template.yaml b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 000000000..1982bcd71 --- /dev/null +++ b/java11/hello-pt-gradle/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,54 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 20 + MemorySize: 512 + +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: HelloWorldFunction + Handler: helloworld.App::handleRequest + Runtime: java11 + {%- if cookiecutter["Powertools for AWS Lambda (Java) Tracing"] == "enabled"%} + Tracing: Active + {%- endif %} + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + # Powertools for AWS Lambda (Java) env vars: https://awslabs.github.io/aws-lambda-powertools-java/#environment-variables + {%- if cookiecutter["Powertools for AWS Lambda (Java) Logging"] == "enabled"%} + POWERTOOLS_LOG_LEVEL: INFO + POWERTOOLS_LOGGER_LOG_EVENT: true + {%- endif %} + {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} + POWERTOOLS_METRICS_NAMESPACE: {{ cookiecutter.project_name|lower|replace(' ', '-') }} + {%- endif %} + PARAM1: VALUE + 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 + +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/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/pom.xml b/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/pom.xml index 8d1d68b9d..12084268f 100644 --- a/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/pom.xml +++ b/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/pom.xml @@ -16,21 +16,21 @@ software.amazon.lambda powertools-tracing - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} software.amazon.lambda powertools-logging - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} software.amazon.lambda powertools-metrics - 1.16.1 + 1.17.0 {%- endif %} diff --git a/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java b/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java index 2b39395ab..fd9999d98 100644 --- a/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java +++ b/java11/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java @@ -21,11 +21,10 @@ import software.amazon.lambda.powertools.metrics.Metrics; {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} -import software.amazon.lambda.powertools.tracing.CaptureMode; import software.amazon.lambda.powertools.tracing.Tracing; -{%- endif %} import static software.amazon.lambda.powertools.tracing.CaptureMode.*; +{%- endif %} /** * Handler for requests to Lambda function. @@ -35,7 +34,6 @@ public class App implements RequestHandler software.amazon.lambda powertools-tracing - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} software.amazon.lambda powertools-logging - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} software.amazon.lambda powertools-metrics - 1.16.1 + 1.17.0 {%- endif %} diff --git a/java17/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java b/java17/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java index cbdbc3f58..a821d1900 100644 --- a/java17/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java +++ b/java17/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java @@ -21,11 +21,10 @@ import software.amazon.lambda.powertools.metrics.Metrics; {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} -import software.amazon.lambda.powertools.tracing.CaptureMode; import software.amazon.lambda.powertools.tracing.Tracing; -{%- endif %} import static software.amazon.lambda.powertools.tracing.CaptureMode.*; +{%- endif %} /** * Handler for requests to Lambda function. @@ -35,7 +34,6 @@ public class App implements RequestHandler software.amazon.lambda powertools-tracing - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} software.amazon.lambda powertools-logging - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} software.amazon.lambda powertools-metrics - 1.16.1 + 1.17.0 {%- endif %} diff --git a/java8.al2/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java b/java8.al2/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java index c5538d7f1..c2f74332c 100644 --- a/java8.al2/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java +++ b/java8.al2/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java @@ -21,11 +21,10 @@ import software.amazon.lambda.powertools.metrics.Metrics; {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Tracing" ] == "enabled" %} -import software.amazon.lambda.powertools.tracing.CaptureMode; import software.amazon.lambda.powertools.tracing.Tracing; -{%- endif %} import static software.amazon.lambda.powertools.tracing.CaptureMode.*; +{%- endif %} /** * Handler for requests to Lambda function. @@ -35,7 +34,6 @@ public class App implements RequestHandler software.amazon.lambda powertools-tracing - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Logging" ] == "enabled" %} software.amazon.lambda powertools-logging - 1.16.1 + 1.17.0 {%- endif %} {%- if cookiecutter[ "Powertools for AWS Lambda (Java) Metrics" ] == "enabled" %} software.amazon.lambda powertools-metrics - 1.16.1 + 1.17.0 {%- endif %} diff --git a/java8/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java b/java8/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java index c5538d7f1..c26315bee 100644 --- a/java8/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java +++ b/java8/hello-pt-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java @@ -35,7 +35,6 @@ public class App implements RequestHandler