diff --git a/.github/workflows/aws-lamda-main.yml b/.github/workflows/aws-lamda-main.yml new file mode 100644 index 00000000..23394002 --- /dev/null +++ b/.github/workflows/aws-lamda-main.yml @@ -0,0 +1,45 @@ +name: aws-lambda-project + +on: + push: + paths: + - "aws-lambda-project/**" + branches: [main] + pull_request: + paths: + - "aws-lambda-project/**" + types: + - opened + - synchronize + - reopened + +jobs: + build: + name: Build + runs-on: ubuntu-latest + defaults: + run: + working-directory: "aws-lambda-project" + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '17' ] + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + + - name: Setup Java ${{ matrix.java }} + uses: actions/setup-java@v3 + with: + java-version: ${{ matrix.java }} + distribution: ${{ matrix.distribution }} + cache: 'maven' + + - name: Build with Maven + run: ./mvnw clean verify + + - if: ${{ github.ref == 'refs/heads/main' }} + name: Build and Publish Docker Image + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + ./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=${{ secrets.DOCKER_USERNAME }}/aws-lambda-project-${{ matrix.java }} + docker push ${{ secrets.DOCKER_USERNAME }}/aws-lambda-project-${{ matrix.java }} diff --git a/aws-lambda-project/.mvn/wrapper/maven-wrapper.jar b/aws-lambda-project/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..cb28b0e3 Binary files /dev/null and b/aws-lambda-project/.mvn/wrapper/maven-wrapper.jar differ diff --git a/aws-lambda-project/.mvn/wrapper/maven-wrapper.properties b/aws-lambda-project/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..eacdc9ed --- /dev/null +++ b/aws-lambda-project/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/aws-lambda-project/docker/docker-compose-app.yml b/aws-lambda-project/docker/docker-compose-app.yml new file mode 100644 index 00000000..032679e8 --- /dev/null +++ b/aws-lambda-project/docker/docker-compose-app.yml @@ -0,0 +1,18 @@ +version: '3.8' +services: + + aws-sqs-project: + build: .. + ports: + - "18080:8080" + - "18787:8787" + restart: always + depends_on: + - postgresqldb + - localstack + environment: + - SPRING_PROFILES_ACTIVE=docker + - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver + - SPRING_DATASOURCE_URL=jdbc:postgresql://postgresqldb:5432/appdb + - SPRING_DATASOURCE_USERNAME=siva + - SPRING_DATASOURCE_PASSWORD=secret diff --git a/aws-lambda-project/docker/docker-compose.yml b/aws-lambda-project/docker/docker-compose.yml new file mode 100644 index 00000000..b392410d --- /dev/null +++ b/aws-lambda-project/docker/docker-compose.yml @@ -0,0 +1,25 @@ +version: '3.8' +services: + + postgresqldb: + image: postgres:16.1-alpine + environment: + - POSTGRES_USER=appuser + - POSTGRES_PASSWORD=secret + - POSTGRES_DB=appdb + ports: + - "5432:5432" + + localstack: + image: localstack/localstack:3.0.0 + ports: + - "127.0.0.1:4566:4566" # LocalStack Gateway + - "127.0.0.1:4510-4559:4510-4559" # external services port range + environment: + - DEBUG=${DEBUG-} + - DOCKER_HOST=unix:///var/run/docker.sock + - SERVICES=lambda + volumes: + - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack" + - "/var/run/docker.sock:/var/run/docker.sock" + - "../.localstack:/etc/localstack/init/ready.d" # ready hook diff --git a/aws-lambda-project/mvnw b/aws-lambda-project/mvnw new file mode 100755 index 00000000..8d937f4c --- /dev/null +++ b/aws-lambda-project/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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 + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/aws-lambda-project/mvnw.cmd b/aws-lambda-project/mvnw.cmd new file mode 100644 index 00000000..f80fbad3 --- /dev/null +++ b/aws-lambda-project/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/aws-lambda-project/pom.xml b/aws-lambda-project/pom.xml new file mode 100644 index 00000000..62c1116b --- /dev/null +++ b/aws-lambda-project/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + com.example.awsspring + aws-lambda-project + 0.0.1-SNAPSHOT + aws-lambda-project-project + Demo project for Spring Boot + + 17 + 2022.0.4 + 1.0.29.RELEASE + 2.21.24 + 4.0.4 + 1.19.3 + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.cloud + spring-cloud-function-adapter-aws + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + org.flywaydb + flyway-core + + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.testcontainers + junit-jupiter + test + + + org.testcontainers + localstack + test + + + org.testcontainers + postgresql + test + + + software.amazon.awssdk + lambda + + + org.apache.maven.shared + maven-invoker + 3.2.0 + test + + + io.rest-assured + rest-assured + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + software.amazon.awssdk + bom + ${aws.java.sdk.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.springframework.boot.experimental + spring-boot-thin-layout + 1.0.29.RELEASE + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + false + true + aws + + + + + + diff --git a/aws-lambda-project/src/main/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplication.java b/aws-lambda-project/src/main/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplication.java new file mode 100644 index 00000000..561c6b0c --- /dev/null +++ b/aws-lambda-project/src/main/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplication.java @@ -0,0 +1,27 @@ +package com.example.springcloudfunctionaws; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.jdbc.core.JdbcTemplate; + +import java.util.function.Function; + +@SpringBootApplication +public class SpringCloudFunctionAwsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCloudFunctionAwsApplication.class, args); + } + + @Bean + Function fetchByName(JdbcTemplate jdbcTemplate) { + return profile -> jdbcTemplate.queryForObject("SELECT COUNT(*) FROM profile WHERE name LIKE ?", Integer.class, + profile.name() + "%"); + } + + public record Profile(String name) { + + } + +} diff --git a/aws-lambda-project/src/main/resources/application-local.properties b/aws-lambda-project/src/main/resources/application-local.properties new file mode 100644 index 00000000..83f68353 --- /dev/null +++ b/aws-lambda-project/src/main/resources/application-local.properties @@ -0,0 +1,8 @@ +spring.datasource.driver-class-name=org.postgresql.Driver +spring.datasource.url=jdbc:postgresql://localhost:5432/appdb +spring.datasource.username=appuser +spring.datasource.password=secret + +spring.cloud.aws.credentials.access-key=noop +spring.cloud.aws.credentials.secret-key=noop +spring.cloud.aws.region.static=us-east-1 \ No newline at end of file diff --git a/aws-lambda-project/src/main/resources/application.properties b/aws-lambda-project/src/main/resources/application.properties new file mode 100644 index 00000000..8f630fac --- /dev/null +++ b/aws-lambda-project/src/main/resources/application.properties @@ -0,0 +1,24 @@ +spring.application.name=aws-lambda-project +server.port=8080 +server.shutdown=graceful +spring.main.allow-bean-definition-overriding=true +spring.jmx.enabled=false + +################ Database ##################### +spring.jpa.show-sql=true +spring.jpa.open-in-view=false +spring.data.jpa.repositories.bootstrap-mode=deferred +spring.datasource.hikari.auto-commit=false +spring.jpa.hibernate.ddl-auto=validate +#spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.jdbc.time_zone=UTC +spring.jpa.properties.hibernate.id.new_generator_mappings=true +spring.jpa.properties.hibernate.id.optimizer.pooled.preferred=pooled-lo +spring.jpa.properties.hibernate.generate_statistics=false +spring.jpa.properties.hibernate.jdbc.batch_size=25 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true +spring.jpa.properties.hibernate.query.in_clause_parameter_padding=true +spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true diff --git a/aws-lambda-project/src/main/resources/db/migration/V1__create_populate_table.sql b/aws-lambda-project/src/main/resources/db/migration/V1__create_populate_table.sql new file mode 100644 index 00000000..a9976acb --- /dev/null +++ b/aws-lambda-project/src/main/resources/db/migration/V1__create_populate_table.sql @@ -0,0 +1,6 @@ +CREATE TABLE IF NOT EXISTS profile(id serial primary key, name varchar(255) not null); + +INSERT INTO profile (name) VALUES ('profile-1'); +INSERT INTO profile (name) VALUES ('profile-2'); +INSERT INTO profile (name) VALUES ('profile-3'); +INSERT INTO profile (name) VALUES ('profile-4'); \ No newline at end of file diff --git a/aws-lambda-project/src/test/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplicationTests.java b/aws-lambda-project/src/test/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplicationTests.java new file mode 100644 index 00000000..af87c36f --- /dev/null +++ b/aws-lambda-project/src/test/java/com/example/springcloudfunctionaws/SpringCloudFunctionAwsApplicationTests.java @@ -0,0 +1,133 @@ +package com.example.springcloudfunctionaws; + +import io.restassured.RestAssured; +import io.restassured.response.ResponseBody; +import org.apache.commons.io.FileUtils; +import org.apache.maven.shared.invoker.DefaultInvocationRequest; +import org.apache.maven.shared.invoker.DefaultInvoker; +import org.apache.maven.shared.invoker.MavenInvocationException; +import org.junit.jupiter.api.Test; +import org.springframework.util.StringUtils; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.localstack.LocalStackContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import org.testcontainers.utility.ResourceReaper; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.*; +import software.amazon.awssdk.services.lambda.model.Runtime; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +@Testcontainers(parallel = true) +class SpringCloudFunctionAwsApplicationTests { + + static String jar = buildJar(); + + static Network network = Network.newNetwork(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16.1-alpine").withNetwork(network) + .withNetworkAliases("postgres"); + + @Container + static LocalStackContainer localstack = new LocalStackContainer( + DockerImageName.parse("localstack/localstack:3.0.0")) + .withNetwork(network) + .withEnv("LOCALSTACK_HOST", "localhost.localstack.cloud") + .withEnv("LAMBDA_DOCKER_NETWORK", ((Network.NetworkImpl) network).getName()) + .withNetworkAliases("localstack") + .withEnv("LAMBDA_DOCKER_FLAGS", testcontainersLabels()); + + static String testcontainersLabels() { + return Stream + .of(DockerClientFactory.DEFAULT_LABELS.entrySet().stream(), + ResourceReaper.instance().getLabels().entrySet().stream()) + .flatMap(Function.identity()) + .map(entry -> String.format("-l %s=%s", entry.getKey(), entry.getValue())) + .collect(Collectors.joining(" ")); + } + + static String buildJar() { + try { + var properties = new Properties(); + properties.setProperty("skipTests", "true"); + + var defaultInvocationRequest = new DefaultInvocationRequest(); + if (StringUtils.hasText(System.getenv("MAVEN_HOME"))) { + defaultInvocationRequest.setMavenHome(new File(System.getenv("MAVEN_HOME"))); + } + defaultInvocationRequest.setJavaHome(new File(System.getenv("JAVA_HOME"))); + defaultInvocationRequest.setPomFile(Paths.get("pom.xml").toFile()); + defaultInvocationRequest.setGoals(List.of("package")); + defaultInvocationRequest.setProperties(properties); + var appInvoker = new DefaultInvoker(); + appInvoker.execute(defaultInvocationRequest); + } catch (MavenInvocationException e) { + throw new RuntimeException("Could not build jar", e); + } + return "target/aws-lambda-project-0.0.1-SNAPSHOT-aws.jar"; + } + + @Test + void contextLoads() throws IOException { + String fnName = "fetchByName-fn"; + var envVars = Map.ofEntries(Map.entry("SPRING_DATASOURCE_URL", "jdbc:postgresql://postgres:5432/test"), + Map.entry("SPRING_DATASOURCE_USERNAME", postgres.getUsername()), Map.entry("SPRING_DATASOURCE_PASSWORD", postgres.getPassword())); + CreateFunctionRequest createFunctionRequest = CreateFunctionRequest.builder() + .functionName(fnName) + .runtime(Runtime.JAVA17) + .role("arn:aws:iam::123456789012:role/irrelevant") + .packageType(PackageType.ZIP) + .code(FunctionCode.builder() + .zipFile(SdkBytes.fromByteArray(FileUtils.readFileToByteArray(new File(jar)))) + .build()) + .timeout(10) + .handler("org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest") + .environment(Environment.builder().variables(envVars).build()) + .build(); + + LambdaClient lambdaClient = LambdaClient.builder() + .region(Region.of(localstack.getRegion())) + .credentialsProvider(StaticCredentialsProvider + .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey()))) + .endpointOverride(localstack.getEndpoint()) + .build(); + + CreateFunctionResponse createFunctionResponse = lambdaClient.createFunction(createFunctionRequest); + WaiterResponse waiterResponse = lambdaClient.waiter() + .waitUntilFunctionActive(GetFunctionConfigurationRequest.builder().functionName(fnName).build()); + + CreateFunctionUrlConfigRequest createFunctionUrlConfigRequest = CreateFunctionUrlConfigRequest.builder() + .functionName(fnName) + .authType(FunctionUrlAuthType.NONE) + .build(); + CreateFunctionUrlConfigResponse createFunctionUrlConfigResponse = lambdaClient.createFunctionUrlConfig(createFunctionUrlConfigRequest); + + String functionUrl = createFunctionUrlConfigResponse.functionUrl() + .replace("" + 4566, "" + localstack.getMappedPort(4566)); + ResponseBody responseBody = RestAssured.given().body(""" + {"name": "profile"} + """).get(functionUrl).prettyPeek().andReturn().body(); + assertThat(responseBody.asString()).isEqualTo("4"); + } + +}