From 9a695bd27b6d914c72906fd53ea35d014e984e98 Mon Sep 17 00:00:00 2001 From: rgamero Date: Fri, 26 Sep 2025 14:17:11 +0200 Subject: [PATCH] similar-products: implement similar products service with DTO mapping, error handling, resilience4j and tests --- similar-products/.gitattributes | 2 + similar-products/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + similar-products/mvnw | 295 ++++++++++++++++++ similar-products/mvnw.cmd | 189 +++++++++++ similar-products/pom.xml | 147 +++++++++ .../SimilarProductApplication.java | 13 + .../similarproducts/client/ProductClient.java | 79 +++++ .../config/ProductClientProperties.java | 20 ++ .../config/WebClientConfig.java | 35 +++ .../controller/ProductController.java | 25 ++ .../controller/dto/ProductDetailDTO.java | 11 + .../exception/NotFoundException.java | 8 + .../handler/GlobalExceptionHandler.java | 61 ++++ .../mapper/ProductDetailMapper.java | 12 + .../similarproducts/model/ProductDetail.java | 12 + .../service/ProductService.java | 11 + .../service/impl/ProductServiceImpl.java | 31 ++ .../src/main/resources/application.yml | 35 +++ .../ProductControllerIntegrationTest.java | 83 +++++ .../service/ProductServiceImplTest.java | 103 ++++++ 21 files changed, 1208 insertions(+) create mode 100644 similar-products/.gitattributes create mode 100644 similar-products/.gitignore create mode 100644 similar-products/.mvn/wrapper/maven-wrapper.properties create mode 100644 similar-products/mvnw create mode 100644 similar-products/mvnw.cmd create mode 100644 similar-products/pom.xml create mode 100644 similar-products/src/main/java/com/example/similarproducts/SimilarProductApplication.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/client/ProductClient.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/config/ProductClientProperties.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/config/WebClientConfig.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/controller/ProductController.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/controller/dto/ProductDetailDTO.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/exception/NotFoundException.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/exception/handler/GlobalExceptionHandler.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/mapper/ProductDetailMapper.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/model/ProductDetail.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/service/ProductService.java create mode 100644 similar-products/src/main/java/com/example/similarproducts/service/impl/ProductServiceImpl.java create mode 100644 similar-products/src/main/resources/application.yml create mode 100644 similar-products/src/test/java/com/example/similarproducts/controller/ProductControllerIntegrationTest.java create mode 100644 similar-products/src/test/java/com/example/similarproducts/service/ProductServiceImplTest.java diff --git a/similar-products/.gitattributes b/similar-products/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/similar-products/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/similar-products/.gitignore b/similar-products/.gitignore new file mode 100644 index 00000000..667aaef0 --- /dev/null +++ b/similar-products/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/similar-products/.mvn/wrapper/maven-wrapper.properties b/similar-products/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c0bcafe9 --- /dev/null +++ b/similar-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.11/apache-maven-3.9.11-bin.zip diff --git a/similar-products/mvnw b/similar-products/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/similar-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/similar-products/mvnw.cmd b/similar-products/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/similar-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/similar-products/pom.xml b/similar-products/pom.xml new file mode 100644 index 00000000..79af75cd --- /dev/null +++ b/similar-products/pom.xml @@ -0,0 +1,147 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.6 + + + com.example + similar-products + 0.0.1-SNAPSHOT + similarProduct + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + 2025.0.0 + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-reactor-resilience4j + + + + org.projectlombok + lombok + 1.18.32 + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + com.squareup.okhttp3 + mockwebserver + 4.11.0 + test + + + org.mapstruct + mapstruct + 1.5.5.Final + + + + org.mapstruct + mapstruct-processor + 1.5.5.Final + provided + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 21 + + + org.projectlombok + lombok + 1.18.32 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 21 + + + org.projectlombok + lombok + 1.18.32 + + + org.mapstruct + mapstruct-processor + 1.5.5.Final + + + + + + + + + + diff --git a/similar-products/src/main/java/com/example/similarproducts/SimilarProductApplication.java b/similar-products/src/main/java/com/example/similarproducts/SimilarProductApplication.java new file mode 100644 index 00000000..18af1b5d --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/SimilarProductApplication.java @@ -0,0 +1,13 @@ +package com.example.similarproducts; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SimilarProductApplication { + + public static void main(String[] args) { + SpringApplication.run(SimilarProductApplication.class, args); + } + +} diff --git a/similar-products/src/main/java/com/example/similarproducts/client/ProductClient.java b/similar-products/src/main/java/com/example/similarproducts/client/ProductClient.java new file mode 100644 index 00000000..e851a58a --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/client/ProductClient.java @@ -0,0 +1,79 @@ +package com.example.similarproducts.client; + +import com.example.similarproducts.config.ProductClientProperties; +import com.example.similarproducts.exception.NotFoundException; +import com.example.similarproducts.model.ProductDetail; +import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; +import io.github.resilience4j.retry.annotation.Retry; +import java.util.List; +import java.util.concurrent.TimeoutException; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientRequestException; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Component +@RequiredArgsConstructor +public class ProductClient { + + private static final String CB_NAME = "products"; + private static final String ERR_NOT_FOUND = "Product %s not found"; + + private final WebClient webClient; + private final ProductClientProperties props; + + @CircuitBreaker(name = CB_NAME) + @Retry(name = CB_NAME) + public Mono> getSimilarIds(String productId) { + return webClient.get() + .uri(props.getSimilarIds(), productId) + .retrieve() + .onStatus(s -> s.value() == 404, + resp -> Mono.error(new NotFoundException(ERR_NOT_FOUND.formatted(productId)))) + .bodyToMono(new ParameterizedTypeReference>() { + }) + .map(list -> list.stream().map(String::valueOf).toList()); + } + + @CircuitBreaker(name = CB_NAME) + @Retry(name = CB_NAME) + public Mono getProduct(String id) { + return webClient.get() + .uri(props.getProduct(), id) + .exchangeToMono(resp -> { + var status = resp.statusCode(); + int code = status.value(); + + if (code == 404) { + return Mono.empty(); + } + if (status.is2xxSuccessful()) { + return resp.bodyToMono(ProductDetail.class); + } + if (status.is5xxServerError()) { + return Mono.empty(); + } + return resp.createException().flatMap(Mono::error); + }) + .onErrorResume(ex -> + (ex instanceof WebClientRequestException || ex instanceof TimeoutException) + ? Mono.empty() + : Mono.error(ex) + ); + } + + + public Flux getProductsInOrder(List ids) { + return Flux.fromIterable(ids) + .concatMap(id -> + getProduct(id) + .onErrorResume(NotFoundException.class, e -> Mono.empty()) + .onErrorResume(TimeoutException.class, e -> Mono.empty()) + ); + } + + +} diff --git a/similar-products/src/main/java/com/example/similarproducts/config/ProductClientProperties.java b/similar-products/src/main/java/com/example/similarproducts/config/ProductClientProperties.java new file mode 100644 index 00000000..04bb717c --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/config/ProductClientProperties.java @@ -0,0 +1,20 @@ +package com.example.similarproducts.config; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@AllArgsConstructor +@ConfigurationProperties(prefix = "clients.products") +public class ProductClientProperties { + + private String baseUrl; + private int connectTimeoutMs; + private int readTimeoutMs; + private String product; + private String similarIds; + +} \ No newline at end of file diff --git a/similar-products/src/main/java/com/example/similarproducts/config/WebClientConfig.java b/similar-products/src/main/java/com/example/similarproducts/config/WebClientConfig.java new file mode 100644 index 00000000..3247b785 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/config/WebClientConfig.java @@ -0,0 +1,35 @@ +package com.example.similarproducts.config; + +import io.netty.channel.ChannelOption; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +@Configuration +@EnableConfigurationProperties(ProductClientProperties.class) +public class WebClientConfig { + + @Bean + public WebClient productsWebClient(ProductClientProperties props) { + + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, props.getConnectTimeoutMs()) + .responseTimeout(Duration.ofMillis(props.getReadTimeoutMs())) + .doOnConnected(conn -> conn + .addHandlerLast(new ReadTimeoutHandler(props.getReadTimeoutMs(), TimeUnit.MILLISECONDS)) + .addHandlerLast(new WriteTimeoutHandler(props.getReadTimeoutMs(), TimeUnit.MILLISECONDS))); + + return WebClient.builder() + .baseUrl(props.getBaseUrl()) + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); + + } +} \ No newline at end of file diff --git a/similar-products/src/main/java/com/example/similarproducts/controller/ProductController.java b/similar-products/src/main/java/com/example/similarproducts/controller/ProductController.java new file mode 100644 index 00000000..9f4de55b --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/controller/ProductController.java @@ -0,0 +1,25 @@ +package com.example.similarproducts.controller; + +import com.example.similarproducts.controller.dto.ProductDetailDTO; +import com.example.similarproducts.service.ProductService; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +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 reactor.core.publisher.Mono; + +@RestController +@RequiredArgsConstructor +@RequestMapping(path = "/product", produces = MediaType.APPLICATION_JSON_VALUE) +public class ProductController { + + private final ProductService productService; + + @GetMapping("/{productId}/similar") + public Mono> getSimilar(@PathVariable String productId) { + return productService.getSimilarProducts(productId); + } +} diff --git a/similar-products/src/main/java/com/example/similarproducts/controller/dto/ProductDetailDTO.java b/similar-products/src/main/java/com/example/similarproducts/controller/dto/ProductDetailDTO.java new file mode 100644 index 00000000..4203919a --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/controller/dto/ProductDetailDTO.java @@ -0,0 +1,11 @@ +package com.example.similarproducts.controller.dto; + +public record ProductDetailDTO( + String id, + String name, + double price, + boolean availability +) { + +} + diff --git a/similar-products/src/main/java/com/example/similarproducts/exception/NotFoundException.java b/similar-products/src/main/java/com/example/similarproducts/exception/NotFoundException.java new file mode 100644 index 00000000..431b1253 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/exception/NotFoundException.java @@ -0,0 +1,8 @@ +package com.example.similarproducts.exception; + +public class NotFoundException extends RuntimeException { + + public NotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/similar-products/src/main/java/com/example/similarproducts/exception/handler/GlobalExceptionHandler.java b/similar-products/src/main/java/com/example/similarproducts/exception/handler/GlobalExceptionHandler.java new file mode 100644 index 00000000..97ffdf29 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/exception/handler/GlobalExceptionHandler.java @@ -0,0 +1,61 @@ +package com.example.similarproducts.exception.handler; + +import com.example.similarproducts.exception.NotFoundException; +import io.netty.handler.timeout.ReadTimeoutException; +import java.util.concurrent.TimeoutException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.reactive.function.client.WebClientRequestException; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final String TITLE_NOT_FOUND = "Product not found"; + private static final String TITLE_TIMEOUT = "Request timeout"; + private static final String TITLE_UPSTREAM = "Upstream error"; + private static final String TITLE_INTERNAL = "Internal server error"; + private static final String DETAIL_TIMEOUT = "The request to the product service took too long"; + + @ExceptionHandler(NotFoundException.class) + public ProblemDetail handleNotFound(NotFoundException ex) { + return pd(HttpStatus.NOT_FOUND, TITLE_NOT_FOUND, ex.getMessage()); + } + + @ExceptionHandler({TimeoutException.class, ReadTimeoutException.class}) + public ProblemDetail handleTimeout(Exception ex) { + return pd(HttpStatus.GATEWAY_TIMEOUT, TITLE_TIMEOUT, DETAIL_TIMEOUT); + } + + @ExceptionHandler(WebClientRequestException.class) + public ProblemDetail handleWebClientRequest(WebClientRequestException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof ReadTimeoutException || cause instanceof TimeoutException) { + return pd(HttpStatus.GATEWAY_TIMEOUT, TITLE_TIMEOUT, DETAIL_TIMEOUT); + } + return pd(HttpStatus.BAD_GATEWAY, TITLE_UPSTREAM, ex.getMessage()); + } + + @ExceptionHandler(WebClientResponseException.class) + public ProblemDetail handleUpstream(WebClientResponseException ex) { + if (ex.getStatusCode().is5xxServerError()) { + return pd(HttpStatus.BAD_GATEWAY, TITLE_UPSTREAM, + "Error from product service: " + ex.getStatusCode().value()); + } + return pd(HttpStatus.INTERNAL_SERVER_ERROR, TITLE_INTERNAL, ex.getMessage()); + } + + @ExceptionHandler(Exception.class) + public ProblemDetail handleGeneric(Exception ex) { + return pd(HttpStatus.INTERNAL_SERVER_ERROR, TITLE_INTERNAL, ex.getMessage()); + } + + private static ProblemDetail pd(HttpStatus status, String title, String detail) { + ProblemDetail p = ProblemDetail.forStatus(status); + p.setTitle(title); + p.setDetail(detail); + return p; + } +} diff --git a/similar-products/src/main/java/com/example/similarproducts/mapper/ProductDetailMapper.java b/similar-products/src/main/java/com/example/similarproducts/mapper/ProductDetailMapper.java new file mode 100644 index 00000000..3dea8966 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/mapper/ProductDetailMapper.java @@ -0,0 +1,12 @@ +package com.example.similarproducts.mapper; + +import com.example.similarproducts.controller.dto.ProductDetailDTO; +import com.example.similarproducts.model.ProductDetail; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface ProductDetailMapper { + + ProductDetailDTO toDTO(ProductDetail productDetail); + +} diff --git a/similar-products/src/main/java/com/example/similarproducts/model/ProductDetail.java b/similar-products/src/main/java/com/example/similarproducts/model/ProductDetail.java new file mode 100644 index 00000000..c388da39 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/model/ProductDetail.java @@ -0,0 +1,12 @@ +package com.example.similarproducts.model; + +import lombok.Data; + +@Data +public class ProductDetail { + + private String id; + private String name; + private Double price; + private Boolean availability; +} diff --git a/similar-products/src/main/java/com/example/similarproducts/service/ProductService.java b/similar-products/src/main/java/com/example/similarproducts/service/ProductService.java new file mode 100644 index 00000000..dbdcbbe9 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/service/ProductService.java @@ -0,0 +1,11 @@ +package com.example.similarproducts.service; + +import com.example.similarproducts.controller.dto.ProductDetailDTO; +import java.util.List; +import reactor.core.publisher.Mono; + +public interface ProductService { + + Mono> getSimilarProducts(String productId); + +} diff --git a/similar-products/src/main/java/com/example/similarproducts/service/impl/ProductServiceImpl.java b/similar-products/src/main/java/com/example/similarproducts/service/impl/ProductServiceImpl.java new file mode 100644 index 00000000..ce4f3631 --- /dev/null +++ b/similar-products/src/main/java/com/example/similarproducts/service/impl/ProductServiceImpl.java @@ -0,0 +1,31 @@ +package com.example.similarproducts.service.impl; + +import com.example.similarproducts.client.ProductClient; +import com.example.similarproducts.controller.dto.ProductDetailDTO; +import com.example.similarproducts.mapper.ProductDetailMapper; +import com.example.similarproducts.service.ProductService; +import io.github.resilience4j.timelimiter.annotation.TimeLimiter; +import java.util.LinkedHashSet; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +@RequiredArgsConstructor +public class ProductServiceImpl implements ProductService { + + private final ProductClient client; + private final ProductDetailMapper mapper; + + @Override + @TimeLimiter(name = "products") + public Mono> getSimilarProducts(String productId) { + return client.getSimilarIds(productId) + .map(ids -> List.copyOf(new LinkedHashSet<>(ids))) + .flatMapMany(client::getProductsInOrder) + .map(mapper::toDTO) + .collectList(); + } + +} diff --git a/similar-products/src/main/resources/application.yml b/similar-products/src/main/resources/application.yml new file mode 100644 index 00000000..e8698970 --- /dev/null +++ b/similar-products/src/main/resources/application.yml @@ -0,0 +1,35 @@ +server: + port: 5000 + +clients: + products: + base-url: http://localhost:3001 + connect-timeout-ms: 4000 + read-timeout-ms: 15000 + product: /product/{id} + similar-ids: /product/{id}/similarids + +resilience4j: + circuitbreaker: + instances: + products: + slidingWindowSize: 20 + failureRateThreshold: 50 + waitDurationInOpenState: 10s + registerHealthIndicator: true + retry: + instances: + products: + maxAttempts: 2 + waitDuration: 50ms + ignoreExceptions: + - com.example.similarproducts.exception.NotFoundException + timelimiter: + instances: + products: + timeoutDuration: 6s + +logging: + level: + reactor.netty.http.client: DEBUG + reactor.netty.transport: DEBUG \ No newline at end of file diff --git a/similar-products/src/test/java/com/example/similarproducts/controller/ProductControllerIntegrationTest.java b/similar-products/src/test/java/com/example/similarproducts/controller/ProductControllerIntegrationTest.java new file mode 100644 index 00000000..2e7022e4 --- /dev/null +++ b/similar-products/src/test/java/com/example/similarproducts/controller/ProductControllerIntegrationTest.java @@ -0,0 +1,83 @@ +package com.example.similarproducts.controller; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import com.example.similarproducts.SimilarProductApplication; +import java.io.IOException; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.reactive.server.WebTestClient; + +@SpringBootTest( + classes = SimilarProductApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "clients.products.base-url=http://localhost:9999", + "clients.products.connect-timeout-ms=500", + "clients.products.read-timeout-ms=1000", + "clients.products.product=/product/{id}", + "clients.products.similar-ids=/product/{id}/similarids" + } +) +class ProductControllerIntegrationTest { + + @Autowired + private WebTestClient webTestClient; + + private static MockWebServer mockWebServer; + + @BeforeAll + static void setUp() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.start(9999); + } + + @AfterAll + static void tearDown() throws IOException { + mockWebServer.shutdown(); + } + + @Test + void getSimilarProducts_returnsOkAndList() { + mockWebServer.enqueue(new MockResponse() + .setBody("[\"2\",\"3\"]") + .addHeader("Content-Type", "application/json")); + + mockWebServer.enqueue(new MockResponse() + .setBody("{\"id\":\"2\",\"name\":\"Prod2\",\"price\":20.0,\"availability\":true}") + .addHeader("Content-Type", "application/json")); + + mockWebServer.enqueue(new MockResponse() + .setBody("{\"id\":\"3\",\"name\":\"Prod3\",\"price\":30.0,\"availability\":false}") + .addHeader("Content-Type", "application/json")); + + webTestClient.get() + .uri("/product/1/similar") + .exchange() + .expectStatus().isOk() + .expectBody() + .jsonPath("$").isArray() + .jsonPath("$.length()").value(len -> { + assertThat((Integer) len).isGreaterThanOrEqualTo(1); + }) + .jsonPath("$[0].id").isEqualTo("2"); + + } + + @Test + void getSimilarProducts_returns404WhenNotFound() { + mockWebServer.enqueue(new MockResponse().setResponseCode(404)); + + webTestClient.get() + .uri("/product/999/similar") + .exchange() + .expectStatus().isNotFound() + .expectBody() + .jsonPath("title").isEqualTo("Product not found"); + } +} \ No newline at end of file diff --git a/similar-products/src/test/java/com/example/similarproducts/service/ProductServiceImplTest.java b/similar-products/src/test/java/com/example/similarproducts/service/ProductServiceImplTest.java new file mode 100644 index 00000000..cb60ff5b --- /dev/null +++ b/similar-products/src/test/java/com/example/similarproducts/service/ProductServiceImplTest.java @@ -0,0 +1,103 @@ +package com.example.similarproducts.service; + +import static org.mockito.Mockito.when; + +import com.example.similarproducts.client.ProductClient; +import com.example.similarproducts.controller.dto.ProductDetailDTO; +import com.example.similarproducts.mapper.ProductDetailMapper; +import com.example.similarproducts.model.ProductDetail; +import com.example.similarproducts.service.impl.ProductServiceImpl; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +@ExtendWith(MockitoExtension.class) +class ProductServiceImplTest { + + @Mock + private ProductClient client; + + @Mock + private ProductDetailMapper mapper; + + private ProductService service; + + @BeforeEach + void setUp() { + service = new ProductServiceImpl(client, mapper); + } + + @Test + void getSimilarProducts_returnsDetails() { + List ids = List.of("2", "3"); + + ProductDetail detail1 = new ProductDetail(); + detail1.setId("2"); + detail1.setName("Test Product 2"); + detail1.setPrice(20.0); + detail1.setAvailability(true); + + ProductDetail detail2 = new ProductDetail(); + detail2.setId("3"); + detail2.setName("Test Product 3"); + detail2.setPrice(30.0); + detail2.setAvailability(false); + + ProductDetailDTO dto1 = new ProductDetailDTO("2", "Test Product 2", 20.0, true); + ProductDetailDTO dto2 = new ProductDetailDTO("3", "Test Product 3", 30.0, false); + + when(client.getSimilarIds("1")).thenReturn(Mono.just(ids)); + when(client.getProductsInOrder(ids)).thenReturn(Flux.just(detail1, detail2)); + when(mapper.toDTO(detail1)).thenReturn(dto1); + when(mapper.toDTO(detail2)).thenReturn(dto2); + + StepVerifier.create(service.getSimilarProducts("1")) + .expectNext(List.of(dto1, dto2)) + .verifyComplete(); + } + + @Test + void getSimilarProducts_emptyWhenNoSimilarIds() { + when(client.getSimilarIds("99")).thenReturn(Mono.just(List.of())); + when(client.getProductsInOrder(List.of())).thenReturn(Flux.empty()); + + StepVerifier.create(service.getSimilarProducts("99")) + .expectNext(List.of()) + .verifyComplete(); + } + + @Test + void getSimilarProducts_removesDuplicatesPreservingOrder() { + List idsWithDupes = List.of("2", "3", "2"); + + ProductDetail detail1a = new ProductDetail(); + detail1a.setId("2"); + detail1a.setName("P2"); + detail1a.setPrice(20.0); + detail1a.setAvailability(true); + + ProductDetail detail2 = new ProductDetail(); + detail2.setId("3"); + detail2.setName("P3"); + detail2.setPrice(30.0); + detail2.setAvailability(false); + + when(client.getSimilarIds("1")).thenReturn(Mono.just(idsWithDupes)); + when(client.getProductsInOrder(List.of("2", "3"))).thenReturn(Flux.just(detail1a, detail2)); + + ProductDetailDTO dto1 = new ProductDetailDTO("2", "P2", 20.0, true); + ProductDetailDTO dto2 = new ProductDetailDTO("3", "P3", 30.0, false); + when(mapper.toDTO(detail1a)).thenReturn(dto1); + when(mapper.toDTO(detail2)).thenReturn(dto2); + + StepVerifier.create(service.getSimilarProducts("1")) + .expectNext(List.of(dto1, dto2)) + .verifyComplete(); + } +}