diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..e2e45f89 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +**/mvnw text eol=lf +*.cmd text eol=lf +*.sh text eol=lf +*.java text eol=lf +*.xml text eol=lf +*.properties text eol=lf +*.yml text eol=lf +*.gitattributes text eol=lf +*.gitignore text eol=lf +*.md text eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ee63bae7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +products/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/docker-compose.yaml b/docker-compose.yaml index 2b20a5d9..0eeb02da 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -33,3 +33,18 @@ services: - K6_OUT=influxdb=http://influxdb:8086/k6 extra_hosts: - "host.docker.internal:host-gateway" + products-redis: + image: 'redis:latest' + ports: + - "6379:6379" + products: + environment: + - SPRING_DATA_REDIS_HOST=products-redis + - SPRING_DATA_REDIS_PORT=6379 + - SERVER_PORT=5000 + - EXTERNAL_API_HOST=simulado + build: ./products + ports: + - "5000:5000" + depends_on: + - products-redis diff --git a/products/.mvn/wrapper/maven-wrapper.properties b/products/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c595b009 --- /dev/null +++ b/products/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/products/Dockerfile b/products/Dockerfile new file mode 100644 index 00000000..65909878 --- /dev/null +++ b/products/Dockerfile @@ -0,0 +1,14 @@ +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /app +COPY pom.xml . +COPY mvnw . +COPY .mvn .mvn +RUN chmod +x mvnw +COPY src ./src +RUN mvn clean package -DskipTests + +FROM eclipse-temurin:21-jre +WORKDIR /app +COPY --from=build /app/target/*.jar app.jar +EXPOSE 5000 +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/products/README.md b/products/README.md new file mode 100644 index 00000000..929337f8 --- /dev/null +++ b/products/README.md @@ -0,0 +1,48 @@ +# Products Service + +A high-performance microservice built to manage and serve product information efficiently, utilizing caching strategies and resilient communication patterns with external dependencies. + +## 🛠 Tech Stack + +* **Runtime:** Java 21 +* **Framework:** Spring Boot 3 +* **Caching:** Redis +* **Resilience:** Resilience4j (Circuit Breaker, Retry patterns) +* **Observability:** Spring Boot Actuator +* **Testing:** + * JUnit 5 + * Mockito + * Spring Boot Starter Test + * WireMock (for mocking external HTTP dependencies) + * Embedded Redis (for integration testing) + +## 🚀 Getting Started + +To launch the complete infrastructure, including the application, database, and monitoring tools, use the following command: + +```bash +docker compose up -d simulado grafana influxdb products products-redis +``` + +### Performance Testing +The k6 performance tests should be executed following the same procedure described in the original project documentation. Ensure the environment is fully up before initiating load tests. + +--- + +### 🔍 Validation & Monitoring + +Once the containers are running, you can verify the application's health and the status of the integrated resilience patterns through the following Actuator endpoints: + +* **System Health & Infrastructure:** [http://localhost:5000/actuator/health](http://localhost:5000/actuator/health) + Displays the overall status of the application, including the connection status to the Redis cache and the health of the configured Circuit Breakers. +* **Circuit Breaker Status:** [http://localhost:5000/actuator/circuitbreakers](http://localhost:5000/actuator/circuitbreakers) + Shows the current state (`CLOSED`, `OPEN`, `HALF_OPEN`) of the `productClient` circuit breaker, along with real-time metrics (failure rate, buffered calls, etc.). +* **Circuit Breaker Events:** [http://localhost:5000/actuator/circuitbreakerevents](http://localhost:5000/actuator/circuitbreakerevents) + Provides a chronological log of the latest events, useful for seeing exactly when the circuit opens due to timeouts or 5xx errors from the external mocks. + +--- + +### 📝 Architectural Decisions + +#### Error Handling & API Contract +A specific design choice was made regarding error propagation: **the application does not return 5xx status codes on its endpoints.** This decision is rooted in the established contract between the backend and the frontend. By intercepting internal or downstream failures and mapping them to specific client-side expectations, we ensure the frontend can handle state transitions gracefully without encountering unhandled server-side exceptions. This maintains a robust and predictable user experience even when external dependencies are unavailable. \ No newline at end of file diff --git a/products/mvnw b/products/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/products/mvnw @@ -0,0 +1,295 @@ +#!/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.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/products/mvnw.cmd b/products/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/products/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@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.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/products/pom.xml b/products/pom.xml new file mode 100644 index 00000000..a7cf3004 --- /dev/null +++ b/products/pom.xml @@ -0,0 +1,136 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.14 + + + org.challenge + products + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 21 + 2025.0.2 + 1.6.3 + 2.8.16 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${openapi.version} + + + org.springframework.boot + spring-boot-starter-aop + + + io.github.resilience4j + resilience4j-spring-boot3 + 2.2.0 + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-cache + + + org.mapstruct + mapstruct + ${mapstruct.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-data-redis + + + com.github.codemonstur + embedded-redis + 1.4.2 + test + + + org.wiremock.integrations + wiremock-spring-boot + 3.2.0 + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + + + + + + + + diff --git a/products/src/main/java/org/challenge/products/ProductsApplication.java b/products/src/main/java/org/challenge/products/ProductsApplication.java new file mode 100644 index 00000000..fd810f83 --- /dev/null +++ b/products/src/main/java/org/challenge/products/ProductsApplication.java @@ -0,0 +1,13 @@ +package org.challenge.products; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ProductsApplication { + + public static void main(String[] args) { + SpringApplication.run(ProductsApplication.class, args); + } + +} diff --git a/products/src/main/java/org/challenge/products/application/exception/ExternalServiceException.java b/products/src/main/java/org/challenge/products/application/exception/ExternalServiceException.java new file mode 100644 index 00000000..f91add63 --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/exception/ExternalServiceException.java @@ -0,0 +1,11 @@ +package org.challenge.products.application.exception; + +public class ExternalServiceException extends RuntimeException { + + private static final String ERROR_MESSAGE = "Error occurred while calling external service: %s. Response body: %s"; + + public ExternalServiceException(String message, String responseBody) { + super(ERROR_MESSAGE.formatted(message, responseBody)); + } + +} diff --git a/products/src/main/java/org/challenge/products/application/port/in/GetSimilarProductsUseCase.java b/products/src/main/java/org/challenge/products/application/port/in/GetSimilarProductsUseCase.java new file mode 100644 index 00000000..cc44e53e --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/port/in/GetSimilarProductsUseCase.java @@ -0,0 +1,9 @@ +package org.challenge.products.application.port.in; + +import org.challenge.products.domain.model.Product; + +import java.util.List; + +public interface GetSimilarProductsUseCase { + List getSimilarProducts(String productId); +} diff --git a/products/src/main/java/org/challenge/products/application/port/out/ProductPort.java b/products/src/main/java/org/challenge/products/application/port/out/ProductPort.java new file mode 100644 index 00000000..b068cec4 --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/port/out/ProductPort.java @@ -0,0 +1,11 @@ +package org.challenge.products.application.port.out; + +import org.challenge.products.domain.model.Product; + +import java.util.List; + +public interface ProductPort { + List getSimilarProductIds(String productId); + + Product getProduct(String productId); +} diff --git a/products/src/main/java/org/challenge/products/application/service/ProductService.java b/products/src/main/java/org/challenge/products/application/service/ProductService.java new file mode 100644 index 00000000..e8678fa2 --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/service/ProductService.java @@ -0,0 +1,44 @@ +package org.challenge.products.application.service; + +import org.challenge.products.application.port.in.GetSimilarProductsUseCase; +import org.challenge.products.application.port.out.ProductPort; +import org.challenge.products.domain.model.Product; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class ProductService implements GetSimilarProductsUseCase { + + private static final Logger log = LoggerFactory.getLogger(ProductService.class); + + private final ProductPort productPort; + + public ProductService(ProductPort productPort) { + this.productPort = productPort; + } + + @Override + @Cacheable(value = "similarProducts", key = "#productId") + public List getSimilarProducts(String productId) { + log.debug("Fetching similar products for productId: {}", productId); + + List result = productPort + .getSimilarProductIds(productId) + .parallelStream() + .flatMap(id -> getProduct(id).stream()) + .toList(); + + log.debug("Found {} similar products for productId: {}", result.size(), productId); + return result; + } + + private Optional getProduct(String productId) { + return Optional.ofNullable(productPort.getProduct(productId)); + } + +} diff --git a/products/src/main/java/org/challenge/products/domain/exception/ProductNotFoundException.java b/products/src/main/java/org/challenge/products/domain/exception/ProductNotFoundException.java new file mode 100644 index 00000000..6b032295 --- /dev/null +++ b/products/src/main/java/org/challenge/products/domain/exception/ProductNotFoundException.java @@ -0,0 +1,18 @@ +package org.challenge.products.domain.exception; + +import org.slf4j.helpers.MessageFormatter; + +public class ProductNotFoundException extends RuntimeException { + + private static final String ERROR_MESSAGE = "Product with id %s not found. Response body: %s"; + + public ProductNotFoundException(String message, Object... args) { + super(MessageFormatter.arrayFormat(message, args).getMessage()); + } + + public ProductNotFoundException(String id, String responseBody) { + super(ERROR_MESSAGE.formatted(id, responseBody)); + } + + +} \ No newline at end of file diff --git a/products/src/main/java/org/challenge/products/domain/model/Product.java b/products/src/main/java/org/challenge/products/domain/model/Product.java new file mode 100644 index 00000000..e94b8d21 --- /dev/null +++ b/products/src/main/java/org/challenge/products/domain/model/Product.java @@ -0,0 +1,10 @@ +package org.challenge.products.domain.model; + +import java.io.Serializable; + +public record Product( + String productId, + String name, + Double price, + Boolean availability +) implements Serializable {} diff --git a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java new file mode 100644 index 00000000..33b90a75 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -0,0 +1,105 @@ +package org.challenge.products.infrastructure.client; + +import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; +import org.challenge.products.application.exception.ExternalServiceException; +import org.challenge.products.application.port.out.ProductPort; +import org.challenge.products.domain.exception.ProductNotFoundException; +import org.challenge.products.domain.model.Product; +import org.challenge.products.infrastructure.dto.ProductDetailDto; +import org.challenge.products.infrastructure.mapper.ProductMapper; +import org.challenge.products.util.StringUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; + +import java.util.List; +import java.util.Optional; + +@Component +public class ProductClient implements ProductPort { + + private static final Logger log = LoggerFactory.getLogger(ProductClient.class); + + private final RestClient productRestClient; + private final ProductMapper productMapper; + + public ProductClient(RestClient productRestClient, ProductMapper productMapper) { + this.productRestClient = productRestClient; + this.productMapper = productMapper; + } + + @Override + @CircuitBreaker(name = "productClient", fallbackMethod = "getSimilarProductIdsFallback") + public List getSimilarProductIds(String productId) { + log.debug("Fetching similar product ids for productId: {}", productId); + List ids = productRestClient.get() + .uri("/{productId}/similarids", productId) + .retrieve() + .onStatus(HttpStatus.NOT_FOUND::equals, + (req, res) -> { + throw new ProductNotFoundException("Similar products for id: {} not found - body response: {}", productId, StringUtil.readString(res.getBody())); + }) + .onStatus(HttpStatusCode::is5xxServerError, + (req, res) -> { + throw new ExternalServiceException("External service error fetching similar ids for: " + productId, + StringUtil.readString(res.getBody())); + }) + .body(ParameterizedTypeReference.forType(List.class)); + + List result = Optional.ofNullable(ids) + .orElseGet(List::of) + .stream() + .map(Object::toString) + .toList(); + + log.debug("Found {} similar product ids for productId: {}", result.size(), productId); + return result; + } + + public List getSimilarProductIdsFallback(String productId, ProductNotFoundException t) { + throw t; + } + + public List getSimilarProductIdsFallback(String productId, Throwable t) { + log.warn("Circuit breaker fallback for getSimilarProductIds, productId: {} - {}", productId, t.getMessage()); + return List.of(); + } + + @Override + @CircuitBreaker(name = "productClient", fallbackMethod = "getProductFallback") + public Product getProduct(String productId) { + log.debug("Fetching product details for productId: {}", productId); + + ProductDetailDto responseBody = productRestClient.get() + .uri("/{productId}", productId) + .retrieve() + .onStatus(HttpStatus.NOT_FOUND::equals, + (req, res) -> { + log.error("Product with id: {} not found", productId); + throw new ProductNotFoundException(productId, StringUtil.readString(res.getBody())); + }) + .onStatus(HttpStatusCode::is5xxServerError, + (req, res) -> { + log.error("Error fetching product details for id: {} - body response: {}", + productId, StringUtil.readString(res.getBody())); + throw new ExternalServiceException("GET /" + productId + " details", + StringUtil.readString(res.getBody())); + }) + .body(ProductDetailDto.class); + + if (responseBody != null) { + log.debug("Successfully fetched product details for productId: {}", productId); + } + return productMapper.toModel(responseBody); + } + + public Product getProductFallback(String productId, Throwable t) { + log.warn("Circuit breaker fallback for getProduct, productId: {} - {}", productId, t.getMessage()); + return null; + } + +} \ No newline at end of file diff --git a/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java b/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java new file mode 100644 index 00000000..92f5ddee --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java @@ -0,0 +1,38 @@ +package org.challenge.products.infrastructure.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.time.Duration; + +@Configuration +@EnableCaching +public class RedisConfig { + + @Bean + public RedisCacheManager cacheManager(RedisConnectionFactory factory, + @Value("${cache.ttl.millis}") long timeToLive, + @Value("${cache.similarProducts.name}") String similarProductsCacheName) { + RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofMillis(timeToLive)) + .serializeKeysWith( + RedisSerializationContext.SerializationPair + .fromSerializer(new StringRedisSerializer())) + .serializeValuesWith( + RedisSerializationContext.SerializationPair + .fromSerializer(RedisSerializer.java())); + + return RedisCacheManager.builder(factory) + .cacheDefaults(defaultConfig) + .withCacheConfiguration(similarProductsCacheName, defaultConfig) + .build(); + } +} \ No newline at end of file diff --git a/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java b/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java new file mode 100644 index 00000000..3a127fcb --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java @@ -0,0 +1,28 @@ +package org.challenge.products.infrastructure.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestClient; + +@Configuration +public class RestClientConfig { + + @Bean + public RestClient productRestClient( + @Value("${integrations.productClient.baseUrl}") String productClientBaseUrl, + @Value("${integrations.productClient.connectTimeout}") int connectTimeout, + @Value("${integrations.productClient.readTimeout}") int readTimeout) { + + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(connectTimeout); + factory.setReadTimeout(readTimeout); + + return RestClient.builder() + .baseUrl(productClientBaseUrl) + .requestFactory(factory) + .build(); + } + +} diff --git a/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java b/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java new file mode 100644 index 00000000..a06af665 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java @@ -0,0 +1,27 @@ +package org.challenge.products.infrastructure.controller; + +import org.challenge.products.application.exception.ExternalServiceException; +import org.challenge.products.domain.exception.ProductNotFoundException; +import org.challenge.products.infrastructure.dto.ErrorResponseDto; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.LocalDateTime; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ProductNotFoundException.class) + public ResponseEntity handleNotFound(ProductNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ErrorResponseDto(e.getMessage(), LocalDateTime.now())); + } + + @ExceptionHandler(ExternalServiceException.class) + public ResponseEntity handleServiceError(ExternalServiceException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .body(new ErrorResponseDto(e.getMessage(), LocalDateTime.now())); + } +} \ No newline at end of file diff --git a/products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java b/products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java new file mode 100644 index 00000000..f9f9e64d --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java @@ -0,0 +1,33 @@ +package org.challenge.products.infrastructure.controller; + +import org.challenge.products.application.port.in.GetSimilarProductsUseCase; +import org.challenge.products.infrastructure.dto.ProductResponseDto; +import org.challenge.products.infrastructure.mapper.ProductMapper; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/product") +public class ProductController { + + private final GetSimilarProductsUseCase getSimilarProductsUseCase; + private final ProductMapper productMapper; + + public ProductController(GetSimilarProductsUseCase getSimilarProductsUseCase, ProductMapper productMapper) { + this.getSimilarProductsUseCase = getSimilarProductsUseCase; + this.productMapper = productMapper; + } + + @GetMapping("/{productId}/similar") + public List getSimilarProducts(@PathVariable String productId) { + return getSimilarProductsUseCase.getSimilarProducts(productId) + .stream() + .map(productMapper::toResponseDTO) + .toList(); + } + +} diff --git a/products/src/main/java/org/challenge/products/infrastructure/dto/ErrorResponseDto.java b/products/src/main/java/org/challenge/products/infrastructure/dto/ErrorResponseDto.java new file mode 100644 index 00000000..f85c6c61 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ErrorResponseDto.java @@ -0,0 +1,7 @@ +package org.challenge.products.infrastructure.dto; + +import java.time.LocalDateTime; + +public record ErrorResponseDto(String message, LocalDateTime timestamp) { + +} diff --git a/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java new file mode 100644 index 00000000..44d4021f --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java @@ -0,0 +1,10 @@ +package org.challenge.products.infrastructure.dto; + +import java.io.Serializable; + +public record ProductDetailDto ( + String id, + String name, + Double price, + Boolean availability +) implements Serializable {} diff --git a/products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java new file mode 100644 index 00000000..e4379dde --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java @@ -0,0 +1,12 @@ +package org.challenge.products.infrastructure.dto; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record ProductResponseDto( + String productId, + String name, + Double price, + Boolean availability +) {} diff --git a/products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java b/products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java new file mode 100644 index 00000000..3e344b97 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java @@ -0,0 +1,15 @@ +package org.challenge.products.infrastructure.mapper; + +import org.challenge.products.domain.model.Product; +import org.challenge.products.infrastructure.dto.ProductDetailDto; +import org.challenge.products.infrastructure.dto.ProductResponseDto; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface ProductMapper { + ProductResponseDto toResponseDTO(Product product); + + @Mapping(source = "id", target = "productId") + Product toModel(ProductDetailDto productDetailDto); +} diff --git a/products/src/main/java/org/challenge/products/util/StringUtil.java b/products/src/main/java/org/challenge/products/util/StringUtil.java new file mode 100644 index 00000000..ab7e5755 --- /dev/null +++ b/products/src/main/java/org/challenge/products/util/StringUtil.java @@ -0,0 +1,23 @@ +package org.challenge.products.util; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public final class StringUtil { + + private StringUtil() { + + } + + public static String readString(InputStream inputStream) { + try { + String string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + return string.isEmpty() ? null : string; + } catch (IOException e) { + throw new RuntimeException("Error reading input stream: " + e.getMessage(), e); + } + } + + +} diff --git a/products/src/main/resources/application.properties b/products/src/main/resources/application.properties new file mode 100644 index 00000000..832a74da --- /dev/null +++ b/products/src/main/resources/application.properties @@ -0,0 +1,30 @@ +spring.application.name=products +server.port=${SERVER_PORT:5000} + +integrations.productClient.baseUrl=http://${EXTERNAL_API_HOST:localhost:3001}/product +integrations.productClient.readTimeout=3000 +integrations.productClient.connectTimeout=2000 + +# OpenAPI configuration +springdoc.api-docs.enabled=true + +# Cache configuration +spring.data.redis.host=${SPRING_DATA_REDIS_HOST:localhost} +spring.data.redis.port=${SPRING_DATA_REDIS_PORT:6379} +cache.ttl.millis=30000 +cache.similarProducts.name=similarProducts + +# Circuit Breaker +resilience4j.circuitbreaker.instances.productClient.sliding-window-size=10 +resilience4j.circuitbreaker.instances.productClient.minimum-number-of-calls=5 +resilience4j.circuitbreaker.instances.productClient.failure-rate-threshold=50 +resilience4j.circuitbreaker.instances.productClient.wait-duration-in-open-state=5s +resilience4j.circuitbreaker.instances.productClient.permitted-number-of-calls-in-half-open-state=3 +resilience4j.circuitbreaker.instances.productClient.automatic-transition-from-open-to-half-open-enabled=true +resilience4j.circuitbreaker.instances.productClient.register-health-indicator=true +resilience4j.circuitbreaker.instances.productClient.ignore-exceptions=org.challenge.products.domain.exception.ProductNotFoundException + +# Actuator +management.endpoints.web.exposure.include=health,circuitbreakers,circuitbreakerevents +management.endpoint.health.show-details=always +management.health.circuitbreakers.enabled=true \ No newline at end of file diff --git a/products/src/test/java/org/challenge/products/application/service/ProductServiceTest.java b/products/src/test/java/org/challenge/products/application/service/ProductServiceTest.java new file mode 100644 index 00000000..53782d42 --- /dev/null +++ b/products/src/test/java/org/challenge/products/application/service/ProductServiceTest.java @@ -0,0 +1,93 @@ +package org.challenge.products.application.service; + +import org.challenge.products.application.port.out.ProductPort; +import org.challenge.products.domain.exception.ProductNotFoundException; +import org.challenge.products.domain.model.Product; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class ProductServiceTest { + + @Mock + private ProductPort productPort; + + @InjectMocks + private ProductService productService; + + @Test + @DisplayName("Should return similar products for valid product id") + void shouldReturnSimilarProducts() { + + String productId1 = "1"; + String productId2 = "2"; + String productId3 = "3"; + + Product product2 = new Product(productId2, "Product 2", 19.99, true); + Product product3 = new Product(productId3, "Product 3", 29.99, true); + + when(productPort.getSimilarProductIds(productId1)).thenReturn(List.of(productId2, productId3)); + when(productPort.getProduct(productId2)).thenReturn(product2); + when(productPort.getProduct(productId3)).thenReturn(product3); + + List result = productService.getSimilarProducts(productId1); + + assertThat(result).hasSize(2); + assertThat(result).containsExactlyInAnyOrder(product2, product3); + } + + @Test + @DisplayName("Should return empty list when no similar ids exist") + void shouldReturnEmptyListWhenNoSimilarIds() { + String productId = "1"; + + when(productPort.getSimilarProductIds(productId)).thenReturn(List.of()); + + List result = productService.getSimilarProducts(productId); + + assertThat(result).isEmpty(); + verify(productPort, never()).getProduct(any()); + } + + @Test + @DisplayName("Should skip product when getProduct returns null") + void shouldSkipNullProducts() { + String productId1 = "1"; + String productId2 = "2"; + String productIdNull = "99"; + + Product product2 = new Product(productId2, "Product 2", 19.99, true); + + when(productPort.getSimilarProductIds(productId1)).thenReturn(List.of(productId2, productIdNull)); + when(productPort.getProduct(productId2)).thenReturn(product2); + when(productPort.getProduct(productIdNull)).thenReturn(null); + + List result = productService.getSimilarProducts(productId1); + + assertThat(result).hasSize(1); + assertThat(result).containsExactly(product2); + } + + @Test + @DisplayName("Should propagate ProductNotFoundException from getSimilarProductIds") + void shouldPropagateNotFoundException() { + String productId = "4"; + String errorMessage = "not found"; + + when(productPort.getSimilarProductIds(productId)) + .thenThrow(new ProductNotFoundException(productId, errorMessage)); + + assertThatThrownBy(() -> productService.getSimilarProducts(productId)) + .isInstanceOf(ProductNotFoundException.class); + } +} diff --git a/products/src/test/java/org/challenge/products/infrastructure/client/ProductClientTest.java b/products/src/test/java/org/challenge/products/infrastructure/client/ProductClientTest.java new file mode 100644 index 00000000..d31967e6 --- /dev/null +++ b/products/src/test/java/org/challenge/products/infrastructure/client/ProductClientTest.java @@ -0,0 +1,140 @@ +package org.challenge.products.infrastructure.client; + +import org.challenge.products.domain.exception.ProductNotFoundException; +import org.challenge.products.domain.model.Product; +import org.challenge.products.infrastructure.dto.ProductDetailDto; +import org.challenge.products.infrastructure.mapper.ProductMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.client.RestClient; + +import java.util.List; +import java.util.concurrent.TimeoutException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ProductClientTest { + + @InjectMocks + private ProductClient productClient; + + @Mock + private RestClient productRestClientMock; + + @Mock + private ProductMapper productMapperMock; + + @Mock + private RestClient.RequestHeadersUriSpec requestHeadersUriSpecMock; + @Mock + private RestClient.RequestHeadersSpec requestHeadersSpecMock; + @Mock + private RestClient.ResponseSpec responseSpecMock; + + @Test + @DisplayName("Should return list of similar product ids") + void shouldReturnSimilarProductIds() { + String productId = "1"; + Integer similarId2 = 2; + Integer similarId3 = 3; + + mockGetChain(); + when(responseSpecMock.body(any(ParameterizedTypeReference.class))) + .thenReturn(List.of(similarId2, similarId3)); + + List result = productClient.getSimilarProductIds(productId); + + assertThat(result).containsExactly( + similarId2.toString(), + similarId3.toString() + ); + } + + @Test + @DisplayName("Should return empty list when similarids body is null") + void shouldReturnEmptyListWhenBodyIsNull() { + String productId = "1"; + + mockGetChain(); + when(responseSpecMock.body(any(ParameterizedTypeReference.class))) + .thenReturn(null); + + List result = productClient.getSimilarProductIds(productId); + + assertThat(result).isEmpty(); + } + + @Test + @DisplayName("Should return product detail") + void shouldReturnProductDetail() { + String productId = "2"; + String productName = "Product 2"; + Double productPrice = 19.99; + Boolean productAvailability = true; + + ProductDetailDto dto = new ProductDetailDto(productId, productName, productPrice, productAvailability); + Product expected = new Product(productId, productName, productPrice, productAvailability); + + mockGetChain(); + when(responseSpecMock.body(ProductDetailDto.class)).thenReturn(dto); + when(productMapperMock.toModel(dto)).thenReturn(expected); + + Product result = productClient.getProduct(productId); + + assertThat(result).isEqualTo(expected); + } + + @Test + @DisplayName("getSimilarProductIds fallback should rethrow ProductNotFoundException") + void fallbackShouldRethrowNotFoundException() { + String productId = "4"; + String errorBody = "not found"; + + ProductNotFoundException ex = new ProductNotFoundException(productId, errorBody); + + assertThatThrownBy(() -> productClient.getSimilarProductIdsFallback(productId, ex)) + .isInstanceOf(ProductNotFoundException.class); + } + + @Test + @DisplayName("getSimilarProductIds fallback should return empty list for generic throwable") + void fallbackShouldReturnEmptyListForGenericError() { + String productId = "5"; + String errorMessage = "connection refused"; + + List result = productClient.getSimilarProductIdsFallback(productId, + new Throwable(errorMessage)); + + assertThat(result).isEmpty(); + } + + @Test + @DisplayName("getProduct fallback should return null") + void getProductFallbackShouldReturnNull() { + String productId = "2"; + String errorMessage = "timeout"; + + Product result = productClient.getProductFallback(productId, + new TimeoutException(errorMessage)); + + assertThat(result).isNull(); + } + + private void mockGetChain() { + doReturn(requestHeadersUriSpecMock).when(productRestClientMock).get(); + doReturn(requestHeadersSpecMock).when(requestHeadersUriSpecMock).uri(any(String.class), any(Object.class)); + doReturn(responseSpecMock).when(requestHeadersSpecMock).retrieve(); + doReturn(responseSpecMock).when(responseSpecMock).onStatus(any(), any()); + } + +} \ No newline at end of file diff --git a/products/src/test/java/org/challenge/products/infrastructure/config/TestRedisConfig.java b/products/src/test/java/org/challenge/products/infrastructure/config/TestRedisConfig.java new file mode 100644 index 00000000..cd955e48 --- /dev/null +++ b/products/src/test/java/org/challenge/products/infrastructure/config/TestRedisConfig.java @@ -0,0 +1,50 @@ +package org.challenge.products.infrastructure.config; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import redis.embedded.RedisServer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; + +import java.io.IOException; + +@TestConfiguration +public class TestRedisConfig { + + private final RedisServer redisServer; + + + public TestRedisConfig(@Value("${spring.data.redis.port}") int port) throws IOException { + this.redisServer = new RedisServer(port); + } + + @PostConstruct + public void postConstruct() throws IOException { + redisServer.start(); + } + + @PreDestroy + public void preDestroy() throws IOException { + redisServer.stop(); + } + + @Bean + public RestTemplateBuilder restTemplateBuilder() { + ObjectMapper objectMapper = new ObjectMapper() + .registerModule(new JavaTimeModule()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + MappingJackson2HttpMessageConverter converter = + new MappingJackson2HttpMessageConverter(objectMapper); + + return new RestTemplateBuilder() + .additionalMessageConverters(converter); + } + +} diff --git a/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerIT.java b/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerIT.java new file mode 100644 index 00000000..c2ae15f2 --- /dev/null +++ b/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerIT.java @@ -0,0 +1,187 @@ +package org.challenge.products.infrastructure.controller; + +import com.github.tomakehurst.wiremock.WireMockServer; +import org.challenge.products.infrastructure.config.TestRedisConfig; +import org.challenge.products.infrastructure.dto.ErrorResponseDto; +import org.challenge.products.infrastructure.dto.ProductResponseDto; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.cache.CacheManager; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.wiremock.spring.ConfigureWireMock; +import org.wiremock.spring.EnableWireMock; +import org.wiremock.spring.InjectWireMock; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@Import(TestRedisConfig.class) +@EnableWireMock(@ConfigureWireMock(port = 8089)) +class ProductControllerIT { + + @LocalServerPort + private Integer port; + + @Autowired + private TestRestTemplate testRestTemplate; + + @InjectWireMock + private WireMockServer wireMock; + + @Autowired + private CacheManager cacheManager; + + @BeforeEach + void setUp() { + wireMock.resetAll(); + cacheManager.getCacheNames() + .forEach(name -> cacheManager.getCache(name).clear()); + } + + @Test + @DisplayName("Should return similar products for a valid product id") + void shouldReturnSimilarProducts() { + wireMock.stubFor(get(urlEqualTo("/product/1/similarids")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody("[2, 3]"))); + + wireMock.stubFor(get(urlEqualTo("/product/2")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody(""" + {"id":"2","name":"Product 2","price":19.99,"availability":true} + """))); + + wireMock.stubFor(get(urlEqualTo("/product/3")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody(""" + {"id":"3","name":"Product 3","price":29.99,"availability":true} + """))); + + ResponseEntity response = + testRestTemplate.getForEntity(buildUrl("product/1/similar"), ProductResponseDto[].class); + + Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assertions.assertNotNull(response.getBody()); + Assertions.assertEquals(2, response.getBody().length); + } + + @Test + @DisplayName("Should return 404 when similar ids endpoint returns 404") + void shouldReturn404WhenProductNotFound() { + wireMock.stubFor(get(urlEqualTo("/product/4/similarids")) + .willReturn(aResponse().withStatus(404))); + + ResponseEntity response = + testRestTemplate.getForEntity(buildUrl("product/4/similar"), ErrorResponseDto.class); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + Assertions.assertNotNull(response.getBody()); + Assertions.assertNotNull(response.getBody().message()); + } + + @Test + @DisplayName("Should return 200 with empty list when downstream returns 5xx — circuit breaker fallback") + void shouldReturnEmptyListWhenDownstreamErrors() { + wireMock.stubFor(get(urlEqualTo("/product/5/similarids")) + .willReturn(aResponse().withStatus(500))); + + ResponseEntity response = + testRestTemplate.getForEntity(buildUrl("product/5/similar"), ProductResponseDto[].class); + + // circuit breaker fallback returns List.of() — contract says 200 with empty list is valid + Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assertions.assertNotNull(response.getBody()); + Assertions.assertEquals(0, response.getBody().length); + } + + @Test + @DisplayName("Should skip product and return partial list when a product detail returns 404") + void shouldSkipProductWhenDetailNotFound() { + wireMock.stubFor(get(urlEqualTo("/product/1/similarids")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody("[2, 99]"))); + + wireMock.stubFor(get(urlEqualTo("/product/2")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody(""" + {"id":"2","name":"Product 2","price":19.99,"availability":true} + """))); + + wireMock.stubFor(get(urlEqualTo("/product/99")) + .willReturn(aResponse().withStatus(404))); + + ResponseEntity response = + testRestTemplate.getForEntity(buildUrl("product/1/similar"), ProductResponseDto[].class); + + // product 99 was skipped, product 2 returned + Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assertions.assertNotNull(response.getBody()); + Assertions.assertEquals(1, response.getBody().length); + Assertions.assertEquals("2", response.getBody()[0].productId()); + } + + @Test + @DisplayName("Should return empty list when product detail throws Any other exception") + void shouldReturnEmptyListWhenProductDetailServiceThrowsAnyException() { + wireMock.stubFor(get(urlEqualTo("/product/1/similarids")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody("[2, 3]"))); + + wireMock.stubFor(get(urlEqualTo("/product/2")) + .willReturn(aResponse().withStatus(500))); + + wireMock.stubFor(get(urlEqualTo("/product/3")) + .willReturn(aResponse().withStatus(500))); + + ResponseEntity response = + testRestTemplate.getForEntity(buildUrl("product/1/similar"), ProductResponseDto[].class); + + Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assertions.assertNotNull(response.getBody()); + Assertions.assertEquals(0, response.getBody().length); + } + + @Test + @DisplayName("Should serve result from cache on second request") + void shouldCacheSimilarProducts() { + wireMock.stubFor(get(urlEqualTo("/product/1/similarids")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody("[2]"))); + + wireMock.stubFor(get(urlEqualTo("/product/2")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody(""" + {"id":"2","name":"Product 2","price":19.99,"availability":true} + """))); + + String url = buildUrl("product/1/similar"); + + testRestTemplate.getForEntity(url, ProductResponseDto[].class); + testRestTemplate.getForEntity(url, ProductResponseDto[].class); + + wireMock.verify(1, getRequestedFor(urlEqualTo("/product/1/similarids"))); + wireMock.verify(1, getRequestedFor(urlEqualTo("/product/2"))); + } + + private String buildUrl(String path) { + return "http://localhost:%s/%s".formatted(port, path); + } +} \ No newline at end of file diff --git a/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerTest.java b/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerTest.java new file mode 100644 index 00000000..3c24e95b --- /dev/null +++ b/products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerTest.java @@ -0,0 +1,96 @@ +package org.challenge.products.infrastructure.controller; + +import org.challenge.products.application.port.in.GetSimilarProductsUseCase; +import org.challenge.products.domain.exception.ProductNotFoundException; +import org.challenge.products.domain.model.Product; +import org.challenge.products.infrastructure.dto.ProductResponseDto; +import org.challenge.products.infrastructure.mapper.ProductMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@WebMvcTest(ProductController.class) +class ProductControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private GetSimilarProductsUseCase getSimilarProductsUseCase; + + @MockitoBean + private ProductMapper productMapper; + + + @Test + @DisplayName("Should return 200 with similar products") + void shouldReturnSimilarProducts() throws Exception { + String productId1 = "1"; + String productId2 = "2"; + String productName2 = "Product 2"; + Double productPrice2 = 19.99; + Boolean productAvailability2 = true; + + Product product = new Product(productId2, productName2, productPrice2, productAvailability2); + ProductResponseDto dto = new ProductResponseDto(productId2, productName2, productPrice2, productAvailability2); + + when(getSimilarProductsUseCase.getSimilarProducts(productId1)).thenReturn(List.of(product)); + when(productMapper.toResponseDTO(product)).thenReturn(dto); + + mockMvc.perform(get("/product/{productId}/similar", productId1) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0].product_id").value(productId2)) + .andExpect(jsonPath("$[0].name").value(productName2)) + .andExpect(jsonPath("$[0].price").value(productPrice2)) + .andExpect(jsonPath("$[0].availability").value(productAvailability2)); + } + + + @Test + @DisplayName("Should return 200 with empty list when no similar products") + void shouldReturnEmptyList() throws Exception { + + String productId = "1"; + + when(getSimilarProductsUseCase.getSimilarProducts(productId)) + .thenReturn(List.of()); + + mockMvc.perform(get("/product/{productId}/similar", productId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(0)); + } + + @Test + @DisplayName("Should return 404 when product not found") + void shouldReturn404WhenProductNotFound() throws Exception { + + String productId = "4"; + String mockedResponseBody = "not found"; + String expectedErrorMessage = String.format("Product with id %s not found. Response body: %s", productId, mockedResponseBody); + + when(getSimilarProductsUseCase.getSimilarProducts(productId)) + .thenThrow(new ProductNotFoundException(productId, mockedResponseBody)); + + mockMvc.perform(get("/product/{productId}/similar", productId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value(expectedErrorMessage)) + .andExpect(jsonPath("$.timestamp").exists()); + } + +} \ No newline at end of file diff --git a/products/src/test/resources/application-test.properties b/products/src/test/resources/application-test.properties new file mode 100644 index 00000000..8b7631ca --- /dev/null +++ b/products/src/test/resources/application-test.properties @@ -0,0 +1,3 @@ +spring.data.redis.host=localhost +spring.data.redis.port=6370 +integrations.productClient.baseUrl=http://localhost:8089/product \ No newline at end of file