diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..667aaef0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c595b009 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/README.md b/README.md index 5e58ae2a..daf9a424 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,11 @@ The focus of this test is not just functional correctness, but demonstrating cle * You must integrate with three distinct data resources to enforce the architectural pattern: - 1. `/latest?base=IDR` (The latest rates relative to IDR) + 1. `/latest?base=IDR` (The latest rates relative to IDR) - 2. **Historical Data:** Query a specific, small time series (e.g., `/2024-01-01..2024-01-05?from=IDR&to=USD`). **Note:** *Use the date range provided in this example unless a different range is communicated separately.* + 2. **Historical Data:** Query a specific, small time series (e.g., `/2024-01-01..2024-01-05?from=IDR&to=USD`). **Note:** *Use the date range provided in this example unless a different range is communicated separately.* - 3. `/currencies` (The list of all supported currency symbols) + 3. `/currencies` (The list of all supported currency symbols) ### 2. Internal API Endpoint @@ -38,10 +38,10 @@ Where `{resourceType}` can be one of the three strings: `latest_idr_rates`, `his **The Spread Factor Must Be Unique :** - 1. **Input:** Your GitHub username (e.g., `johndoe47`). - 2. **Calculation:** Calculate the sum of the Unicode (ASCII) values of all characters in your lowercase GitHub username string. - 3. **Spread Factor Derivation:** `Spread Factor = (Sum of Unicode Values % 1000) / 100000.0` - *(This will yield a unique factor between 0.00000 and 0.00999, ensuring a personalized result.)* + 1. **Input:** Your GitHub username (e.g., `johndoe47`). + 2. **Calculation:** Calculate the sum of the Unicode (ASCII) values of all characters in your lowercase GitHub username string. + 3. **Spread Factor Derivation:** `Spread Factor = (Sum of Unicode Values % 1000) / 100000.0` + *(This will yield a unique factor between 0.00000 and 0.00999, ensuring a personalized result.)* **Final Formula:** `USD_BuySpread_IDR = (1 / Rate_USD) * (1 + Spread Factor)` (where `Rate_USD` is the value from the API when `base=IDR`). @@ -113,11 +113,11 @@ A clear `README.md` is mandatory. It must include: This section should contain a brief, but detailed, explanation answering the following questions: - 1. **Polymorphism Justification:** Explain *why* the Strategy Pattern was used over a simpler conditional block in the service layer for handling the multi-resource endpoint. Discuss the benefits in terms of **extensibility** and **maintainability**. + 1. **Polymorphism Justification:** Explain *why* the Strategy Pattern was used over a simpler conditional block in the service layer for handling the multi-resource endpoint. Discuss the benefits in terms of **extensibility** and **maintainability**. - 2. **Client Factory:** Explain the specific role and benefit of using a **`FactoryBean`** to construct the external API client. Why is this preferable to defining the client using a standard `@Bean` method in this scenario? + 2. **Client Factory:** Explain the specific role and benefit of using a **`FactoryBean`** to construct the external API client. Why is this preferable to defining the client using a standard `@Bean` method in this scenario? - 3. **Startup Runner Choice:** Justify the choice of using an `ApplicationRunner` (or `CommandLineRunner`) for the initial data ingestion over a simpler `@PostConstruct` method. + 3. **Startup Runner Choice:** Justify the choice of using an `ApplicationRunner` (or `CommandLineRunner`) for the initial data ingestion over a simpler `@PostConstruct` method. ## IV. Submission & Review Process @@ -136,4 +136,4 @@ A clear `README.md` is mandatory. It must include: * **Code Review Readiness:** The code should be well-structured and ready for immediate review. -Good luck! +Good luck! \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/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/pom.xml b/pom.xml new file mode 100644 index 00000000..87f4f318 --- /dev/null +++ b/pom.xml @@ -0,0 +1,161 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + com.allobank + backendtest + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webclient + + + org.springframework.boot + spring-boot-starter-webmvc + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-actuator-test + test + + + org.springframework.boot + spring-boot-starter-validation-test + test + + + org.springframework.boot + spring-boot-starter-webclient-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-test + test + + + com.squareup.okhttp3 + mockwebserver + 4.12.0 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.springframework.boot + spring-boot-configuration-processor + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + diff --git a/src/main/java/com/allobank/backendtest/BackendtestApplication.java b/src/main/java/com/allobank/backendtest/BackendtestApplication.java new file mode 100644 index 00000000..c87d20ca --- /dev/null +++ b/src/main/java/com/allobank/backendtest/BackendtestApplication.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BackendtestApplication { + public static void main(String[] args) { + SpringApplication.run(BackendtestApplication.class, args); + } +} diff --git a/src/main/java/com/allobank/backendtest/config/JacksonConfig.java b/src/main/java/com/allobank/backendtest/config/JacksonConfig.java new file mode 100644 index 00000000..c5327258 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/config/JacksonConfig.java @@ -0,0 +1,20 @@ +package com.allobank.backendtest.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +@Configuration +public class JacksonConfig { + @Bean + @Primary + public ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } +} diff --git a/src/main/java/com/allobank/backendtest/config/WebClientFactoryBean.java b/src/main/java/com/allobank/backendtest/config/WebClientFactoryBean.java new file mode 100644 index 00000000..a0a8cfb3 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/config/WebClientFactoryBean.java @@ -0,0 +1,43 @@ +package com.allobank.backendtest.config; + +import io.netty.channel.ChannelOption; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import java.time.Duration; + +@Component +public class WebClientFactoryBean implements FactoryBean { + @Value("${frankfurter.api.base-url}") + private String baseUrl; + + @Value("${frankfurter.api.timeout-ms}") + private int timeoutMs; + + @Override + public WebClient getObject() { + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMs) + .responseTimeout(Duration.ofMillis(timeoutMs)); + + return WebClient.builder() + .baseUrl(baseUrl) + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .defaultHeader("Accept", "application/json") + .build(); + } + + @Override + public Class getObjectType() { + return WebClient.class; + } + + @Override + public boolean isSingleton() { + return true; + } +} diff --git a/src/main/java/com/allobank/backendtest/constant/ApiConstants.java b/src/main/java/com/allobank/backendtest/constant/ApiConstants.java new file mode 100644 index 00000000..552efdea --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/ApiConstants.java @@ -0,0 +1,15 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ApiConstants { + public static final String LATEST_PATH = "/latest"; + public static final String CURRENCIES_PATH = "/currencies"; + public static final String FROM_PARAM = "from"; + public static final String TO_PARAM = "to"; + public static final String BASE_PARAM = "base"; + public static final String SYMBOLS_PARAM = "symbols"; + public static final String AMOUNT_PARAM = "amount"; +} diff --git a/src/main/java/com/allobank/backendtest/constant/ControllerConstants.java b/src/main/java/com/allobank/backendtest/constant/ControllerConstants.java new file mode 100644 index 00000000..7fddd4f7 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/ControllerConstants.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ControllerConstants { + public static final String FINANCE_BASE_URL = "/api/finance"; + public static final String DATA_ENDPOINT = "/data/{resourceType}"; + public static final String RESOURCE_TYPE_VAR = "resourceType"; +} diff --git a/src/main/java/com/allobank/backendtest/constant/CurrencyConstants.java b/src/main/java/com/allobank/backendtest/constant/CurrencyConstants.java new file mode 100644 index 00000000..08308e72 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/CurrencyConstants.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class CurrencyConstants { + public static final String IDR = "IDR"; + public static final String USD = "USD"; + public static final String EUR = "EUR"; +} diff --git a/src/main/java/com/allobank/backendtest/constant/HttpConstants.java b/src/main/java/com/allobank/backendtest/constant/HttpConstants.java new file mode 100644 index 00000000..250d9c23 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/HttpConstants.java @@ -0,0 +1,10 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class HttpConstants { + public static final String HEADER_ACCEPT = "Accept"; + public static final String MEDIA_TYPE_JSON = "application/json"; +} diff --git a/src/main/java/com/allobank/backendtest/constant/MessageConstants.java b/src/main/java/com/allobank/backendtest/constant/MessageConstants.java new file mode 100644 index 00000000..cbdb4e52 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/MessageConstants.java @@ -0,0 +1,26 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class MessageConstants { + public static final String ERROR_FETCH_LATEST = "Failed to fetch latest IDR rates"; + public static final String ERROR_FETCH_HISTORICAL = "Failed to fetch historical IDR/USD data"; + public static final String ERROR_FETCH_CURRENCIES = "Failed to fetch supported currencies"; + public static final String ERROR_EXTERNAL_API = "External API error"; + public static final String ERROR_RESOURCE_NOT_FOUND = "Unknown resource type: "; + public static final String ERROR_DATA_NOT_READY = "Data store has not been initialized. Please try again later."; + public static final String ERROR_NULL_RESPONSE = "Received null or empty response from Frankfurter API"; + + public static final String ERR_TYPE_NOT_FOUND = "Not Found"; + public static final String ERR_TYPE_SERVICE_UNAVAILABLE = "Service Unavailable"; + public static final String ERR_TYPE_VALIDATION = "Validation Error"; + public static final String ERR_TYPE_BAD_REQUEST = "Bad Request"; + public static final String ERR_TYPE_INTERNAL_SERVER = "Internal Server Error"; + + public static final String LOG_FETCH_START = "Starting data fetch for resource: {}"; + public static final String LOG_FETCH_SUCCESS = "Successfully loaded data for: {}"; + public static final String LOG_APP_STARTUP_LOADING = "Loading data from all strategies"; + public static final String LOG_STRATEGY_REGISTERED = "Registered data fetching strategy: {} for resource: {}"; +} diff --git a/src/main/java/com/allobank/backendtest/constant/ResourceConstants.java b/src/main/java/com/allobank/backendtest/constant/ResourceConstants.java new file mode 100644 index 00000000..64186d9f --- /dev/null +++ b/src/main/java/com/allobank/backendtest/constant/ResourceConstants.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ResourceConstants { + public static final String LATEST_IDR_RATES = "latest_idr_rates"; + public static final String HISTORICAL_IDR_USD = "historical_idr_usd"; + public static final String SUPPORTED_CURRENCIES = "supported_currencies"; +} diff --git a/src/main/java/com/allobank/backendtest/controller/FinanceDataController.java b/src/main/java/com/allobank/backendtest/controller/FinanceDataController.java new file mode 100644 index 00000000..b18c7baa --- /dev/null +++ b/src/main/java/com/allobank/backendtest/controller/FinanceDataController.java @@ -0,0 +1,24 @@ +package com.allobank.backendtest.controller; + +import com.allobank.backendtest.constant.ControllerConstants; +import com.allobank.backendtest.model.ResourceResult; +import com.allobank.backendtest.service.FinanceDataService; +import jakarta.validation.constraints.NotBlank; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +@Validated +@RestController +@RequiredArgsConstructor +@RequestMapping(ControllerConstants.FINANCE_BASE_URL) +public class FinanceDataController { + private final FinanceDataService financeDataService; + + @GetMapping(ControllerConstants.DATA_ENDPOINT) + public ResponseEntity getData(@PathVariable(ControllerConstants.RESOURCE_TYPE_VAR) @NotBlank String resourceType) { + Object data = financeDataService.getData(resourceType); + return ResponseEntity.ok(new ResourceResult(resourceType, data)); + } +} diff --git a/src/main/java/com/allobank/backendtest/exception/DataNotReadyException.java b/src/main/java/com/allobank/backendtest/exception/DataNotReadyException.java new file mode 100644 index 00000000..8fb32237 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/exception/DataNotReadyException.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE) +public class DataNotReadyException extends RuntimeException { + public DataNotReadyException(String message) { + super(message); + } +} diff --git a/src/main/java/com/allobank/backendtest/exception/ExternalApiException.java b/src/main/java/com/allobank/backendtest/exception/ExternalApiException.java new file mode 100644 index 00000000..9ea88e2a --- /dev/null +++ b/src/main/java/com/allobank/backendtest/exception/ExternalApiException.java @@ -0,0 +1,15 @@ +package com.allobank.backendtest.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.BAD_GATEWAY) +public class ExternalApiException extends RuntimeException { + public ExternalApiException(String message) { + super(message); + } + + public ExternalApiException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/allobank/backendtest/exception/GlobalExceptionHandler.java b/src/main/java/com/allobank/backendtest/exception/GlobalExceptionHandler.java new file mode 100644 index 00000000..769e51a7 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/exception/GlobalExceptionHandler.java @@ -0,0 +1,69 @@ +package com.allobank.backendtest.exception; + +import com.allobank.backendtest.constant.MessageConstants; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(ExternalApiException.class) + public ResponseEntity> handleExternalApiException(ExternalApiException ex) { + log.error("{}: {}", MessageConstants.ERROR_EXTERNAL_API, ex.getMessage(), ex); + return buildErrorResponse(HttpStatus.BAD_GATEWAY, MessageConstants.ERROR_EXTERNAL_API, ex.getMessage()); + } + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity> handleResourceNotFound(ResourceNotFoundException ex) { + log.warn("Resource not found: {}", ex.getMessage()); + return buildErrorResponse(HttpStatus.NOT_FOUND, MessageConstants.ERR_TYPE_NOT_FOUND, ex.getMessage()); + } + + @ExceptionHandler(DataNotReadyException.class) + public ResponseEntity> handleDataNotReady(DataNotReadyException ex) { + log.warn("Data not ready: {}", ex.getMessage()); + return buildErrorResponse(HttpStatus.SERVICE_UNAVAILABLE, MessageConstants.ERR_TYPE_SERVICE_UNAVAILABLE, ex.getMessage()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions(MethodArgumentNotValidException ex) { + String details = ex.getBindingResult().getFieldErrors().stream() + .map(FieldError::getField) + .collect(Collectors.joining(", ", "Invalid fields: ", "")); + log.warn("Validation failed: {}", details); + return buildErrorResponse(HttpStatus.BAD_REQUEST, MessageConstants.ERR_TYPE_VALIDATION, details); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { + log.warn("Bad request: {}", ex.getMessage()); + return buildErrorResponse(HttpStatus.BAD_REQUEST, MessageConstants.ERR_TYPE_BAD_REQUEST, ex.getMessage()); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGenericException(Exception ex) { + log.error("Unexpected error: {}", ex.getMessage(), ex); + return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, MessageConstants.ERR_TYPE_INTERNAL_SERVER, ex.getMessage()); + } + + private ResponseEntity> buildErrorResponse(HttpStatus status, String error, String message) { + Map body = new LinkedHashMap<>(); + + body.put("timestamp", Instant.now().toString()); + body.put("status", status.value()); + body.put("error", error); + body.put("message", message); + + return ResponseEntity.status(status).body(body); + } +} diff --git a/src/main/java/com/allobank/backendtest/exception/ResourceNotFoundException.java b/src/main/java/com/allobank/backendtest/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..8f50bd35 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/exception/ResourceNotFoundException.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/com/allobank/backendtest/model/HistoricalRatesResponse.java b/src/main/java/com/allobank/backendtest/model/HistoricalRatesResponse.java new file mode 100644 index 00000000..7a12662f --- /dev/null +++ b/src/main/java/com/allobank/backendtest/model/HistoricalRatesResponse.java @@ -0,0 +1,14 @@ +package com.allobank.backendtest.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Map; + +public record HistoricalRatesResponse( + double amount, + String base, + @JsonProperty("start_date") String startDate, + @JsonProperty("end_date") String endDate, + Map> rates +) { +} diff --git a/src/main/java/com/allobank/backendtest/model/LatestRatesResponse.java b/src/main/java/com/allobank/backendtest/model/LatestRatesResponse.java new file mode 100644 index 00000000..a8ee352b --- /dev/null +++ b/src/main/java/com/allobank/backendtest/model/LatestRatesResponse.java @@ -0,0 +1,11 @@ +package com.allobank.backendtest.model; + +import java.util.Map; + +public record LatestRatesResponse( + double amount, + String base, + String date, + Map rates +) { +} diff --git a/src/main/java/com/allobank/backendtest/model/ResourceResult.java b/src/main/java/com/allobank/backendtest/model/ResourceResult.java new file mode 100644 index 00000000..6feb8ced --- /dev/null +++ b/src/main/java/com/allobank/backendtest/model/ResourceResult.java @@ -0,0 +1,10 @@ +package com.allobank.backendtest.model; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record ResourceResult( + @NotBlank String resourceType, + @NotNull Object data +) { +} diff --git a/src/main/java/com/allobank/backendtest/runner/DataLoaderRunner.java b/src/main/java/com/allobank/backendtest/runner/DataLoaderRunner.java new file mode 100644 index 00000000..dc6e0a77 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/runner/DataLoaderRunner.java @@ -0,0 +1,26 @@ +package com.allobank.backendtest.runner; + +import com.allobank.backendtest.service.FinanceDataService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class DataLoaderRunner implements ApplicationRunner { + private final FinanceDataService financeDataService; + + public DataLoaderRunner(FinanceDataService financeDataService) { + this.financeDataService = financeDataService; + } + + @Override + public void run(ApplicationArguments args) { + try { + financeDataService.loadAllData(); + } catch (Exception e) { + throw new RuntimeException("Unable to load required finance data", e); + } + } +} diff --git a/src/main/java/com/allobank/backendtest/service/FinanceDataService.java b/src/main/java/com/allobank/backendtest/service/FinanceDataService.java new file mode 100644 index 00000000..43452597 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/service/FinanceDataService.java @@ -0,0 +1,59 @@ +package com.allobank.backendtest.service; + +import com.allobank.backendtest.constant.MessageConstants; +import com.allobank.backendtest.exception.DataNotReadyException; +import com.allobank.backendtest.exception.ResourceNotFoundException; +import com.allobank.backendtest.strategy.IDRDataFetcher; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Slf4j +@Service +public class FinanceDataService { + private final Map strategyMap; + private volatile Map dataStore; + + public FinanceDataService(List fetchers) { + this.strategyMap = fetchers.stream().collect(Collectors.toUnmodifiableMap(IDRDataFetcher::getResourceType, Function.identity())); + } + + public void loadAllData() { + log.info(MessageConstants.LOG_APP_STARTUP_LOADING); + Map data = new HashMap<>(); + + for (Map.Entry entry : strategyMap.entrySet()) { + String resourceType = entry.getKey(); + + log.info(MessageConstants.LOG_FETCH_START, resourceType); + Object result = entry.getValue().fetchData(); + + data.put(resourceType, result); + log.info(MessageConstants.LOG_FETCH_SUCCESS, resourceType); + } + + this.dataStore = Collections.unmodifiableMap(data); + } + + public Object getData(String resourceType) { + if (dataStore == null) { + throw new DataNotReadyException(MessageConstants.ERROR_DATA_NOT_READY); + } + + if (!dataStore.containsKey(resourceType)) { + throw new ResourceNotFoundException(MessageConstants.ERROR_RESOURCE_NOT_FOUND + resourceType); + } + + return dataStore.get(resourceType); + } + + public boolean isDataLoaded() { + return dataStore != null; + } +} diff --git a/src/main/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcher.java b/src/main/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcher.java new file mode 100644 index 00000000..b232988e --- /dev/null +++ b/src/main/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcher.java @@ -0,0 +1,86 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.ApiConstants; +import com.allobank.backendtest.constant.CurrencyConstants; +import com.allobank.backendtest.constant.MessageConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.allobank.backendtest.model.HistoricalRatesResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Component +public class HistoricalIdrUsdFetcher implements IDRDataFetcher { + private final WebClient webClient; + private final ObjectMapper objectMapper; + private final String startDate; + private final String endDate; + + public HistoricalIdrUsdFetcher(WebClient webClient, ObjectMapper objectMapper, @Value("${frankfurter.api.historical.start-date}") String startDate, @Value("${frankfurter.api.historical.end-date}") String endDate) { + this.webClient = webClient; + this.objectMapper = objectMapper; + this.startDate = startDate; + this.endDate = endDate; + } + + @Override + public String getResourceType() { + return ResourceConstants.HISTORICAL_IDR_USD; + } + + @Override + public Object fetchData() { + log.info(MessageConstants.LOG_FETCH_START, getResourceType()); + + String path = "/" + startDate + ".." + endDate; + String uri = UriComponentsBuilder.fromPath(path) + .queryParam(ApiConstants.FROM_PARAM, CurrencyConstants.IDR) + .queryParam(ApiConstants.TO_PARAM, CurrencyConstants.USD) + .toUriString(); + + try { + String responseBody = webClient.get() + .uri(uri) + .retrieve() + .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), + clientResponse -> clientResponse.bodyToMono(String.class) + .map(body -> new ExternalApiException( + MessageConstants.ERROR_EXTERNAL_API + " [" + clientResponse.statusCode() + "]: " + body))) + .bodyToMono(String.class) + .block(); + + if (responseBody == null || responseBody.isBlank()) { + throw new ExternalApiException(MessageConstants.ERROR_NULL_RESPONSE + " for " + getResourceType()); + } + + HistoricalRatesResponse response = objectMapper.readValue(responseBody, HistoricalRatesResponse.class); + + Map result = new LinkedHashMap<>(); + result.put("amount", response.amount()); + result.put("base", response.base()); + result.put("startDate", response.startDate()); + result.put("endDate", response.endDate()); + result.put("rates", response.rates()); + + log.info(MessageConstants.LOG_FETCH_SUCCESS, getResourceType()); + return Collections.unmodifiableMap(result); + + } catch (WebClientResponseException e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_HISTORICAL + ": HTTP " + e.getStatusCode(), e); + } catch (ExternalApiException e) { + throw e; + } catch (Exception e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_HISTORICAL + ": " + e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/allobank/backendtest/strategy/IDRDataFetcher.java b/src/main/java/com/allobank/backendtest/strategy/IDRDataFetcher.java new file mode 100644 index 00000000..e8f22f2c --- /dev/null +++ b/src/main/java/com/allobank/backendtest/strategy/IDRDataFetcher.java @@ -0,0 +1,6 @@ +package com.allobank.backendtest.strategy; + +public interface IDRDataFetcher { + String getResourceType(); + Object fetchData(); +} diff --git a/src/main/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcher.java b/src/main/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcher.java new file mode 100644 index 00000000..9a06ba62 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcher.java @@ -0,0 +1,113 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.ApiConstants; +import com.allobank.backendtest.constant.CurrencyConstants; +import com.allobank.backendtest.constant.MessageConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.allobank.backendtest.model.LatestRatesResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Component +public class LatestIdrRatesFetcher implements IDRDataFetcher { + private final WebClient webClient; + private final ObjectMapper objectMapper; + private final String githubUsername; + + @Getter + private final double spreadFactor; + + public LatestIdrRatesFetcher(WebClient webClient, ObjectMapper objectMapper, @Value("${spread.github-username}") String githubUsername) { + this.webClient = webClient; + this.objectMapper = objectMapper; + this.githubUsername = githubUsername.toLowerCase(); + this.spreadFactor = calculateSpreadFactor(this.githubUsername); + + log.info(MessageConstants.LOG_STRATEGY_REGISTERED, this.getClass().getSimpleName(), getResourceType()); + } + + @Override + public String getResourceType() { + return ResourceConstants.LATEST_IDR_RATES; + } + + @Override + public Object fetchData() { + log.info(MessageConstants.LOG_FETCH_START, getResourceType()); + + String uri = UriComponentsBuilder.fromPath(ApiConstants.LATEST_PATH) + .queryParam(ApiConstants.BASE_PARAM, CurrencyConstants.IDR) + .toUriString(); + + try { + String responseBody = webClient.get() + .uri(uri) + .retrieve() + .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), + clientResponse -> clientResponse.bodyToMono(String.class) + .map(body -> new ExternalApiException( + MessageConstants.ERROR_EXTERNAL_API + " [" + clientResponse.statusCode() + "]: " + body))) + .bodyToMono(String.class) + .block(); + + if (responseBody == null || responseBody.isBlank()) { + throw new ExternalApiException(MessageConstants.ERROR_NULL_RESPONSE + " for " + getResourceType()); + } + + LatestRatesResponse response = objectMapper.readValue(responseBody, LatestRatesResponse.class); + if (response.rates() == null) { + throw new ExternalApiException("Rates field is null in the response"); + } + + return transformResponse(response); + + } catch (WebClientResponseException e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_LATEST + ": HTTP " + e.getStatusCode(), e); + } catch (ExternalApiException e) { + throw e; + } catch (Exception e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_LATEST + ": " + e.getMessage(), e); + } + } + + private Map transformResponse(LatestRatesResponse response) { + Double rateUsd = response.rates().get(CurrencyConstants.USD); + if (rateUsd == null || rateUsd == 0.0) { + throw new ExternalApiException("USD rate not found or is zero in the API response"); + } + + double usdBuySpreadIdr = (1.0 / rateUsd) * (1.0 + spreadFactor); + + Map result = new LinkedHashMap<>(); + result.put("amount", response.amount()); + result.put("base", response.base()); + result.put("date", response.date()); + result.put("rates", response.rates()); + + result.put("githubUsername", githubUsername); + result.put("spreadFactor", spreadFactor); + result.put("USD_BuySpread_IDR", usdBuySpreadIdr); + + return Collections.unmodifiableMap(result); + } + + static double calculateSpreadFactor(String username) { + int sum = 0; + for (char c : username.toCharArray()) { + sum += c; + } + return (sum % 1000) / 100000.0; + } +} diff --git a/src/main/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcher.java b/src/main/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcher.java new file mode 100644 index 00000000..f038ce47 --- /dev/null +++ b/src/main/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcher.java @@ -0,0 +1,67 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.ApiConstants; +import com.allobank.backendtest.constant.MessageConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import java.util.Collections; +import java.util.Map; + +@Slf4j +@Component +public class SupportedCurrenciesFetcher implements IDRDataFetcher { + private final WebClient webClient; + private final ObjectMapper objectMapper; + + public SupportedCurrenciesFetcher(WebClient webClient, ObjectMapper objectMapper) { + this.webClient = webClient; + this.objectMapper = objectMapper; + log.info(MessageConstants.LOG_STRATEGY_REGISTERED, this.getClass().getSimpleName(), getResourceType()); + } + + @Override + public String getResourceType() { + return ResourceConstants.SUPPORTED_CURRENCIES; + } + + @Override + public Object fetchData() { + log.info(MessageConstants.LOG_FETCH_START, getResourceType()); + + try { + String responseBody = webClient.get() + .uri(ApiConstants.CURRENCIES_PATH) + .retrieve() + .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), + clientResponse -> clientResponse.bodyToMono(String.class) + .map(body -> new ExternalApiException( + MessageConstants.ERROR_EXTERNAL_API + " [" + clientResponse.statusCode() + "]: " + body))) + .bodyToMono(String.class) + .block(); + + if (responseBody == null || responseBody.isBlank()) { + throw new ExternalApiException(MessageConstants.ERROR_NULL_RESPONSE + " for " + getResourceType()); + } + + Map currencies = objectMapper.readValue( + responseBody, new TypeReference>() {}); + + log.info(MessageConstants.LOG_FETCH_SUCCESS, getResourceType()); + return Collections.unmodifiableMap(currencies); + + } catch (WebClientResponseException e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_CURRENCIES + ": HTTP " + e.getStatusCode(), e); + } catch (ExternalApiException e) { + throw e; + } catch (Exception e) { + throw new ExternalApiException(MessageConstants.ERROR_FETCH_CURRENCIES + ": " + e.getMessage(), e); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..3203e1b1 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,12 @@ +spring: + application: + name: backendtest +frankfurter: + api: + base-url: https://api.frankfurter.app + timeout-ms: 5000 + historical: + start-date: "2026-01-01" + end-date: "2026-01-05" +spread: + github-username: erlanggariansyah diff --git a/src/test/java/com/allobank/backendtest/BackendtestApplicationTests.java b/src/test/java/com/allobank/backendtest/BackendtestApplicationTests.java new file mode 100644 index 00000000..28b690b3 --- /dev/null +++ b/src/test/java/com/allobank/backendtest/BackendtestApplicationTests.java @@ -0,0 +1,95 @@ +package com.allobank.backendtest; + +import com.allobank.backendtest.service.FinanceDataService; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +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.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class BackendtestApplicationTests { + + static MockWebServer mockWebServer; + + // --- Mock Data --- + + private static final String LATEST_JSON = """ + {"amount":1.0,"base":"IDR","date":"2026-04-17","rates":{"USD":0.000058,"EUR":0.000049}} + """; + + private static final String HISTORICAL_JSON = """ + {"amount":1.0,"base":"IDR","start_date":"2023-12-29","end_date":"2024-01-05","rates":{"2023-12-29":{"USD":0.000065}}} + """; + + private static final String CURRENCIES_JSON = """ + {"IDR":"Indonesian Rupiah","USD":"United States Dollar"} + """; + + // --- Lifecycle Management --- + + @BeforeAll + static void startMockServer() throws IOException { + mockWebServer = new MockWebServer(); + + mockWebServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + if (path != null) { + if (path.startsWith("/latest")) { + return jsonResponse(LATEST_JSON); + } else if (path.contains("2024-01-01")) { + return jsonResponse(HISTORICAL_JSON); + } else if (path.startsWith("/currencies")) { + return jsonResponse(CURRENCIES_JSON); + } + } + return new MockResponse().setResponseCode(404); + } + }); + + mockWebServer.start(); + } + + @AfterAll + static void shutdownMockServer() throws IOException { + if (mockWebServer != null) { + mockWebServer.shutdown(); + } + } + + @DynamicPropertySource + static void configureProperties(DynamicPropertyRegistry registry) { + // Point the Frankfurter API base URL to our local mock server + registry.add("frankfurter.api.base-url", () -> "http://localhost:" + mockWebServer.getPort()); + } + + @Autowired + private FinanceDataService financeDataService; + + // --- Tests --- + + @Test + void contextLoads() { + // Basic sanity check: did the data load correctly on startup? + assertThat(financeDataService.isDataLoaded()).isTrue(); + } + + private static MockResponse jsonResponse(String body) { + return new MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(body); + } +} diff --git a/src/test/java/com/allobank/backendtest/runner/DataLoaderRunnerIntegrationTest.java b/src/test/java/com/allobank/backendtest/runner/DataLoaderRunnerIntegrationTest.java new file mode 100644 index 00000000..56a9e1a3 --- /dev/null +++ b/src/test/java/com/allobank/backendtest/runner/DataLoaderRunnerIntegrationTest.java @@ -0,0 +1,137 @@ +package com.allobank.backendtest.runner; + +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.service.FinanceDataService; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class DataLoaderRunnerIntegrationTest { + static MockWebServer mockWebServer; + + private static final String LATEST_JSON = """ + { + "amount": 1.0, + "base": "IDR", + "date": "2026-04-17", + "rates": { + "USD": 0.000058, + "EUR": 0.000049 + } + } + """; + + private static final String HISTORICAL_JSON = """ + { + "amount": 1.0, + "base": "IDR", + "start_date": "2023-12-29", + "end_date": "2024-01-05", + "rates": { + "2023-12-29": { "USD": 0.000065 }, + "2024-01-02": { "USD": 0.000064 } + } + } + """; + + private static final String CURRENCIES_JSON = """ + { + "IDR": "Indonesian Rupiah", + "USD": "United States Dollar" + } + """; + + @BeforeAll + static void startMockServer() throws IOException { + mockWebServer = new MockWebServer(); + + mockWebServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + if (path != null) { + if (path.startsWith("/latest")) { + return jsonResponse(LATEST_JSON); + } else if (path.contains("2024-01-01")) { + return jsonResponse(HISTORICAL_JSON); + } else if (path.startsWith("/currencies")) { + return jsonResponse(CURRENCIES_JSON); + } + } + + return new MockResponse().setResponseCode(404).setBody("Not Found"); + } + }); + + mockWebServer.start(); + } + + @AfterAll + static void shutdownMockServer() throws IOException { + if (mockWebServer != null) { + mockWebServer.shutdown(); + } + } + + @DynamicPropertySource + static void configureProperties(DynamicPropertyRegistry registry) { + registry.add("frankfurter.api.base-url", + () -> "http://localhost:" + mockWebServer.getPort()); + } + + @Autowired + private FinanceDataService financeDataService; + + @Test + @DisplayName("Data store should be initialized after application startup") + void dataStoreShouldBeInitialized() { + assertThat(financeDataService.isDataLoaded()).isTrue(); + } + + @Test + @DisplayName("Latest IDR rates should be loaded and available") + void latestIdrRatesShouldBeLoaded() { + Object data = financeDataService.getData(ResourceConstants.LATEST_IDR_RATES); + assertThat(data).isNotNull(); + } + + @Test + @DisplayName("Historical IDR/USD data should be loaded and available") + void historicalIdrUsdShouldBeLoaded() { + Object data = financeDataService.getData(ResourceConstants.HISTORICAL_IDR_USD); + assertThat(data).isNotNull(); + } + + @Test + @DisplayName("Supported currencies should be loaded and available") + void supportedCurrenciesShouldBeLoaded() { + Object data = financeDataService.getData(ResourceConstants.SUPPORTED_CURRENCIES); + assertThat(data).isNotNull(); + } + + @Test + @DisplayName("All three resource types should be present in the data store") + void allResourceTypesShouldBePresent() { + assertThat(financeDataService.getData(ResourceConstants.LATEST_IDR_RATES)).isNotNull(); + assertThat(financeDataService.getData(ResourceConstants.HISTORICAL_IDR_USD)).isNotNull(); + assertThat(financeDataService.getData(ResourceConstants.SUPPORTED_CURRENCIES)).isNotNull(); + } + + private static MockResponse jsonResponse(String body) { + return new MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(body); + } +} diff --git a/src/test/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcherTest.java b/src/test/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcherTest.java new file mode 100644 index 00000000..8e82b6b0 --- /dev/null +++ b/src/test/java/com/allobank/backendtest/strategy/HistoricalIdrUsdFetcherTest.java @@ -0,0 +1,100 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.CurrencyConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFunction; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.*; + +class HistoricalIdrUsdFetcherTest { + + private static final String HISTORICAL_RESPONSE_JSON = """ + { + "amount": 1.0, + "base": "IDR", + "start_date": "2023-12-29", + "end_date": "2024-01-05", + "rates": { + "2023-12-29": { "USD": 0.000065 }, + "2024-01-02": { "USD": 0.000064 }, + "2024-01-03": { "USD": 0.000064 }, + "2024-01-04": { "USD": 0.000064 }, + "2024-01-05": { "USD": 0.000064 } + } + } + """; + + private HistoricalIdrUsdFetcher fetcher; + + @BeforeEach + void setUp() { + WebClient mockWebClient = createMockWebClient(HISTORICAL_RESPONSE_JSON, HttpStatus.OK); + fetcher = new HistoricalIdrUsdFetcher(mockWebClient, new ObjectMapper(), "2024-01-01", "2024-01-05"); + } + + @Test + @DisplayName("Should return correct resource type identifier") + void getResourceType_shouldReturnHistoricalIdrUsd() { + assertThat(fetcher.getResourceType()).isEqualTo(ResourceConstants.HISTORICAL_IDR_USD); + } + + @Test + @DisplayName("Should fetch and deserialize historical data correctly") + @SuppressWarnings("unchecked") + void fetchData_shouldReturnCorrectStructure() { + Map result = (Map) fetcher.fetchData(); + + // Verify top-level structure + assertThat(result).containsKeys("amount", "base", "startDate", "endDate", "rates"); + + assertThat(result.get("amount")).isEqualTo(1.0); + assertThat(result.get("base")).isEqualTo(CurrencyConstants.IDR); + assertThat(result.get("startDate")).isEqualTo("2023-12-29"); + assertThat(result.get("endDate")).isEqualTo("2024-01-05"); + } + + @Test + @DisplayName("Should contain all date entries in rates") + @SuppressWarnings("unchecked") + void fetchData_shouldContainAllDateEntries() { + Map result = (Map) fetcher.fetchData(); + Map> rates = (Map>) result.get("rates"); + + assertThat(rates).hasSize(5); + assertThat(rates).containsKeys("2023-12-29", "2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"); + } + + @Test + @DisplayName("Should throw ExternalApiException on server error") + void fetchData_shouldThrowOnServerError() { + WebClient errorClient = createMockWebClient("Server Error", HttpStatus.INTERNAL_SERVER_ERROR); + HistoricalIdrUsdFetcher errorFetcher = new HistoricalIdrUsdFetcher( + errorClient, new ObjectMapper(), "2024-01-01", "2024-01-05"); + + assertThatThrownBy(errorFetcher::fetchData) + .isInstanceOf(ExternalApiException.class); + } + + private WebClient createMockWebClient(String responseBody, HttpStatus status) { + ExchangeFunction exchangeFunction = clientRequest -> + Mono.just(ClientResponse.create(status) + .header("Content-Type", "application/json") + .body(responseBody) + .build()); + + return WebClient.builder() + .exchangeFunction(exchangeFunction) + .build(); + } +} diff --git a/src/test/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcherTest.java b/src/test/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcherTest.java new file mode 100644 index 00000000..a0d91bef --- /dev/null +++ b/src/test/java/com/allobank/backendtest/strategy/LatestIdrRatesFetcherTest.java @@ -0,0 +1,111 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.CurrencyConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFunction; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.*; + +class LatestIdrRatesFetcherTest { + + private static final String GITHUB_USERNAME = "erlanggariansyah"; + private static final double EXPECTED_SPREAD_FACTOR = 0.00696; + + private static final String LATEST_RESPONSE_JSON = """ + { + "amount": 1.0, + "base": "IDR", + "date": "2026-04-17", + "rates": { + "AUD": 0.000081, + "USD": 0.000058, + "EUR": 0.000049, + "JPY": 0.00926 + } + } + """; + + private LatestIdrRatesFetcher fetcher; + + @BeforeEach + void setUp() { + WebClient mockWebClient = createMockWebClient(LATEST_RESPONSE_JSON, HttpStatus.OK); + fetcher = new LatestIdrRatesFetcher(mockWebClient, new ObjectMapper(), GITHUB_USERNAME); + } + + @Test + @DisplayName("Should return correct resource type identifier") + void getResourceType_shouldReturnLatestIdrRates() { + assertThat(fetcher.getResourceType()).isEqualTo(ResourceConstants.LATEST_IDR_RATES); + } + + @Test + @DisplayName("Should correctly calculate spread factor from GitHub username") + void calculateSpreadFactor_shouldComputeCorrectValue() { + double factor = LatestIdrRatesFetcher.calculateSpreadFactor(GITHUB_USERNAME); + assertThat(factor).isEqualTo(EXPECTED_SPREAD_FACTOR); + } + + @Test + @DisplayName("Should fetch data and include USD_BuySpread_IDR in response") + @SuppressWarnings("unchecked") + void fetchData_shouldReturnEnrichedDataWithSpread() { + Map result = (Map) fetcher.fetchData(); + + // Verify unified structure keys + assertThat(result).containsKeys("amount", "base", "date", "rates"); + + // Verify enrichment keys + assertThat(result).containsKeys("githubUsername", "spreadFactor", "USD_BuySpread_IDR"); + + assertThat(result.get("base")).isEqualTo(CurrencyConstants.IDR); + assertThat(result.get("githubUsername")).isEqualTo(GITHUB_USERNAME); + assertThat(result.get("spreadFactor")).isEqualTo(EXPECTED_SPREAD_FACTOR); + } + + @Test + @DisplayName("Should calculate USD_BuySpread_IDR correctly using the formula") + @SuppressWarnings("unchecked") + void fetchData_shouldCalculateUsdBuySpreadCorrectly() { + Map result = (Map) fetcher.fetchData(); + + double rateUsd = 0.000058; + double expectedSpread = (1.0 / rateUsd) * (1.0 + EXPECTED_SPREAD_FACTOR); + double actualSpread = (double) result.get("USD_BuySpread_IDR"); + + assertThat(actualSpread).isCloseTo(expectedSpread, within(0.01)); + } + + @Test + @DisplayName("Should throw ExternalApiException on server error") + void fetchData_shouldThrowOnServerError() { + WebClient errorClient = createMockWebClient("Server Error", HttpStatus.INTERNAL_SERVER_ERROR); + LatestIdrRatesFetcher errorFetcher = new LatestIdrRatesFetcher(errorClient, new ObjectMapper(), GITHUB_USERNAME); + + assertThatThrownBy(errorFetcher::fetchData) + .isInstanceOf(ExternalApiException.class); + } + + private WebClient createMockWebClient(String responseBody, HttpStatus status) { + ExchangeFunction exchangeFunction = clientRequest -> + Mono.just(ClientResponse.create(status) + .header("Content-Type", "application/json") + .body(responseBody) + .build()); + + return WebClient.builder() + .exchangeFunction(exchangeFunction) + .build(); + } +} diff --git a/src/test/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcherTest.java b/src/test/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcherTest.java new file mode 100644 index 00000000..61457d18 --- /dev/null +++ b/src/test/java/com/allobank/backendtest/strategy/SupportedCurrenciesFetcherTest.java @@ -0,0 +1,78 @@ +package com.allobank.backendtest.strategy; + +import com.allobank.backendtest.constant.CurrencyConstants; +import com.allobank.backendtest.constant.ResourceConstants; +import com.allobank.backendtest.exception.ExternalApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFunction; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.*; + +class SupportedCurrenciesFetcherTest { + + private static final String CURRENCIES_RESPONSE_JSON = """ + { + "AUD": "Australian Dollar", + "BRL": "Brazilian Real", + "EUR": "Euro", + "IDR": "Indonesian Rupiah", + "USD": "United States Dollar" + } + """; + + private SupportedCurrenciesFetcher fetcher; + + @BeforeEach + void setUp() { + WebClient mockWebClient = createMockWebClient(CURRENCIES_RESPONSE_JSON, HttpStatus.OK); + fetcher = new SupportedCurrenciesFetcher(mockWebClient, new ObjectMapper()); + } + + @Test + @DisplayName("Should return correct resource type identifier") + void getResourceType_shouldReturnSupportedCurrencies() { + assertThat(fetcher.getResourceType()).isEqualTo(ResourceConstants.SUPPORTED_CURRENCIES); + } + + @Test + @DisplayName("Should fetch and deserialize currencies correctly") + @SuppressWarnings("unchecked") + void fetchData_shouldReturnCurrencyMap() { + Map result = (Map) fetcher.fetchData(); + + assertThat(result).hasSize(5); + assertThat(result).containsEntry(CurrencyConstants.IDR, "Indonesian Rupiah"); + assertThat(result).containsEntry(CurrencyConstants.USD, "United States Dollar"); + } + + @Test + @DisplayName("Should throw ExternalApiException on server error") + void fetchData_shouldThrowOnServerError() { + WebClient errorClient = createMockWebClient("Server Error", HttpStatus.INTERNAL_SERVER_ERROR); + SupportedCurrenciesFetcher errorFetcher = new SupportedCurrenciesFetcher(errorClient, new ObjectMapper()); + + assertThatThrownBy(errorFetcher::fetchData) + .isInstanceOf(ExternalApiException.class); + } + + private WebClient createMockWebClient(String responseBody, HttpStatus status) { + ExchangeFunction exchangeFunction = clientRequest -> + Mono.just(ClientResponse.create(status) + .header("Content-Type", "application/json") + .body(responseBody) + .build()); + + return WebClient.builder() + .exchangeFunction(exchangeFunction) + .build(); + } +}