From d9a0bf8b5213cd4f6f85922455c9d6938b17ee58 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Wed, 22 Apr 2026 12:46:39 +0200 Subject: [PATCH 01/11] First commit. Add base project. --- .gitattributes | 10 + .gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + products/mvnw | 295 ++++++++++++++++++ products/mvnw.cmd | 189 +++++++++++ products/pom.xml | 124 ++++++++ .../products/ProductsApplication.java | 13 + .../src/main/resources/application.properties | 1 + .../products/ProductsApplicationTests.java | 13 + 9 files changed, 681 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 products/.mvn/wrapper/maven-wrapper.properties create mode 100644 products/mvnw create mode 100644 products/mvnw.cmd create mode 100644 products/pom.xml create mode 100644 products/src/main/java/org/challenge/products/ProductsApplication.java create mode 100644 products/src/main/resources/application.properties create mode 100644 products/src/test/java/org/challenge/products/ProductsApplicationTests.java 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/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/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..690b8159 --- /dev/null +++ b/products/pom.xml @@ -0,0 +1,124 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + org.challenge + products + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 21 + 2025.1.1 + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 3.0.2 + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-resilience4j + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + 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/resources/application.properties b/products/src/main/resources/application.properties new file mode 100644 index 00000000..bf5bc7a1 --- /dev/null +++ b/products/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=products diff --git a/products/src/test/java/org/challenge/products/ProductsApplicationTests.java b/products/src/test/java/org/challenge/products/ProductsApplicationTests.java new file mode 100644 index 00000000..0d2b5db4 --- /dev/null +++ b/products/src/test/java/org/challenge/products/ProductsApplicationTests.java @@ -0,0 +1,13 @@ +package org.challenge.products; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ProductsApplicationTests { + + @Test + void contextLoads() { + } + +} From 4215e954c8e0bafcba4dee9b28747052127953a0 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Wed, 22 Apr 2026 19:13:05 +0200 Subject: [PATCH 02/11] implemented mock flow with happy path --- products/pom.xml | 47 +++++-------------- .../port/in/GetSimilarProductsUseCase.java | 9 ++++ .../application/port/out/ProductPort.java | 10 ++++ .../application/service/ProductService.java | 27 +++++++++++ .../products/domain/model/Product.java | 8 ++++ .../infrastructure/client/ProductClient.java | 24 ++++++++++ .../controller/ProductController.java | 33 +++++++++++++ .../infrastructure/dto/ProductDetailDto.java | 8 ++++ .../dto/ProductResponseDto.java | 12 +++++ .../products/mapper/ProductMapper.java | 12 +++++ .../src/main/resources/application.properties | 2 + 11 files changed, 158 insertions(+), 34 deletions(-) create mode 100644 products/src/main/java/org/challenge/products/application/port/in/GetSimilarProductsUseCase.java create mode 100644 products/src/main/java/org/challenge/products/application/port/out/ProductPort.java create mode 100644 products/src/main/java/org/challenge/products/application/service/ProductService.java create mode 100644 products/src/main/java/org/challenge/products/domain/model/Product.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java create mode 100644 products/src/main/java/org/challenge/products/mapper/ProductMapper.java diff --git a/products/pom.xml b/products/pom.xml index 690b8159..2ce18b38 100644 --- a/products/pom.xml +++ b/products/pom.xml @@ -29,6 +29,8 @@ 21 2025.1.1 + 1.6.3 + 3.0.2 @@ -38,18 +40,17 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 3.0.2 + ${openapi.version} org.springframework.cloud spring-cloud-starter-circuitbreaker-resilience4j - - - org.projectlombok - lombok - true - + + org.mapstruct + mapstruct + ${mapstruct.version} + org.springframework.boot spring-boot-starter-webmvc-test @@ -73,14 +74,6 @@ org.springframework.boot spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - org.apache.maven.plugins @@ -94,25 +87,11 @@ - - org.projectlombok - lombok - - - - - - default-testCompile - test-compile - - testCompile - - - - - org.projectlombok - lombok - + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + 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..d9a8fa04 --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/port/out/ProductPort.java @@ -0,0 +1,10 @@ +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 getProductDetail(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..7c6f3579 --- /dev/null +++ b/products/src/main/java/org/challenge/products/application/service/ProductService.java @@ -0,0 +1,27 @@ +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.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class ProductService implements GetSimilarProductsUseCase { + + private final ProductPort productPort; + + public ProductService(ProductPort productPort) { + this.productPort = productPort; + } + + @Override + public List getSimilarProducts(String productId) { + return productPort + .getSimilarProductIds(productId) + .stream() + .map(productPort::getProductDetail) + .toList(); + } +} 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..70dd0e76 --- /dev/null +++ b/products/src/main/java/org/challenge/products/domain/model/Product.java @@ -0,0 +1,8 @@ +package org.challenge.products.domain.model; + +public record Product( + String productId, + String name, + Double price, + Boolean availability +) {} 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..5025624a --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -0,0 +1,24 @@ +package org.challenge.products.infrastructure.client; + +import org.challenge.products.application.port.out.ProductPort; +import org.challenge.products.domain.model.Product; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class ProductClient implements ProductPort { + + //TODO: implement the client to call the external service and get the similar product ids, for now we are returning a hardcoded list of similar product ids + @Override + public List getSimilarProductIds(String productId) { + return List.of("1", "2", "3", "4", "5"); + } + + //TODO: Implement the client to call the external service to get the product details. For now, we are returning a dummy product detail. + @Override + public Product getProductDetail(String productId) { + return new Product(productId, null, null, null); + } + +} \ 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..17e269c8 --- /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.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/ProductDetailDto.java b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java new file mode 100644 index 00000000..ea7bedd4 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java @@ -0,0 +1,8 @@ +package org.challenge.products.infrastructure.dto; + +public record ProductDetailDto ( + String productId, + String name, + Double price, + Boolean availability +) {} 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..3c19c1a2 --- /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 tools.jackson.databind.PropertyNamingStrategies; +import tools.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/mapper/ProductMapper.java b/products/src/main/java/org/challenge/products/mapper/ProductMapper.java new file mode 100644 index 00000000..d0113947 --- /dev/null +++ b/products/src/main/java/org/challenge/products/mapper/ProductMapper.java @@ -0,0 +1,12 @@ +package org.challenge.products.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; + +@Mapper(componentModel = "spring") +public interface ProductMapper { + ProductResponseDto toResponseDTO(Product product); + Product toModel(ProductDetailDto productDetailDto); +} diff --git a/products/src/main/resources/application.properties b/products/src/main/resources/application.properties index bf5bc7a1..f9241f9f 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -1 +1,3 @@ spring.application.name=products +server.port=5000 +existing.api.base-url=http://localhost:3001 \ No newline at end of file From d349e0e050cd672e701afa12b6ac697ed990df5f Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Wed, 22 Apr 2026 22:31:54 +0200 Subject: [PATCH 03/11] implemented: happy path for GET similar products list request --- .../infrastructure/client/ProductClient.java | 15 +++++++++++++-- .../config/RestClientConfig.java | 18 ++++++++++++++++++ .../src/main/resources/application.properties | 5 ++++- 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java 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 index 5025624a..7870b74c 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -2,17 +2,28 @@ import org.challenge.products.application.port.out.ProductPort; import org.challenge.products.domain.model.Product; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; import java.util.List; @Component public class ProductClient implements ProductPort { - //TODO: implement the client to call the external service and get the similar product ids, for now we are returning a hardcoded list of similar product ids + private final RestClient productRestClient; + + public ProductClient(RestClient productRestClient) { + this.productRestClient = productRestClient; + } + @Override public List getSimilarProductIds(String productId) { - return List.of("1", "2", "3", "4", "5"); + List ids = productRestClient.get() + .uri("/{productId}/similarids", productId) + .retrieve() + .body(ParameterizedTypeReference.forType(List.class)); + return ids.stream().map(Object::toString).toList(); } //TODO: Implement the client to call the external service to get the product details. For now, we are returning a dummy product detail. 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..348210d6 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java @@ -0,0 +1,18 @@ +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.web.client.RestClient; + +@Configuration +public class RestClientConfig { + + @Bean + public RestClient productRestClient(@Value("${integrations.product-client.base-url}") String productClientBaseUrl) { + return RestClient.builder() + .baseUrl(productClientBaseUrl) + .build(); + } + +} diff --git a/products/src/main/resources/application.properties b/products/src/main/resources/application.properties index f9241f9f..23bca504 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -1,3 +1,6 @@ spring.application.name=products server.port=5000 -existing.api.base-url=http://localhost:3001 \ No newline at end of file + +integrations.product-client.base-url=http://localhost:3001/product + +springdoc.api-docs.enabled=true \ No newline at end of file From 0a6ce5d64766737093cb4b382db4217debfdeb07 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Wed, 22 Apr 2026 23:08:20 +0200 Subject: [PATCH 04/11] implemented: happy path for GET product detail request --- .../application/service/ProductService.java | 2 +- .../infrastructure/client/ProductClient.java | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) 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 index 7c6f3579..146f39a4 100644 --- a/products/src/main/java/org/challenge/products/application/service/ProductService.java +++ b/products/src/main/java/org/challenge/products/application/service/ProductService.java @@ -20,7 +20,7 @@ public ProductService(ProductPort productPort) { public List getSimilarProducts(String productId) { return productPort .getSimilarProductIds(productId) - .stream() + .parallelStream() .map(productPort::getProductDetail) .toList(); } 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 index 7870b74c..4f768446 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -2,6 +2,8 @@ import org.challenge.products.application.port.out.ProductPort; import org.challenge.products.domain.model.Product; +import org.challenge.products.infrastructure.dto.ProductDetailDto; +import org.challenge.products.mapper.ProductMapper; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClient; @@ -12,9 +14,11 @@ public class ProductClient implements ProductPort { private final RestClient productRestClient; + private final ProductMapper productMapper; - public ProductClient(RestClient productRestClient) { + public ProductClient(RestClient productRestClient, ProductMapper productMapper) { this.productRestClient = productRestClient; + this.productMapper = productMapper; } @Override @@ -26,10 +30,13 @@ public List getSimilarProductIds(String productId) { return ids.stream().map(Object::toString).toList(); } - //TODO: Implement the client to call the external service to get the product details. For now, we are returning a dummy product detail. @Override public Product getProductDetail(String productId) { - return new Product(productId, null, null, null); + ProductDetailDto responseBody = productRestClient.get() + .uri("/{productId}", productId) + .retrieve() + .body(ProductDetailDto.class); + return productMapper.toModel(responseBody); } } \ No newline at end of file From 16cb2d65bf6d4ac486d393e8ad05f577cfcee8db Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Thu, 23 Apr 2026 12:53:56 +0200 Subject: [PATCH 05/11] implemented: centralized exception handling and debug logs for traceability --- .../exception/ExternalServiceException.java | 11 ++++ .../application/port/out/ProductPort.java | 3 +- .../application/service/ProductService.java | 24 +++++++- .../exception/ProductNotFoundException.java | 18 ++++++ .../infrastructure/client/ProductClient.java | 60 ++++++++++++++++--- .../controller/ErrorResponse.java | 7 +++ .../controller/GlobalExceptionHandler.java | 26 ++++++++ .../controller/ProductController.java | 2 +- .../infrastructure/dto/ProductDetailDto.java | 2 +- .../mapper/ProductMapper.java | 5 +- .../challenge/products/util/StringUtil.java | 23 +++++++ 11 files changed, 167 insertions(+), 14 deletions(-) create mode 100644 products/src/main/java/org/challenge/products/application/exception/ExternalServiceException.java create mode 100644 products/src/main/java/org/challenge/products/domain/exception/ProductNotFoundException.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java rename products/src/main/java/org/challenge/products/{ => infrastructure}/mapper/ProductMapper.java (74%) create mode 100644 products/src/main/java/org/challenge/products/util/StringUtil.java 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/out/ProductPort.java b/products/src/main/java/org/challenge/products/application/port/out/ProductPort.java index d9a8fa04..b068cec4 100644 --- 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 @@ -6,5 +6,6 @@ public interface ProductPort { List getSimilarProductIds(String productId); - Product getProductDetail(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 index 146f39a4..18f6b6f1 100644 --- a/products/src/main/java/org/challenge/products/application/service/ProductService.java +++ b/products/src/main/java/org/challenge/products/application/service/ProductService.java @@ -3,13 +3,18 @@ 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.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) { @@ -18,10 +23,25 @@ public ProductService(ProductPort productPort) { @Override public List getSimilarProducts(String productId) { - return productPort + log.debug("Fetching similar products for productId: {}", productId); + + List result = productPort .getSimilarProductIds(productId) .parallelStream() - .map(productPort::getProductDetail) + .flatMap(id -> getProduct(id).stream()) .toList(); + + log.debug("Found {} similar products for productId: {}", result.size(), productId); + return result; } + + private Optional getProduct(String productId) { + try { + return Optional.of(productPort.getProduct(productId)); + } catch (Exception e) { + log.warn("Error fetching product details for id: {} - error: {}", productId, e.getMessage()); + return Optional.empty(); + } + } + } 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/infrastructure/client/ProductClient.java b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java index 4f768446..6f7cc2f0 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -1,18 +1,28 @@ package org.challenge.products.infrastructure.client; +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.mapper.ProductMapper; -import org.springframework.core.ParameterizedTypeReference; +import org.challenge.products.infrastructure.mapper.ProductMapper; +import org.challenge.products.util.StringUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClient; +import java.util.Arrays; 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; @@ -23,20 +33,54 @@ public ProductClient(RestClient productRestClient, ProductMapper productMapper) @Override public List getSimilarProductIds(String productId) { - List ids = productRestClient.get() + log.debug("Fetching similar product ids for productId: {}", productId); + String[] ids = productRestClient.get() .uri("/{productId}/similarids", productId) .retrieve() - .body(ParameterizedTypeReference.forType(List.class)); - return ids.stream().map(Object::toString).toList(); + .onStatus(HttpStatus.NOT_FOUND::equals, + (req, res) -> { + log.error("Similar products for id: {} not found", productId); + throw new ProductNotFoundException("Similar products for id: {} not found - body response: {}", productId, StringUtil.readString(res.getBody())); + }) + .onStatus(HttpStatusCode::is5xxServerError, + (req, res) -> { + log.error("Error fetching similar ids for id: {} - body response: {}", productId, StringUtil.readString(res.getBody())); + throw new ExternalServiceException("External service error fetching similar ids for: " + productId, + StringUtil.readString(res.getBody())); + }) + .body(String[].class); + + List result = Optional.ofNullable(ids) + .map(Arrays::asList) + .orElse(List.of()); + + log.debug("Found {} similar product ids for productId: {}", result.size(), productId); + return result; } @Override - public Product getProductDetail(String productId) { + public Product getProduct(String productId) { + log.debug("Fetching product details for productId: {}", productId); + ProductDetailDto responseBody = productRestClient.get() .uri("/{productId}", productId) .retrieve() + .onStatus(status -> status.value() == 404, + (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); - return productMapper.toModel(responseBody); - } + Product result = productMapper.toModel(responseBody); + log.debug("Successfully fetched product details for productId: {}", productId); + return result; + } } \ No newline at end of file diff --git a/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java b/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java new file mode 100644 index 00000000..6ae5d6e9 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java @@ -0,0 +1,7 @@ +package org.challenge.products.infrastructure.controller; + +import java.time.LocalDateTime; + +public record ErrorResponse (String message, LocalDateTime timestamp) { + +} 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..09aba582 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java @@ -0,0 +1,26 @@ +package org.challenge.products.infrastructure.controller; + +import org.challenge.products.application.exception.ExternalServiceException; +import org.challenge.products.domain.exception.ProductNotFoundException; +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 ErrorResponse(e.getMessage(), LocalDateTime.now())); + } + + @ExceptionHandler(ExternalServiceException.class) + public ResponseEntity handleServiceError(ExternalServiceException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .body(new ErrorResponse(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 index 17e269c8..f9f9e64d 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/ProductController.java @@ -2,7 +2,7 @@ import org.challenge.products.application.port.in.GetSimilarProductsUseCase; import org.challenge.products.infrastructure.dto.ProductResponseDto; -import org.challenge.products.mapper.ProductMapper; +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; 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 index ea7bedd4..313ed8cf 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java @@ -1,7 +1,7 @@ package org.challenge.products.infrastructure.dto; public record ProductDetailDto ( - String productId, + String id, String name, Double price, Boolean availability diff --git a/products/src/main/java/org/challenge/products/mapper/ProductMapper.java b/products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java similarity index 74% rename from products/src/main/java/org/challenge/products/mapper/ProductMapper.java rename to products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java index d0113947..3e344b97 100644 --- a/products/src/main/java/org/challenge/products/mapper/ProductMapper.java +++ b/products/src/main/java/org/challenge/products/infrastructure/mapper/ProductMapper.java @@ -1,12 +1,15 @@ -package org.challenge.products.mapper; +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); + } + } + + +} From 7b5c9a33fd20b103bc128268c64a4e8d879a6cdd Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Thu, 23 Apr 2026 18:02:00 +0200 Subject: [PATCH 06/11] implemented: redis configuration and restclient timeout for performance and resilience --- products/pom.xml | 8 ++++ .../products/domain/model/Product.java | 4 +- .../infrastructure/client/ProductClient.java | 3 ++ .../infrastructure/config/RedisConfig.java | 39 +++++++++++++++++++ .../config/RestClientConfig.java | 16 +++++++- .../infrastructure/dto/ProductDetailDto.java | 4 +- .../src/main/resources/application.properties | 7 +++- 7 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java diff --git a/products/pom.xml b/products/pom.xml index 2ce18b38..a1e10eac 100644 --- a/products/pom.xml +++ b/products/pom.xml @@ -46,6 +46,14 @@ org.springframework.cloud spring-cloud-starter-circuitbreaker-resilience4j + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-cache + org.mapstruct mapstruct 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 index 70dd0e76..e94b8d21 100644 --- a/products/src/main/java/org/challenge/products/domain/model/Product.java +++ b/products/src/main/java/org/challenge/products/domain/model/Product.java @@ -1,8 +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 index 6f7cc2f0..045ad117 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -9,6 +9,7 @@ import org.challenge.products.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.Cacheable; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.stereotype.Component; @@ -32,6 +33,7 @@ public ProductClient(RestClient productRestClient, ProductMapper productMapper) } @Override + @Cacheable(value = "similarIds", key = "#productId") public List getSimilarProductIds(String productId) { log.debug("Fetching similar product ids for productId: {}", productId); String[] ids = productRestClient.get() @@ -59,6 +61,7 @@ public List getSimilarProductIds(String productId) { } @Override + @Cacheable(value = "productDetail", key = "#productId") public Product getProduct(String productId) { log.debug("Fetching product details for productId: {}", productId); 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..e2067a01 --- /dev/null +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java @@ -0,0 +1,39 @@ +package org.challenge.products.infrastructure.config; + +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) { + RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofMinutes(5)) + .disableCachingNullValues() + .serializeKeysWith( + RedisSerializationContext.SerializationPair + .fromSerializer(new StringRedisSerializer())) + .serializeValuesWith( + RedisSerializationContext.SerializationPair + .fromSerializer(RedisSerializer.java())); + + return RedisCacheManager.builder(factory) + .cacheDefaults(defaultConfig) + .withCacheConfiguration("similarIds", + defaultConfig.entryTtl(Duration.ofMinutes(10))) + .withCacheConfiguration("productDetail", + defaultConfig.entryTtl(Duration.ofMinutes(5))) + .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 index 348210d6..e91536bc 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java @@ -3,15 +3,29 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.JdkClientHttpRequestFactory; import org.springframework.web.client.RestClient; +import java.net.http.HttpClient; +import java.time.Duration; + @Configuration public class RestClientConfig { @Bean - public RestClient productRestClient(@Value("${integrations.product-client.base-url}") String productClientBaseUrl) { + public RestClient productRestClient( + @Value("${integrations.product-client.base-url}") String productClientBaseUrl) { + + HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(2)) + .build(); + + JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient); + factory.setReadTimeout(Duration.ofSeconds(3)); + return RestClient.builder() .baseUrl(productClientBaseUrl) + .requestFactory(factory) .build(); } 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 index 313ed8cf..44d4021f 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductDetailDto.java @@ -1,8 +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/resources/application.properties b/products/src/main/resources/application.properties index 23bca504..a4318bd9 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -3,4 +3,9 @@ server.port=5000 integrations.product-client.base-url=http://localhost:3001/product -springdoc.api-docs.enabled=true \ No newline at end of file +# OpenAPI configuration +springdoc.api-docs.enabled=true + +# Redis configuration +spring.data.redis.host=${SPRING_DATA_REDIS_HOST:localhost} +spring.data.redis.port=6379 \ No newline at end of file From 2ce0dac485b2fd7a6d04e4bfd827564edbc1c842 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Thu, 23 Apr 2026 21:26:13 +0200 Subject: [PATCH 07/11] downgrade: Spring version for compatibility with resilience4j --- products/pom.xml | 51 +++++++++++-------- .../dto/ProductResponseDto.java | 4 +- 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/products/pom.xml b/products/pom.xml index a1e10eac..dad7978a 100644 --- a/products/pom.xml +++ b/products/pom.xml @@ -2,12 +2,12 @@ 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 4.0.5 - - + + org.springframework.boot + spring-boot-starter-parent + 3.5.14 + + org.challenge products 0.0.1-SNAPSHOT @@ -28,24 +28,33 @@ 21 - 2025.1.1 + 2025.0.2 1.6.3 - 3.0.2 + 2.8.16 - - org.springframework.boot - spring-boot-starter-webmvc - + + org.springframework.boot + spring-boot-starter-web + org.springdoc springdoc-openapi-starter-webmvc-ui ${openapi.version} - - org.springframework.cloud - spring-cloud-starter-circuitbreaker-resilience4j - + + 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 @@ -59,11 +68,11 @@ mapstruct ${mapstruct.version} - - org.springframework.boot - spring-boot-starter-webmvc-test - test - + + org.springframework.boot + spring-boot-starter-test + test + 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 index 3c19c1a2..e4379dde 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java +++ b/products/src/main/java/org/challenge/products/infrastructure/dto/ProductResponseDto.java @@ -1,7 +1,7 @@ package org.challenge.products.infrastructure.dto; -import tools.jackson.databind.PropertyNamingStrategies; -import tools.jackson.databind.annotation.JsonNaming; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public record ProductResponseDto( From 456124c7745cb55bc09519e3ddb56775105a025d Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Fri, 24 Apr 2026 00:16:25 +0200 Subject: [PATCH 08/11] implemented: resillience4j + optimized cache --- .../application/service/ProductService.java | 9 ++-- .../infrastructure/client/ProductClient.java | 44 +++++++++++++------ .../infrastructure/config/RedisConfig.java | 13 +++--- .../config/RestClientConfig.java | 18 +++----- .../src/main/resources/application.properties | 25 +++++++++-- 5 files changed, 68 insertions(+), 41 deletions(-) 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 index 18f6b6f1..e8678fa2 100644 --- a/products/src/main/java/org/challenge/products/application/service/ProductService.java +++ b/products/src/main/java/org/challenge/products/application/service/ProductService.java @@ -5,6 +5,7 @@ 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; @@ -22,6 +23,7 @@ public ProductService(ProductPort productPort) { } @Override + @Cacheable(value = "similarProducts", key = "#productId") public List getSimilarProducts(String productId) { log.debug("Fetching similar products for productId: {}", productId); @@ -36,12 +38,7 @@ public List getSimilarProducts(String productId) { } private Optional getProduct(String productId) { - try { - return Optional.of(productPort.getProduct(productId)); - } catch (Exception e) { - log.warn("Error fetching product details for id: {} - error: {}", productId, e.getMessage()); - return Optional.empty(); - } + return Optional.ofNullable(productPort.getProduct(productId)); } } 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 index 045ad117..33b90a75 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java +++ b/products/src/main/java/org/challenge/products/infrastructure/client/ProductClient.java @@ -1,5 +1,6 @@ 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; @@ -9,13 +10,12 @@ import org.challenge.products.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.cache.annotation.Cacheable; +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.Arrays; import java.util.List; import java.util.Optional; @@ -33,42 +33,51 @@ public ProductClient(RestClient productRestClient, ProductMapper productMapper) } @Override - @Cacheable(value = "similarIds", key = "#productId") + @CircuitBreaker(name = "productClient", fallbackMethod = "getSimilarProductIdsFallback") public List getSimilarProductIds(String productId) { log.debug("Fetching similar product ids for productId: {}", productId); - String[] ids = productRestClient.get() + List ids = productRestClient.get() .uri("/{productId}/similarids", productId) .retrieve() .onStatus(HttpStatus.NOT_FOUND::equals, (req, res) -> { - log.error("Similar products for id: {} not found", productId); throw new ProductNotFoundException("Similar products for id: {} not found - body response: {}", productId, StringUtil.readString(res.getBody())); }) .onStatus(HttpStatusCode::is5xxServerError, (req, res) -> { - log.error("Error fetching similar ids for id: {} - body response: {}", productId, StringUtil.readString(res.getBody())); throw new ExternalServiceException("External service error fetching similar ids for: " + productId, StringUtil.readString(res.getBody())); }) - .body(String[].class); + .body(ParameterizedTypeReference.forType(List.class)); List result = Optional.ofNullable(ids) - .map(Arrays::asList) - .orElse(List.of()); + .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 - @Cacheable(value = "productDetail", key = "#productId") + @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(status -> status.value() == 404, + .onStatus(HttpStatus.NOT_FOUND::equals, (req, res) -> { log.error("Product with id: {} not found", productId); throw new ProductNotFoundException(productId, StringUtil.readString(res.getBody())); @@ -82,8 +91,15 @@ public Product getProduct(String productId) { }) .body(ProductDetailDto.class); - Product result = productMapper.toModel(responseBody); - log.debug("Successfully fetched product details for productId: {}", productId); - return result; + 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 index e2067a01..92f5ddee 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RedisConfig.java @@ -1,5 +1,6 @@ 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; @@ -17,10 +18,11 @@ public class RedisConfig { @Bean - public RedisCacheManager cacheManager(RedisConnectionFactory factory) { + public RedisCacheManager cacheManager(RedisConnectionFactory factory, + @Value("${cache.ttl.millis}") long timeToLive, + @Value("${cache.similarProducts.name}") String similarProductsCacheName) { RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofMinutes(5)) - .disableCachingNullValues() + .entryTtl(Duration.ofMillis(timeToLive)) .serializeKeysWith( RedisSerializationContext.SerializationPair .fromSerializer(new StringRedisSerializer())) @@ -30,10 +32,7 @@ public RedisCacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.builder(factory) .cacheDefaults(defaultConfig) - .withCacheConfiguration("similarIds", - defaultConfig.entryTtl(Duration.ofMinutes(10))) - .withCacheConfiguration("productDetail", - defaultConfig.entryTtl(Duration.ofMinutes(5))) + .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 index e91536bc..3a127fcb 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java +++ b/products/src/main/java/org/challenge/products/infrastructure/config/RestClientConfig.java @@ -3,25 +3,21 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestClient; -import java.net.http.HttpClient; -import java.time.Duration; - @Configuration public class RestClientConfig { @Bean public RestClient productRestClient( - @Value("${integrations.product-client.base-url}") String productClientBaseUrl) { - - HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(Duration.ofSeconds(2)) - .build(); + @Value("${integrations.productClient.baseUrl}") String productClientBaseUrl, + @Value("${integrations.productClient.connectTimeout}") int connectTimeout, + @Value("${integrations.productClient.readTimeout}") int readTimeout) { - JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient); - factory.setReadTimeout(Duration.ofSeconds(3)); + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(connectTimeout); + factory.setReadTimeout(readTimeout); return RestClient.builder() .baseUrl(productClientBaseUrl) diff --git a/products/src/main/resources/application.properties b/products/src/main/resources/application.properties index a4318bd9..5e7692eb 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -1,11 +1,30 @@ spring.application.name=products server.port=5000 -integrations.product-client.base-url=http://localhost:3001/product +integrations.productClient.baseUrl=http://localhost:3001/product +integrations.productClient.readTimeout=3000 +integrations.productClient.connectTimeout=2000 # OpenAPI configuration springdoc.api-docs.enabled=true -# Redis configuration +# Cache configuration spring.data.redis.host=${SPRING_DATA_REDIS_HOST:localhost} -spring.data.redis.port=6379 \ No newline at end of file +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.permittedNumberOfCallsInHalfOpenState=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 From c433a625df872689b790cf33acec76c260aa1cf1 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Fri, 24 Apr 2026 14:41:53 +0200 Subject: [PATCH 09/11] implemented: Unit and integration tests --- products/pom.xml | 18 +- .../controller/ErrorResponse.java | 7 - .../controller/GlobalExceptionHandler.java | 9 +- .../infrastructure/dto/ErrorResponseDto.java | 7 + .../src/main/resources/application.properties | 2 +- .../products/ProductsApplicationTests.java | 13 -- .../service/ProductServiceTest.java | 93 +++++++++ .../client/ProductClientTest.java | 140 +++++++++++++ .../config/TestRedisConfig.java | 50 +++++ .../controller/ProductControllerIT.java | 187 ++++++++++++++++++ .../controller/ProductControllerTest.java | 96 +++++++++ .../resources/application-test.properties | 3 + 12 files changed, 599 insertions(+), 26 deletions(-) delete mode 100644 products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java create mode 100644 products/src/main/java/org/challenge/products/infrastructure/dto/ErrorResponseDto.java delete mode 100644 products/src/test/java/org/challenge/products/ProductsApplicationTests.java create mode 100644 products/src/test/java/org/challenge/products/application/service/ProductServiceTest.java create mode 100644 products/src/test/java/org/challenge/products/infrastructure/client/ProductClientTest.java create mode 100644 products/src/test/java/org/challenge/products/infrastructure/config/TestRedisConfig.java create mode 100644 products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerIT.java create mode 100644 products/src/test/java/org/challenge/products/infrastructure/controller/ProductControllerTest.java create mode 100644 products/src/test/resources/application-test.properties diff --git a/products/pom.xml b/products/pom.xml index dad7978a..a7cf3004 100644 --- a/products/pom.xml +++ b/products/pom.xml @@ -73,7 +73,23 @@ 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 + + diff --git a/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java b/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java deleted file mode 100644 index 6ae5d6e9..00000000 --- a/products/src/main/java/org/challenge/products/infrastructure/controller/ErrorResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.challenge.products.infrastructure.controller; - -import java.time.LocalDateTime; - -public record ErrorResponse (String message, LocalDateTime timestamp) { - -} 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 index 09aba582..a06af665 100644 --- a/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java +++ b/products/src/main/java/org/challenge/products/infrastructure/controller/GlobalExceptionHandler.java @@ -2,6 +2,7 @@ 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; @@ -13,14 +14,14 @@ public class GlobalExceptionHandler { @ExceptionHandler(ProductNotFoundException.class) - public ResponseEntity handleNotFound(ProductNotFoundException e) { + public ResponseEntity handleNotFound(ProductNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new ErrorResponse(e.getMessage(), LocalDateTime.now())); + .body(new ErrorResponseDto(e.getMessage(), LocalDateTime.now())); } @ExceptionHandler(ExternalServiceException.class) - public ResponseEntity handleServiceError(ExternalServiceException e) { + public ResponseEntity handleServiceError(ExternalServiceException e) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .body(new ErrorResponse(e.getMessage(), LocalDateTime.now())); + .body(new ErrorResponseDto(e.getMessage(), LocalDateTime.now())); } } \ No newline at end of file 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/resources/application.properties b/products/src/main/resources/application.properties index 5e7692eb..9ece5a5b 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -19,7 +19,7 @@ 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.permittedNumberOfCallsInHalfOpenState=3 +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 diff --git a/products/src/test/java/org/challenge/products/ProductsApplicationTests.java b/products/src/test/java/org/challenge/products/ProductsApplicationTests.java deleted file mode 100644 index 0d2b5db4..00000000 --- a/products/src/test/java/org/challenge/products/ProductsApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.challenge.products; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class ProductsApplicationTests { - - @Test - void contextLoads() { - } - -} 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 From 27e2c513c2e01582ce7c0fc4f3ff756b31db5746 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Fri, 24 Apr 2026 15:43:53 +0200 Subject: [PATCH 10/11] dockerized application --- docker-compose.yaml | 15 +++++++++++++++ products/Dockerfile | 14 ++++++++++++++ .../src/main/resources/application.properties | 6 +++--- 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 products/Dockerfile 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/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/src/main/resources/application.properties b/products/src/main/resources/application.properties index 9ece5a5b..832a74da 100644 --- a/products/src/main/resources/application.properties +++ b/products/src/main/resources/application.properties @@ -1,7 +1,7 @@ spring.application.name=products -server.port=5000 +server.port=${SERVER_PORT:5000} -integrations.productClient.baseUrl=http://localhost:3001/product +integrations.productClient.baseUrl=http://${EXTERNAL_API_HOST:localhost:3001}/product integrations.productClient.readTimeout=3000 integrations.productClient.connectTimeout=2000 @@ -10,7 +10,7 @@ springdoc.api-docs.enabled=true # Cache configuration spring.data.redis.host=${SPRING_DATA_REDIS_HOST:localhost} -spring.data.redis.port=6379 +spring.data.redis.port=${SPRING_DATA_REDIS_PORT:6379} cache.ttl.millis=30000 cache.similarProducts.name=similarProducts From 86e0ca60c7b2b31f8278ad6a784c181c4a9ae991 Mon Sep 17 00:00:00 2001 From: Ineiles Reyes Date: Fri, 24 Apr 2026 16:20:19 +0200 Subject: [PATCH 11/11] added: README.md --- products/README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 products/README.md 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