diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..80d144a --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,23 @@ +name: Build + +on: + push: + branches: + - '**' + +jobs: + test: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: 'maven' + + - name: Test + run: ./mvnw verify diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eac309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5f0536e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +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/.sdkmanrc b/.sdkmanrc new file mode 100644 index 0000000..817e04b --- /dev/null +++ b/.sdkmanrc @@ -0,0 +1,2 @@ +java=17.0.8-tem +maven=3.9.4 diff --git a/README.md b/README.md index 4a0c8c7..6a3e591 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# java-local-development-workshop -Java local development workshop +# Java local development workshop diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..66df285 --- /dev/null +++ b/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/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 https://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/pom.xml b/pom.xml new file mode 100644 index 0000000..0a6fda2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,212 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.0-SNAPSHOT + + + com.testcontainers + java-local-development-workshop + 0.0.1-SNAPSHOT + java-local-development-workshop + + + 17 + 3.0.2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + io.awspring.cloud + spring-cloud-aws-starter-s3 + + + io.awspring.cloud + spring-cloud-aws-starter-sqs + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + org.flywaydb + flyway-core + + + org.springframework.kafka + spring-kafka + + + commons-io + commons-io + 1.3.2 + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.springframework.kafka + spring-kafka-test + test + + + org.testcontainers + junit-jupiter + test + + + org.testcontainers + kafka + test + + + org.testcontainers + postgresql + test + + + org.testcontainers + localstack + test + + + io.rest-assured + rest-assured + test + + + org.awaitility + awaitility + test + + + org.wiremock.integrations.testcontainers + wiremock-testcontainers-module + 1.0-alpha-13 + test + + + + + + + io.awspring.cloud + spring-cloud-aws-dependencies + ${awspring.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.diffplug.spotless + spotless-maven-plugin + 2.36.0 + + + + + + 2.30.0 + + + + + + + compile + + check + + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + diff --git a/src/main/java/com/testcontainers/catalog/Application.java b/src/main/java/com/testcontainers/catalog/Application.java new file mode 100644 index 0000000..d237d27 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/Application.java @@ -0,0 +1,14 @@ +package com.testcontainers.catalog; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/src/main/java/com/testcontainers/catalog/ApplicationProperties.java b/src/main/java/com/testcontainers/catalog/ApplicationProperties.java new file mode 100644 index 0000000..092b26c --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/ApplicationProperties.java @@ -0,0 +1,12 @@ +package com.testcontainers.catalog; + +import jakarta.validation.constraints.NotEmpty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +@ConfigurationProperties(prefix = "application") +@Validated +public record ApplicationProperties( + @NotEmpty String productImagesBucketName, + @NotEmpty String productImageUpdatesTopic, + @NotEmpty String inventoryServiceUrl) {} diff --git a/src/main/java/com/testcontainers/catalog/api/ProductController.java b/src/main/java/com/testcontainers/catalog/api/ProductController.java new file mode 100644 index 0000000..d61b2c8 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/api/ProductController.java @@ -0,0 +1,57 @@ +package com.testcontainers.catalog.api; + +import com.testcontainers.catalog.domain.ProductNotFoundException; +import com.testcontainers.catalog.domain.ProductService; +import com.testcontainers.catalog.domain.models.CreateProductRequest; +import com.testcontainers.catalog.domain.models.Product; +import java.io.IOException; +import java.net.URI; +import java.util.Map; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@RestController +@RequestMapping("/api/products") +class ProductController { + private final ProductService productService; + + ProductController(ProductService productService) { + this.productService = productService; + } + + @PostMapping + ResponseEntity createProduct(@Validated @RequestBody CreateProductRequest request) { + productService.createProduct(request); + URI uri = ServletUriComponentsBuilder.fromCurrentContextPath() + .path("/api/products/{code}") + .buildAndExpand(request.code()) + .toUri(); + return ResponseEntity.created(uri).build(); + } + + @GetMapping("/{code}") + ResponseEntity getProductByCode(@PathVariable String code) { + var product = productService.getProductByCode(code).orElseThrow(() -> ProductNotFoundException.withCode(code)); + return ResponseEntity.ok(product); + } + + @PostMapping("/{code}/image") + ResponseEntity> uploadProductImage( + @PathVariable String code, @RequestParam("file") MultipartFile file) throws IOException { + var filename = file.getOriginalFilename(); + var extn = filename.substring(filename.lastIndexOf(".")); + var imageName = code + extn; + productService.uploadProductImage(code, imageName, file.getInputStream()); + Map response = Map.of("status", "success", "filename", imageName); + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/com/testcontainers/catalog/clients/inventory/InventoryServiceClient.java b/src/main/java/com/testcontainers/catalog/clients/inventory/InventoryServiceClient.java new file mode 100644 index 0000000..9bf4f45 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/clients/inventory/InventoryServiceClient.java @@ -0,0 +1,10 @@ +package com.testcontainers.catalog.clients.inventory; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.service.annotation.GetExchange; + +public interface InventoryServiceClient { + + @GetExchange("/api/inventory/{code}") + ProductInventory getInventory(@PathVariable String code); +} diff --git a/src/main/java/com/testcontainers/catalog/clients/inventory/ProductInventory.java b/src/main/java/com/testcontainers/catalog/clients/inventory/ProductInventory.java new file mode 100644 index 0000000..5a68862 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/clients/inventory/ProductInventory.java @@ -0,0 +1,3 @@ +package com.testcontainers.catalog.clients.inventory; + +public record ProductInventory(String code, int quantity) {} diff --git a/src/main/java/com/testcontainers/catalog/clients/inventory/RestClientConfig.java b/src/main/java/com/testcontainers/catalog/clients/inventory/RestClientConfig.java new file mode 100644 index 0000000..5049427 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/clients/inventory/RestClientConfig.java @@ -0,0 +1,20 @@ +package com.testcontainers.catalog.clients.inventory; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.support.RestClientAdapter; +import org.springframework.web.service.invoker.HttpServiceProxyFactory; + +@Configuration +class RestClientConfig { + + @Bean + InventoryServiceClient inventoryServiceProxy(@Value("${inventory.service.base-url}") String baseURI) { + RestClient restClient = RestClient.create(baseURI); + HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient)) + .build(); + return factory.createClient(InventoryServiceClient.class); + } +} diff --git a/src/main/java/com/testcontainers/catalog/config/AwsConfig.java b/src/main/java/com/testcontainers/catalog/config/AwsConfig.java new file mode 100644 index 0000000..8c3dd00 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/config/AwsConfig.java @@ -0,0 +1,16 @@ +package com.testcontainers.catalog.config; + +import com.testcontainers.catalog.ApplicationProperties; +import com.testcontainers.catalog.domain.FileStorageService; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +class AwsConfig { + + @Bean + ApplicationRunner awsInitializer(ApplicationProperties properties, FileStorageService fileStorageService) { + return args -> fileStorageService.createBucket(properties.productImagesBucketName()); + } +} diff --git a/src/main/java/com/testcontainers/catalog/config/GlobalExceptionHandler.java b/src/main/java/com/testcontainers/catalog/config/GlobalExceptionHandler.java new file mode 100644 index 0000000..25dd0f1 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/config/GlobalExceptionHandler.java @@ -0,0 +1,21 @@ +package com.testcontainers.catalog.config; + +import com.testcontainers.catalog.domain.ProductNotFoundException; +import java.time.Instant; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@RestControllerAdvice +class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(ProductNotFoundException.class) + ProblemDetail handleProductNotFoundException(ProductNotFoundException e) { + ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); + problemDetail.setTitle("Product Not Found"); + problemDetail.setProperty("timestamp", Instant.now()); + return problemDetail; + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/FileStorageService.java b/src/main/java/com/testcontainers/catalog/domain/FileStorageService.java new file mode 100644 index 0000000..c57c3f0 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/FileStorageService.java @@ -0,0 +1,11 @@ +package com.testcontainers.catalog.domain; + +import java.io.InputStream; + +public interface FileStorageService { + void createBucket(String bucketName); + + void upload(String filename, InputStream inputStream); + + String getPreSignedURL(String filename); +} diff --git a/src/main/java/com/testcontainers/catalog/domain/ProductNotFoundException.java b/src/main/java/com/testcontainers/catalog/domain/ProductNotFoundException.java new file mode 100644 index 0000000..7830703 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/ProductNotFoundException.java @@ -0,0 +1,11 @@ +package com.testcontainers.catalog.domain; + +public class ProductNotFoundException extends RuntimeException { + public ProductNotFoundException(String message) { + super(message); + } + + public static ProductNotFoundException withCode(String code) { + return new ProductNotFoundException("Product with code " + code + " not found"); + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/ProductService.java b/src/main/java/com/testcontainers/catalog/domain/ProductService.java new file mode 100644 index 0000000..22c0eae --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/ProductService.java @@ -0,0 +1,17 @@ +package com.testcontainers.catalog.domain; + +import com.testcontainers.catalog.domain.models.CreateProductRequest; +import com.testcontainers.catalog.domain.models.Product; +import java.io.InputStream; +import java.util.Optional; + +public interface ProductService { + + void createProduct(CreateProductRequest request); + + Optional getProductByCode(String code); + + void uploadProductImage(String code, String imageName, InputStream inputStream); + + void updateProductImage(String code, String image); +} diff --git a/src/main/java/com/testcontainers/catalog/domain/internal/DefaultProductService.java b/src/main/java/com/testcontainers/catalog/domain/internal/DefaultProductService.java new file mode 100644 index 0000000..48b8e85 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/internal/DefaultProductService.java @@ -0,0 +1,86 @@ +package com.testcontainers.catalog.domain.internal; + +import com.testcontainers.catalog.clients.inventory.InventoryServiceClient; +import com.testcontainers.catalog.domain.FileStorageService; +import com.testcontainers.catalog.domain.ProductService; +import com.testcontainers.catalog.domain.models.CreateProductRequest; +import com.testcontainers.catalog.domain.models.Product; +import com.testcontainers.catalog.domain.models.ProductImageUploadedEvent; +import java.io.InputStream; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +@Service +@Transactional +class DefaultProductService implements ProductService { + private static final Logger log = LoggerFactory.getLogger(DefaultProductService.class); + + private final ProductRepository productRepository; + private final InventoryServiceClient inventoryServiceClient; + private final FileStorageService fileStorageService; + private final ProductEventPublisher productEventPublisher; + + public DefaultProductService( + ProductRepository productRepository, + InventoryServiceClient inventoryServiceClient, + FileStorageService fileStorageService, + ProductEventPublisher productEventPublisher) { + this.productRepository = productRepository; + this.inventoryServiceClient = inventoryServiceClient; + this.fileStorageService = fileStorageService; + this.productEventPublisher = productEventPublisher; + } + + public void createProduct(CreateProductRequest request) { + ProductEntity entity = new ProductEntity(); + entity.setCode(request.code()); + entity.setName(request.name()); + entity.setDescription(request.description()); + entity.setPrice(request.price()); + + productRepository.save(entity); + } + + public Optional getProductByCode(String code) { + Optional productEntity = productRepository.findByCode(code); + if (productEntity.isEmpty()) { + return Optional.empty(); + } + return productEntity.map(this::toProduct); + } + + public void uploadProductImage(String code, String imageName, InputStream inputStream) { + fileStorageService.upload(imageName, inputStream); + productEventPublisher.publish(new ProductImageUploadedEvent(code, imageName)); + log.info("Published event to update product image for code: {}", code); + } + + public void updateProductImage(String code, String image) { + productRepository.updateProductImage(code, image); + } + + private boolean isProductAvailable(String code) { + try { + return inventoryServiceClient.getInventory(code).quantity() > 0; + } catch (Exception e) { + log.error("Error while calling inventory service", e); + // business decision is to show as available if inventory service is down + return true; + } + } + + private Product toProduct(ProductEntity entity) { + return new Product( + entity.getId(), + entity.getCode(), + entity.getName(), + entity.getDescription(), + StringUtils.hasText(entity.getImage()) ? fileStorageService.getPreSignedURL(entity.getImage()) : null, + entity.getPrice(), + isProductAvailable(entity.getCode())); + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/internal/ProductEntity.java b/src/main/java/com/testcontainers/catalog/domain/internal/ProductEntity.java new file mode 100644 index 0000000..542da3f --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/internal/ProductEntity.java @@ -0,0 +1,95 @@ +package com.testcontainers.catalog.domain.internal; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import java.math.BigDecimal; + +@Entity +@Table(name = "products") +class ProductEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true) + @NotEmpty(message = "Product code must not be null/empty") + private String code; + + @NotEmpty(message = "Product name must not be null/empty") + @Column(nullable = false) + private String name; + + private String description; + + private String image; + + @NotNull(message = "Product price must not be null") @DecimalMin("0.1") + @Column(nullable = false) + private BigDecimal price; + + public ProductEntity() {} + + public ProductEntity(Long id, String code, String name, String description, String image, BigDecimal price) { + this.id = id; + this.code = code; + this.name = name; + this.description = description; + this.image = image; + this.price = price; + } + + 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; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getImage() { + return image; + } + + public void setImage(String image) { + this.image = image; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/internal/ProductEventPublisher.java b/src/main/java/com/testcontainers/catalog/domain/internal/ProductEventPublisher.java new file mode 100644 index 0000000..8b8805a --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/internal/ProductEventPublisher.java @@ -0,0 +1,21 @@ +package com.testcontainers.catalog.domain.internal; + +import com.testcontainers.catalog.ApplicationProperties; +import com.testcontainers.catalog.domain.models.ProductImageUploadedEvent; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +class ProductEventPublisher { + private final KafkaTemplate kafkaTemplate; + private final ApplicationProperties properties; + + public ProductEventPublisher(KafkaTemplate kafkaTemplate, ApplicationProperties properties) { + this.kafkaTemplate = kafkaTemplate; + this.properties = properties; + } + + public void publish(ProductImageUploadedEvent event) { + kafkaTemplate.send(properties.productImageUpdatesTopic(), event.code(), event); + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/internal/ProductRepository.java b/src/main/java/com/testcontainers/catalog/domain/internal/ProductRepository.java new file mode 100644 index 0000000..09e5ec3 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/internal/ProductRepository.java @@ -0,0 +1,15 @@ +package com.testcontainers.catalog.domain.internal; + +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +interface ProductRepository extends JpaRepository { + Optional findByCode(String code); + + @Modifying + @Query("update ProductEntity p set p.image = :image where p.code = :code") + void updateProductImage(@Param("code") String code, @Param("image") String image); +} diff --git a/src/main/java/com/testcontainers/catalog/domain/internal/S3FileStorageService.java b/src/main/java/com/testcontainers/catalog/domain/internal/S3FileStorageService.java new file mode 100644 index 0000000..7e138a0 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/internal/S3FileStorageService.java @@ -0,0 +1,43 @@ +package com.testcontainers.catalog.domain.internal; + +import com.testcontainers.catalog.ApplicationProperties; +import com.testcontainers.catalog.domain.FileStorageService; +import io.awspring.cloud.s3.S3Template; +import java.io.InputStream; +import java.time.Duration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +class S3FileStorageService implements FileStorageService { + private static final Logger log = LoggerFactory.getLogger(S3FileStorageService.class); + private final S3Template s3Template; + private final ApplicationProperties properties; + + public S3FileStorageService(S3Template s3Template, ApplicationProperties properties) { + this.s3Template = s3Template; + this.properties = properties; + } + + public void createBucket(String bucketName) { + s3Template.createBucket(bucketName); + } + + public void upload(String filename, InputStream inputStream) { + log.debug("Uploading file with name {} to S3", filename); + try { + s3Template.upload(properties.productImagesBucketName(), filename, inputStream, null); + log.debug("Uploaded file with name {} to S3", filename); + } catch (Exception e) { + log.error("IException: ", e); + throw new RuntimeException(e); + } + } + + public String getPreSignedURL(String filename) { + return s3Template + .createSignedGetURL(properties.productImagesBucketName(), filename, Duration.ofMinutes(60)) + .toString(); + } +} diff --git a/src/main/java/com/testcontainers/catalog/domain/models/CreateProductRequest.java b/src/main/java/com/testcontainers/catalog/domain/models/CreateProductRequest.java new file mode 100644 index 0000000..18f1aab --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/models/CreateProductRequest.java @@ -0,0 +1,9 @@ +package com.testcontainers.catalog.domain.models; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import java.math.BigDecimal; + +public record CreateProductRequest( + @NotEmpty String code, @NotEmpty String name, String description, @NotNull @Positive BigDecimal price) {} diff --git a/src/main/java/com/testcontainers/catalog/domain/models/Product.java b/src/main/java/com/testcontainers/catalog/domain/models/Product.java new file mode 100644 index 0000000..829ab9f --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/models/Product.java @@ -0,0 +1,6 @@ +package com.testcontainers.catalog.domain.models; + +import java.math.BigDecimal; + +public record Product( + Long id, String code, String name, String description, String imageUrl, BigDecimal price, boolean available) {} diff --git a/src/main/java/com/testcontainers/catalog/domain/models/ProductImageUploadedEvent.java b/src/main/java/com/testcontainers/catalog/domain/models/ProductImageUploadedEvent.java new file mode 100644 index 0000000..5d263f5 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/domain/models/ProductImageUploadedEvent.java @@ -0,0 +1,3 @@ +package com.testcontainers.catalog.domain.models; + +public record ProductImageUploadedEvent(String code, String image) {} diff --git a/src/main/java/com/testcontainers/catalog/events/ProductEventListener.java b/src/main/java/com/testcontainers/catalog/events/ProductEventListener.java new file mode 100644 index 0000000..289daf8 --- /dev/null +++ b/src/main/java/com/testcontainers/catalog/events/ProductEventListener.java @@ -0,0 +1,27 @@ +package com.testcontainers.catalog.events; + +import com.testcontainers.catalog.domain.ProductService; +import com.testcontainers.catalog.domain.models.ProductImageUploadedEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +@Transactional +class ProductEventListener { + private static final Logger log = LoggerFactory.getLogger(ProductEventListener.class); + + private final ProductService productService; + + ProductEventListener(ProductService productService) { + this.productService = productService; + } + + @KafkaListener(topics = "${application.product-image-updates-topic}", groupId = "catalog-service") + public void handle(ProductImageUploadedEvent event) { + log.info("Received a ProductImageUploaded with code:{}", event.code()); + productService.updateProductImage(event.code(), event.image()); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..7fec071 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,17 @@ +spring.application.name=shopping-cart +server.port=8080 +spring.servlet.multipart.max-file-size=10MB +spring.servlet.multipart.max-request-size=10MB + +spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer + +spring.kafka.consumer.group-id=catalog-service +spring.kafka.consumer.auto-offset-reset=latest +spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer +spring.kafka.consumer.properties.spring.json.trusted.packages=com.testcontainers.catalog.domain.models + +application.product-images-bucket-name=product-images +application.product-image-updates-topic=product-image-updates +application.inventory-service-url=http://localhost:8081 diff --git a/src/main/resources/db/migration/V1__catalog_tables.sql b/src/main/resources/db/migration/V1__catalog_tables.sql new file mode 100644 index 0000000..16936f6 --- /dev/null +++ b/src/main/resources/db/migration/V1__catalog_tables.sql @@ -0,0 +1,15 @@ +create table products +( + id bigserial primary key, + code varchar not null unique, + name varchar not null, + description varchar, + image varchar, + price numeric not null +); + +insert into products(code, name, description, image, price) values +('P101','Product P101','Product P101 description', null, 34.0), +('P102','Product P102','Product P102 description', null, 25.0), +('P103','Product P103','Product P103 description', null, 15.0) +; \ No newline at end of file diff --git a/src/test/java/com/testcontainers/catalog/ApplicationTests.java b/src/test/java/com/testcontainers/catalog/ApplicationTests.java new file mode 100644 index 0000000..03d4b56 --- /dev/null +++ b/src/test/java/com/testcontainers/catalog/ApplicationTests.java @@ -0,0 +1,10 @@ +package com.testcontainers.catalog; + +import com.testcontainers.catalog.common.BaseIntegrationTest; +import org.junit.jupiter.api.Test; + +class ApplicationTests extends BaseIntegrationTest { + + @Test + void contextLoads() {} +} diff --git a/src/test/java/com/testcontainers/catalog/ContainersConfig.java b/src/test/java/com/testcontainers/catalog/ContainersConfig.java new file mode 100644 index 0000000..304e22c --- /dev/null +++ b/src/test/java/com/testcontainers/catalog/ContainersConfig.java @@ -0,0 +1,53 @@ +package com.testcontainers.catalog; + +import static org.testcontainers.containers.localstack.LocalStackContainer.Service.SQS; +import static org.testcontainers.utility.DockerImageName.parse; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.localstack.LocalStackContainer; +import org.wiremock.integrations.testcontainers.WireMockContainer; + +@TestConfiguration(proxyBeanMethods = false) +public class ContainersConfig { + private static boolean reuse = true; + + public static void setReuse(boolean reuse) { + ContainersConfig.reuse = reuse; + } + + @Bean + @ServiceConnection + KafkaContainer kafkaContainer() { + return new KafkaContainer(parse("confluentinc/cp-kafka:7.5.0")).withReuse(reuse); + } + + @Bean + @ServiceConnection + PostgreSQLContainer postgresContainer() { + return new PostgreSQLContainer<>(parse("postgres:16-alpine")).withReuse(reuse); + } + + @Bean + LocalStackContainer localstackContainer(DynamicPropertyRegistry registry) { + LocalStackContainer localStack = new LocalStackContainer(parse("localstack/localstack:2.3")).withReuse(reuse); + registry.add("spring.cloud.aws.credentials.access-key", localStack::getAccessKey); + registry.add("spring.cloud.aws.credentials.secret-key", localStack::getSecretKey); + registry.add("spring.cloud.aws.region.static", localStack::getRegion); + registry.add("spring.cloud.aws.endpoint", () -> localStack.getEndpointOverride(SQS)); + return localStack; + } + + @Bean + WireMockContainer wiremockServer(DynamicPropertyRegistry registry) { + WireMockContainer wiremockServer = new WireMockContainer("wiremock/wiremock:3.2.0-alpine") + .withMappingFromResource("mocks-config.json") + .withReuse(reuse); + registry.add("inventory.service.base-url", wiremockServer::getBaseUrl); + return wiremockServer; + } +} diff --git a/src/test/java/com/testcontainers/catalog/TestApplication.java b/src/test/java/com/testcontainers/catalog/TestApplication.java new file mode 100644 index 0000000..0661122 --- /dev/null +++ b/src/test/java/com/testcontainers/catalog/TestApplication.java @@ -0,0 +1,11 @@ +package com.testcontainers.catalog; + +import org.springframework.boot.SpringApplication; + +public class TestApplication { + + public static void main(String[] args) { + ContainersConfig.setReuse(true); + SpringApplication.from(Application::main).with(ContainersConfig.class).run(args); + } +} diff --git a/src/test/java/com/testcontainers/catalog/api/ProductControllerTest.java b/src/test/java/com/testcontainers/catalog/api/ProductControllerTest.java new file mode 100644 index 0000000..a1fcdac --- /dev/null +++ b/src/test/java/com/testcontainers/catalog/api/ProductControllerTest.java @@ -0,0 +1,186 @@ +package com.testcontainers.catalog.api; + +import static io.restassured.RestAssured.given; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.CoreMatchers.endsWith; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import com.testcontainers.catalog.common.BaseIntegrationTest; +import com.testcontainers.catalog.domain.ProductService; +import com.testcontainers.catalog.domain.models.Product; +import io.restassured.http.ContentType; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.test.context.jdbc.Sql; + +@Sql("/test-data.sql") +class ProductControllerTest extends BaseIntegrationTest { + + @Autowired + ProductService productService; + + @Nested + class CreateProductTests { + @Test + void createProductSuccessfully() { + String code = UUID.randomUUID().toString(); + given().contentType(ContentType.JSON) + .body( + """ + { + "code": "%s", + "name": "Product %s", + "description": "Product %s description", + "price": 10.0 + } + """ + .formatted(code, code, code)) + .when() + .post("/api/products") + .then() + .statusCode(201) + .header("Location", endsWith("/api/products/%s".formatted(code))); + } + + @ParameterizedTest + @MethodSource("invalidProductListProvider") + void shouldNotCreateProductWithInvalidData(String code, String name, BigDecimal price) { + given().contentType(ContentType.JSON) + .body( + """ + { + "code": "%s", + "name": "%s", + "description": "Product description", + "price": "%s" + } + """ + .formatted(code, name, price)) + .when() + .post("/api/products") + .then() + .statusCode(400); + } + + static Stream invalidProductListProvider() { + return Stream.of( + arguments("", "product name", BigDecimal.TEN), + arguments(UUID.randomUUID().toString(), "", BigDecimal.TEN), + arguments(UUID.randomUUID().toString(), "product name", null)); + } + } + + @Nested + class GetProductByCodeTests { + @Test + void getProductByCodeSuccessfully() { + String code = "P101"; + + Product product = given().contentType(ContentType.JSON) + .when() + .get("/api/products/{code}", code) + .then() + .statusCode(200) + .extract() + .as(Product.class); + + assertThat(product.code()).isEqualTo(code); + assertThat(product.name()).isEqualTo("Product %s".formatted(code)); + assertThat(product.description()).isEqualTo("Product %s description".formatted(code)); + assertThat(product.price().compareTo(new BigDecimal("34.0"))).isEqualTo(0); + assertThat(product.available()).isTrue(); + } + + @Test + void getProductByCodeWithStatusAsUnavailableFromInventory() { + String code = "P103"; + + Product product = given().contentType(ContentType.JSON) + .when() + .get("/api/products/{code}", code) + .then() + .statusCode(200) + .extract() + .as(Product.class); + + assertThat(product.code()).isEqualTo(code); + assertThat(product.name()).isEqualTo("Product %s".formatted(code)); + assertThat(product.description()).isEqualTo("Product %s description".formatted(code)); + assertThat(product.price().compareTo(new BigDecimal("15.0"))).isEqualTo(0); + assertThat(product.available()).isFalse(); + } + + @Test + void getProductByCodeWithStatusAsAvailableWhenInventoryCallFails() { + String code = "P102"; + + Product product = given().contentType(ContentType.JSON) + .when() + .get("/api/products/{code}", code) + .then() + .statusCode(200) + .extract() + .as(Product.class); + + assertThat(product.code()).isEqualTo(code); + assertThat(product.name()).isEqualTo("Product %s".formatted(code)); + assertThat(product.description()).isEqualTo("Product %s description".formatted(code)); + assertThat(product.price().compareTo(new BigDecimal("25.0"))).isEqualTo(0); + assertThat(product.available()).isTrue(); + } + + @Test + void shouldGetNotFoundWhenProductCodeNotExists() { + String code = UUID.randomUUID().toString(); + + given().contentType(ContentType.JSON) + .when() + .get("/api/products/{code}", code) + .then() + .statusCode(404); + } + } + + @Nested + class ProductImageUploadTests { + @Test + void shouldUploadProductImageSuccessfully() throws IOException { + String code = "P101"; + File file = new ClassPathResource("P101.jpg").getFile(); + + Optional product = productService.getProductByCode(code); + assertThat(product).isPresent(); + assertThat(product.get().imageUrl()).isNull(); + + given().multiPart("file", file, "multipart/form-data") + .contentType(ContentType.MULTIPART) + .when() + .post("/api/products/{code}/image", code) + .then() + .statusCode(200) + .body("status", endsWith("success")) + .body("filename", endsWith("P101.jpg")); + + await().pollInterval(Duration.ofSeconds(3)).atMost(10, SECONDS).untilAsserted(() -> { + Optional optionalProduct = productService.getProductByCode(code); + assertThat(optionalProduct).isPresent(); + assertThat(optionalProduct.get().imageUrl()).isNotEmpty(); + }); + } + } +} diff --git a/src/test/java/com/testcontainers/catalog/common/BaseIntegrationTest.java b/src/test/java/com/testcontainers/catalog/common/BaseIntegrationTest.java new file mode 100644 index 0000000..d394014 --- /dev/null +++ b/src/test/java/com/testcontainers/catalog/common/BaseIntegrationTest.java @@ -0,0 +1,25 @@ +package com.testcontainers.catalog.common; + +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import com.testcontainers.catalog.ContainersConfig; +import io.restassured.RestAssured; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Import; + +@SpringBootTest( + webEnvironment = RANDOM_PORT, + properties = {"spring.cloud.aws.region.static=us-east-1"}) +@Import(ContainersConfig.class) +public abstract class BaseIntegrationTest { + + @LocalServerPort + private int port; + + @BeforeEach + void setUpBase() { + RestAssured.port = port; + } +} diff --git a/src/test/resources/P101.jpg b/src/test/resources/P101.jpg new file mode 100644 index 0000000..51416f4 Binary files /dev/null and b/src/test/resources/P101.jpg differ diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 0000000..eb2f4e2 --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,14 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/mocks-config.json b/src/test/resources/mocks-config.json new file mode 100644 index 0000000..88517f6 --- /dev/null +++ b/src/test/resources/mocks-config.json @@ -0,0 +1,48 @@ +{ + "mappings": [ + { + "request": { + "method": "GET", + "urlPattern": "/api/inventory/P101" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "code": "P101", + "quantity": 25 + } + } + }, + { + "request": { + "method": "GET", + "urlPattern": "/api/inventory/P102" + }, + "response": { + "status": 500, + "headers": { + "Content-Type": "application/json" + } + } + }, + { + "request": { + "method": "GET", + "urlPattern": "/api/inventory/P103" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "code": "P103", + "quantity": 0 + } + } + } + ] +} \ No newline at end of file diff --git a/src/test/resources/test-data.sql b/src/test/resources/test-data.sql new file mode 100644 index 0000000..0c3d659 --- /dev/null +++ b/src/test/resources/test-data.sql @@ -0,0 +1,7 @@ +DELETE FROM products; + +insert into products(code, name, description, image, price) values +('P101','Product P101','Product P101 description', null, 34.0), +('P102','Product P102','Product P102 description', null, 25.0), +('P103','Product P103','Product P103 description', null, 15.0) +; \ No newline at end of file