diff --git a/similar-products/.gitignore b/similar-products/.gitignore new file mode 100644 index 00000000..fc12ab87 --- /dev/null +++ b/similar-products/.gitignore @@ -0,0 +1,336 @@ +# Created by https://www.gitignore.io/api/java,linux,macos,sonar,gradle,windows,eclipse,sonarqube,sublimetext,intellij+all,visualstudiocode +# Edit at https://www.gitignore.io/?templates=java,linux,macos,sonar,gradle,windows,eclipse,sonarqube,sublimetext,intellij+all,visualstudiocode + +### Eclipse ### +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet + +### Eclipse Patch ### +# Eclipse Core +.project + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Annotation Processing +.apt_generated + +.sts4-cache/ + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignores the whole .idea folder and all .iml files +# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 + +.idea/ + +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Sonar ### +#Sonar generated dir +/.sonar/ + +### SonarQube ### +# SonarQube ignore files. +# +# https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner +# Sonar Scanner working directories +.sonar/ +.scannerwork/ + +# http://www.sonarlint.org/commandline/ +# SonarLint working directories, configuration files (including credentials) +.sonarlint/ + +### SublimeText ### +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Gradle ### +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +# End of https://www.gitignore.io/api/java,linux,macos,sonar,gradle,windows,eclipse,sonarqube,sublimetext,intellij+all,visualstudiocode + +# HPROF +# ----- +*.hprof + diff --git a/similar-products/Dockerfile b/similar-products/Dockerfile new file mode 100644 index 00000000..ed8485cd --- /dev/null +++ b/similar-products/Dockerfile @@ -0,0 +1,36 @@ +# Use the official Gradle image as the build environment. +FROM gradle:7.6.2-jdk17 AS build + +# Set the working directory +WORKDIR /workspace/app + +# Set the default value for CLIENT_URL +ENV CLIENT_URL=http://host.docker.internal:3001/product/ + +# Copy the gradle configuration files first to leverage Docker cache +COPY gradlew . +COPY gradle gradle +COPY build.gradle . +COPY settings.gradle . + +# Download all required dependencies into one layer +RUN ./gradlew dependencies + +# Copy source code and build our application +COPY src src +RUN ./gradlew bootJar + +# Use the official OpenJDK base image +FROM openjdk:17 + +# Set the working directory +WORKDIR /app + +# Copy the jar from the build stage +COPY --from=build /workspace/app/build/libs/*.jar app.jar + +# Specify the entrypoint +ENTRYPOINT ["java", "-jar", "app.jar"] + +# Expose the port your app runs on +EXPOSE 5000 diff --git a/similar-products/HELP.md b/similar-products/HELP.md new file mode 100644 index 00000000..4d21f71e --- /dev/null +++ b/similar-products/HELP.md @@ -0,0 +1,9 @@ +# Read Me First +Steps to test: +``` +docker build -t similar-products:latest . +``` + +``` +docker run -e CLIENT_URL=http://host.docker.internal:3001/product/ -p 5000:5000 similar-products:latest +``` diff --git a/similar-products/build.gradle b/similar-products/build.gradle new file mode 100644 index 00000000..d5dfe698 --- /dev/null +++ b/similar-products/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' +} + +group = 'com.anycompany' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('springCloudVersion', "2022.0.4") +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + implementation 'org.mapstruct:mapstruct:1.5.5.Final' + implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.0.3' + implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j:3.0.3' + + annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0' + +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/similar-products/gradle/wrapper/gradle-wrapper.jar b/similar-products/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/similar-products/gradle/wrapper/gradle-wrapper.jar differ diff --git a/similar-products/gradle/wrapper/gradle-wrapper.properties b/similar-products/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9f4197d5 --- /dev/null +++ b/similar-products/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/similar-products/gradlew b/similar-products/gradlew new file mode 100644 index 00000000..fcb6fca1 --- /dev/null +++ b/similar-products/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/similar-products/gradlew.bat b/similar-products/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/similar-products/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/similar-products/settings.gradle b/similar-products/settings.gradle new file mode 100644 index 00000000..83919698 --- /dev/null +++ b/similar-products/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'similar-products' diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/SimilarProductsApplication.java b/similar-products/src/main/java/com/anycompany/similarproducts/SimilarProductsApplication.java new file mode 100644 index 00000000..6b9041eb --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/SimilarProductsApplication.java @@ -0,0 +1,31 @@ +package com.anycompany.similarproducts; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; + +import java.time.Duration; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; + +@SpringBootApplication +public class SimilarProductsApplication { + + public static void main(String[] args) { + SpringApplication.run(SimilarProductsApplication.class, args); + } + + @Bean + public Customizer defaultCustomizer() { + return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) + .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration( + Duration.ofSeconds(10)).build()) + .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()) + .build()); + } + +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/dto/ProductDto.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/dto/ProductDto.java new file mode 100644 index 00000000..268446d3 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/dto/ProductDto.java @@ -0,0 +1,20 @@ +package com.anycompany.similarproducts.adapter.rest.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ProductDto { + String id; + String name; + double price; + boolean availability; +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/ClearCacheApi.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/ClearCacheApi.java new file mode 100644 index 00000000..37ee3a48 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/ClearCacheApi.java @@ -0,0 +1,24 @@ +package com.anycompany.similarproducts.adapter.rest.in; + +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.RequiredArgsConstructor; + +@RestController +@RequestMapping("/cache/") +@RequiredArgsConstructor +@CrossOrigin("*") +public class ClearCacheApi { + + + @PostMapping("clear") + @CacheEvict(value = "detail-product-cache", allEntries = true) + public ResponseEntity clearCache() { + return ResponseEntity.ok().build(); + } +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/SimilarProductRestController.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/SimilarProductRestController.java new file mode 100644 index 00000000..8c6b0ab5 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/in/SimilarProductRestController.java @@ -0,0 +1,40 @@ +package com.anycompany.similarproducts.adapter.rest.in; + + +import com.anycompany.similarproducts.adapter.rest.dto.ProductDto; +import com.anycompany.similarproducts.adapter.rest.mapper.ProductMapper; +import com.anycompany.similarproducts.core.application.usecase.GetSimilarProductUseCase; +import com.anycompany.similarproducts.core.exception.ProductNotFoundException; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.ExceptionHandler; +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; + +import lombok.RequiredArgsConstructor; + +@RestController +@RequestMapping("/product/") +@RequiredArgsConstructor +@CrossOrigin("*") +public class SimilarProductRestController { + + private final GetSimilarProductUseCase useCase; + private final ProductMapper mapper; + + @GetMapping("{productId}/similar") + public ResponseEntity> getSimilarProduct(@PathVariable String productId) { + return ResponseEntity.ok(mapper.toDto(useCase.getSimilarProduct(productId))); + } + + @ExceptionHandler(ProductNotFoundException.class) + public ResponseEntity handleProductNotFound(ProductNotFoundException ex) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); + } +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/mapper/ProductMapper.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/mapper/ProductMapper.java new file mode 100644 index 00000000..5da4538b --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/mapper/ProductMapper.java @@ -0,0 +1,18 @@ +package com.anycompany.similarproducts.adapter.rest.mapper; + +import com.anycompany.similarproducts.adapter.rest.dto.ProductDto; +import com.anycompany.similarproducts.core.domain.Product; + +import org.mapstruct.Mapper; +import org.mapstruct.NullValueCheckStrategy; +import org.mapstruct.NullValuePropertyMappingStrategy; + +import java.util.List; + +@Mapper(componentModel = "spring", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, + nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) +public interface ProductMapper { + + List toDto(List product); + Product toModel(ProductDto productDto); +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductClient.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductClient.java new file mode 100644 index 00000000..c431d1b2 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductClient.java @@ -0,0 +1,48 @@ +package com.anycompany.similarproducts.adapter.rest.ou; + +import com.anycompany.similarproducts.adapter.rest.dto.ProductDto; +import com.anycompany.similarproducts.adapter.rest.mapper.ProductMapper; +import com.anycompany.similarproducts.core.application.port.GetProductPort; +import com.anycompany.similarproducts.core.domain.Product; +import com.anycompany.similarproducts.core.exception.ProductNotFoundException; + +import org.springframework.stereotype.Component; + +import java.util.List; + +import feign.FeignException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Component +@RequiredArgsConstructor +@Slf4j +public class ProductClient implements GetProductPort { + + private final ProductFeignClient productFeignClient; + private final ProductMapper mapper; + + @Override + public List getSimilarProductIds(String productId) { + List similarProductIds; + try { + similarProductIds = productFeignClient.getSimilarProductIds(productId); + } catch (FeignException e) { + log.info(e.getMessage()); + throw new ProductNotFoundException(); + } + return similarProductIds; + + } + + @Override + public Product getProductDetail(String productId) { + ProductDto productDto = null; + try { + productDto = productFeignClient.getProductDetail(productId); + } catch (Exception e) { + log.info(e.getMessage()); + } + return mapper.toModel(productDto); + } +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductFeignClient.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductFeignClient.java new file mode 100644 index 00000000..d7e11a5f --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/ProductFeignClient.java @@ -0,0 +1,22 @@ +package com.anycompany.similarproducts.adapter.rest.ou; + +import com.anycompany.similarproducts.adapter.rest.dto.ProductDto; +import com.anycompany.similarproducts.adapter.rest.ou.fallback.GetSimilarProductFallback; + +import org.springframework.cache.annotation.Cacheable; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import java.util.List; + +@FeignClient(name = "product-client", url = "${rest-client.product-client.url}", + fallback = GetSimilarProductFallback.class) +public interface ProductFeignClient { + @GetMapping(value = "/{productId}/similarids") + List getSimilarProductIds(@PathVariable String productId); + + @GetMapping(value = "/{productId}") + @Cacheable(cacheNames = "detail-product-cache", key = "#root.args[0]") + ProductDto getProductDetail(@PathVariable String productId); +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/fallback/GetSimilarProductFallback.java b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/fallback/GetSimilarProductFallback.java new file mode 100644 index 00000000..38446cc3 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/adapter/rest/ou/fallback/GetSimilarProductFallback.java @@ -0,0 +1,26 @@ +package com.anycompany.similarproducts.adapter.rest.ou.fallback; + +import com.anycompany.similarproducts.adapter.rest.dto.ProductDto; +import com.anycompany.similarproducts.adapter.rest.ou.ProductFeignClient; +import com.anycompany.similarproducts.core.exception.ProductNotFoundException; + +import org.springframework.stereotype.Component; + +import java.util.List; + +import lombok.extern.slf4j.Slf4j; + +@Component +@Slf4j +public class GetSimilarProductFallback implements ProductFeignClient { + @Override + public List getSimilarProductIds(String productId) { + log.info("[Fallback] Circuit breaker"); + throw new ProductNotFoundException(); + } + + @Override + public ProductDto getProductDetail(String productId) { + return null; + } +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/common/UseCase.java b/similar-products/src/main/java/com/anycompany/similarproducts/common/UseCase.java new file mode 100644 index 00000000..828c7c0d --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/common/UseCase.java @@ -0,0 +1,26 @@ +package com.anycompany.similarproducts.common; + +import org.springframework.core.annotation.AliasFor; +import org.springframework.stereotype.Component; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Component +public @interface UseCase { + + /** + * The value may indicate a suggestion for a logical component name, + * to be turned into a Spring bean in case of an autodetected component. + * @return the suggested component name, if any (or empty String otherwise) + */ + @AliasFor(annotation = Component.class) + String value() default ""; + +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/config/CacheConfig.java b/similar-products/src/main/java/com/anycompany/similarproducts/config/CacheConfig.java new file mode 100644 index 00000000..8379edfb --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/config/CacheConfig.java @@ -0,0 +1,9 @@ +package com.anycompany.similarproducts.config; + +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableCaching +public class CacheConfig { +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/config/FeignConfig.java b/similar-products/src/main/java/com/anycompany/similarproducts/config/FeignConfig.java new file mode 100644 index 00000000..0c7a551e --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/config/FeignConfig.java @@ -0,0 +1,9 @@ +package com.anycompany.similarproducts.config; + +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableFeignClients(basePackages = "com.anycompany.similarproducts.adapter.rest") +public class FeignConfig { +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/core/application/port/GetProductPort.java b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/port/GetProductPort.java new file mode 100644 index 00000000..caa6eb00 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/port/GetProductPort.java @@ -0,0 +1,11 @@ +package com.anycompany.similarproducts.core.application.port; + +import com.anycompany.similarproducts.core.domain.Product; + +import java.util.List; + +public interface GetProductPort { + List getSimilarProductIds(String productId); + + Product getProductDetail(String productId); +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/GetSimilarProductUseCase.java b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/GetSimilarProductUseCase.java new file mode 100644 index 00000000..26787ad7 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/GetSimilarProductUseCase.java @@ -0,0 +1,9 @@ +package com.anycompany.similarproducts.core.application.usecase; + +import com.anycompany.similarproducts.core.domain.Product; + +import java.util.List; + +public interface GetSimilarProductUseCase { + List getSimilarProduct(String productId); +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImpl.java b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImpl.java new file mode 100644 index 00000000..02d53593 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImpl.java @@ -0,0 +1,25 @@ +package com.anycompany.similarproducts.core.application.usecase.impl; + +import com.anycompany.similarproducts.common.UseCase; +import com.anycompany.similarproducts.core.application.port.GetProductPort; +import com.anycompany.similarproducts.core.application.usecase.GetSimilarProductUseCase; +import com.anycompany.similarproducts.core.domain.Product; + +import java.util.List; +import java.util.Objects; + +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@UseCase +public class GetSimilarProductUseCaseImpl implements GetSimilarProductUseCase { + + private final GetProductPort port; + + @Override + public List getSimilarProduct(String productId) { + return port.getSimilarProductIds(productId).stream().distinct().map(port::getProductDetail) + .filter(Objects::nonNull) + .toList(); + } +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/core/domain/Product.java b/similar-products/src/main/java/com/anycompany/similarproducts/core/domain/Product.java new file mode 100644 index 00000000..431d265b --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/core/domain/Product.java @@ -0,0 +1,13 @@ +package com.anycompany.similarproducts.core.domain; + +import lombok.Builder; +import lombok.Value; + +@Value +@Builder +public class Product { + String id; + String name; + double price; + boolean availability; +} diff --git a/similar-products/src/main/java/com/anycompany/similarproducts/core/exception/ProductNotFoundException.java b/similar-products/src/main/java/com/anycompany/similarproducts/core/exception/ProductNotFoundException.java new file mode 100644 index 00000000..a5506194 --- /dev/null +++ b/similar-products/src/main/java/com/anycompany/similarproducts/core/exception/ProductNotFoundException.java @@ -0,0 +1,7 @@ +package com.anycompany.similarproducts.core.exception; + +public class ProductNotFoundException extends RuntimeException { + public ProductNotFoundException() { + super("Product Not found"); + } +} diff --git a/similar-products/src/main/resources/application.yml b/similar-products/src/main/resources/application.yml new file mode 100644 index 00000000..bd65a583 --- /dev/null +++ b/similar-products/src/main/resources/application.yml @@ -0,0 +1,23 @@ +server: + port: "${SERVER_PORT:5000}" + +spring: + cloud: + openfeign: + client: + config: + default: + connectTimeout: 1000 + readTimeout: 10000 + loggerLevel: BASIC + circuitbreaker: + enabled: true + alphanumeric-ids: + enabled: true + + +logging.level.com.anycompany.similarproducts.adapter.rest.out.ProductFeignClient: DEBUG + +rest-client: + product-client: + url: "${CLIENT_URL:http://localhost:3001/product/}" diff --git a/similar-products/src/test/java/com/anycompany/similarproducts/SimilarProductsApplicationTests.java b/similar-products/src/test/java/com/anycompany/similarproducts/SimilarProductsApplicationTests.java new file mode 100644 index 00000000..64b9c2aa --- /dev/null +++ b/similar-products/src/test/java/com/anycompany/similarproducts/SimilarProductsApplicationTests.java @@ -0,0 +1,13 @@ +package com.anycompany.similarproducts; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SimilarProductsApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/similar-products/src/test/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImplTest.java b/similar-products/src/test/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImplTest.java new file mode 100644 index 00000000..99c650fb --- /dev/null +++ b/similar-products/src/test/java/com/anycompany/similarproducts/core/application/usecase/impl/GetSimilarProductUseCaseImplTest.java @@ -0,0 +1,81 @@ +package com.anycompany.similarproducts.core.application.usecase.impl; + +import com.anycompany.similarproducts.core.application.port.GetProductPort; +import com.anycompany.similarproducts.core.domain.Product; +import com.anycompany.similarproducts.core.exception.ProductNotFoundException; + +import org.junit.jupiter.api.Assertions; +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.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +@ExtendWith(MockitoExtension.class) +class GetSimilarProductUseCaseImplTest { + + @Mock + private GetProductPort port; + + + private GetSimilarProductUseCaseImpl useCase; + + @BeforeEach + public void setUp(){ + MockitoAnnotations.openMocks(this); + useCase = new GetSimilarProductUseCaseImpl(port); + } + + @Test + void getSimilarProduct_happy_path() { + String productId = "1"; + when(port.getSimilarProductIds(productId)).thenReturn(List.of("1", "2", "3")); + + when(port.getProductDetail("1")).thenReturn(Product.builder().id("1").build()); + when(port.getProductDetail("2")).thenReturn(Product.builder().id("2").build()); + when(port.getProductDetail("3")).thenReturn(Product.builder().id("3").build()); + + List response = useCase.getSimilarProduct(productId); + + + verify(port).getProductDetail("1"); + verify(port).getProductDetail("2"); + verify(port).getProductDetail("3"); + Assertions.assertEquals(3, response.size()); + Assertions.assertEquals("1", response.get(0).getId()); + Assertions.assertEquals("2", response.get(1).getId()); + Assertions.assertEquals("3", response.get(2).getId()); + } + + @Test + void getSimilarProduct_one_detail_nulled() { + String productId = "1"; + when(port.getSimilarProductIds(productId)).thenReturn(List.of("1", "2", "3")); + + when(port.getProductDetail("1")).thenReturn(Product.builder().id("1").build()); + when(port.getProductDetail("2")).thenReturn(Product.builder().id("2").build()); + when(port.getProductDetail("3")).thenReturn(null); + + List response = useCase.getSimilarProduct(productId); + Assertions.assertEquals(2, response.size()); + } + + @Test + void getSimilarProduct_ProductNotFound() { + String productId = "1"; + when(port.getSimilarProductIds(productId)).thenThrow(new ProductNotFoundException()); + + assertThrows(ProductNotFoundException.class, () -> { + useCase.getSimilarProduct(productId); + }); + } + +}