diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf 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..bff6fa9b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,83 @@ +<<<<<<< HEAD +# Frankfurter Exchange Rate Aggregator + Frankfurter Exchange Rate Aggregator as part of Allobank Backend Developer test. + +## Personalization + +- **GitHub Username:** nflhm +- **Spread Factor Calculation** + Sum of ASCII values of lowercase username: + `n`=110, `f`=102, `l`=108, `h`=104, `m`=109 + Total = 110+102+108+104+109 = **533** + Spread Factor = (533 % 1000) / 100000.0 = **0.00533** + +--- + +## Prerequisites + +- **Java 21** (or later) +- **Maven 3.6+** + +--- + +## Setup & Run Instructions + +1. **Clone the repository** + git clone https://github.com/nflhm/frankfurter-aggregator.git + +2. **Configure GitHub username** + Open src/main/resources/application.properties and set github.username value + +3. **Build the application** + Run the following command in cmd: mvn clean compile + +4. **Run the tests** + Run the following command in cmd: mvn test + +5. **Start the Application** + Run the following command in cmd: mvn spring-boot:run + +6. **Access the API** + The service runs on http://localhost:8080 with the following endpoint: +### 1. Latest IDR rates (includes USD_BuySpread_IDR) + curl http://localhost:8080/api/finance/data/latest_idr_rates + +### 2. Historical IDR to USD rates + curl http://localhost:8080/api/finance/data/historical_idr_usd + +### 3. All supported currencies + curl http://localhost:8080/api/finance/data/supported_currencies + +--- + +## Architectural Rationale +1. **Polymorphism Justification – Strategy Pattern** + The application supports three distinct data sources (latest_idr_rates, historical_idr_usd, supported_currencies), each requiring different logic for fetching and transforming data. Using the Strategy Pattern encapsulates each variant in its own class, implementing a common interface (IDRDataFetcher). The controller selects the appropriate strategy via a map lookup (injected by Spring). + + Benefits: + Extensibility: Adding a new resource type only requires creating a new strategy class; no existing code needs modification. + Maintainability: Each strategy is isolated, making it easier to test, debug, and modify individual behaviors. + Avoids Conditional Logic: Eliminates the need for if-else or switch statements in the controller or service layer, keeping the code clean and reducing complexity. + +2. **Client Factory – Why FactoryBean?** + A custom FactoryBean is used to create the WebClient instance. This factory centralizes configuration (base URL, timeouts, headers) and can be reused across all strategies. + + Advantages over a standard @Bean method: + Encapsulation of Complex Setup: The FactoryBean can perform additional logic (e.g., validation, conditional configuration) that would otherwise clutter a simple @Bean definition. + Separation of Concerns: The factory bean is responsible only for client creation, keeping the configuration class clean. + Testability: The factory can be easily mocked or replaced with a test double, allowing unit tests to inject a custom WebClient. + +3. **Startup Runner – ApplicationRunner over @PostConstruct** + The initial data load is performed in an ApplicationRunner component. + + Why not @PostConstruct? + @PostConstruct runs before the application context is fully initialized; if any dependencies (e,g., WebClient) are not yet ready, the operation may fail. + ApplicationRunner guarantees that all beans are fully instantiated and the context is ready before execution. + + Benefits: + Reliability: The data load happens after the entire application is ready, reducing the risk of missing dependencies. + Error Handling: Failures during data loading can be managed to prevent the application from starting with incomplete data (or to allow startup with graceful fallback). +======= # Allo Bank Backend Developer Take-Home Test Thank you for applying to our team! This take-home test is designed to evaluate your practical skills in building **production-ready** Spring Boot applications within a finance domain, focusing on architectural patterns and complex data handling. @@ -137,3 +217,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! +>>>>>>> upstream/main 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..f299ed39 --- /dev/null +++ b/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.1 + + + com.allobank + frankfurter + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.squareup.okhttp3 + mockwebserver + 4.12.0 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/allobank/frankfurter/FrankfurterApplication.java b/src/main/java/com/allobank/frankfurter/FrankfurterApplication.java new file mode 100644 index 00000000..8bcea465 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/FrankfurterApplication.java @@ -0,0 +1,13 @@ +package com.allobank.frankfurter; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FrankfurterApplication { + + public static void main(String[] args) { + SpringApplication.run(FrankfurterApplication.class, args); + } + +} diff --git a/src/main/java/com/allobank/frankfurter/client/WebClientFactoryBean.java b/src/main/java/com/allobank/frankfurter/client/WebClientFactoryBean.java new file mode 100644 index 00000000..588f8697 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/client/WebClientFactoryBean.java @@ -0,0 +1,44 @@ +package com.allobank.frankfurter.client; + +import io.netty.channel.ChannelOption; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import java.time.Duration; + +public class WebClientFactoryBean implements FactoryBean { + + private final String baseUrl; + private final Duration connectTimeout; + private final Duration readTimeout; + + public WebClientFactoryBean(String baseUrl, Duration connectTimeout, Duration readTimeout) { + this.baseUrl = baseUrl; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + } + + @Override + public WebClient getObject() { + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis()) + .responseTimeout(readTimeout); + + return WebClient.builder() + .baseUrl(baseUrl) + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); + } + + @Override + public Class getObjectType() { + return WebClient.class; + } + + @Override + public boolean isSingleton() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/config/FrankfurterApiProperties.java b/src/main/java/com/allobank/frankfurter/config/FrankfurterApiProperties.java new file mode 100644 index 00000000..171e4add --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/config/FrankfurterApiProperties.java @@ -0,0 +1,38 @@ +package com.allobank.frankfurter.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "frankfurter.api") +public class FrankfurterApiProperties { + private String baseUrl; + private int connectTimeout; + private int readTimeout; + + public String getBaseUrl() { + return baseUrl; + } + + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + this.connectTimeout = 5000; + this.readTimeout = 5000; + } + + public int getConnectTimeout() { + return connectTimeout; + } + + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } + + public int getReadTimeout() { + return readTimeout; + } + + public void setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/config/StrategyConfig.java b/src/main/java/com/allobank/frankfurter/config/StrategyConfig.java new file mode 100644 index 00000000..7dd3df6c --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/config/StrategyConfig.java @@ -0,0 +1,20 @@ +package com.allobank.frankfurter.config; + +import com.allobank.frankfurter.service.strategy.IDRDataFetcher; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Configuration +public class StrategyConfig { + + @Bean + public Map fetcherMap(List fetchers) { + return fetchers.stream() + .collect(Collectors.toMap(IDRDataFetcher::getResourceType, Function.identity())); + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/config/WebClientConfig.java b/src/main/java/com/allobank/frankfurter/config/WebClientConfig.java new file mode 100644 index 00000000..d6141a98 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/config/WebClientConfig.java @@ -0,0 +1,25 @@ +package com.allobank.frankfurter.config; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import java.time.Duration; + +@Configuration +public class WebClientConfig { + + private final FrankfurterApiProperties apiProperties; + + public WebClientConfig(FrankfurterApiProperties apiProperties) { + this.apiProperties = apiProperties; + } + + @Bean + public WebClientFactoryBean webClientFactoryBean() { + return new WebClientFactoryBean( + apiProperties.getBaseUrl(), + Duration.ofMillis(apiProperties.getConnectTimeout()), + Duration.ofMillis(apiProperties.getReadTimeout()) + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/controller/FinanceController.java b/src/main/java/com/allobank/frankfurter/controller/FinanceController.java new file mode 100644 index 00000000..17f82514 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/controller/FinanceController.java @@ -0,0 +1,33 @@ +package com.allobank.frankfurter.controller; + +import com.allobank.frankfurter.service.InMemoryDataStore; +import com.allobank.frankfurter.service.strategy.IDRDataFetcher; +import org.springframework.http.ResponseEntity; +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.Map; + +@RestController +@RequestMapping("/api/finance/data") +public class FinanceController { + + private final InMemoryDataStore dataStore; + private final Map fetcherMap; // not strictly needed for serving data, but could be used to fetch on-demand if needed + + public FinanceController(InMemoryDataStore dataStore, Map fetcherMap) { + this.dataStore = dataStore; + this.fetcherMap = fetcherMap; + } + + @GetMapping("/{resourceType}") + public ResponseEntity getData(@PathVariable String resourceType) { + var result = dataStore.get(resourceType); + if (result == null) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(result.getData()); + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/model/DataResult.java b/src/main/java/com/allobank/frankfurter/model/DataResult.java new file mode 100644 index 00000000..0e0c8cf2 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/model/DataResult.java @@ -0,0 +1,14 @@ +package com.allobank.frankfurter.model; + +public class DataResult { + private final String resourceType; + private final Object data; // can be Map, List, etc. + + public DataResult(String resourceType, Object data) { + this.resourceType = resourceType; + this.data = data; + } + + public String getResourceType() { return resourceType; } + public Object getData() { return data; } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/model/HistoricalRatesResponse.java b/src/main/java/com/allobank/frankfurter/model/HistoricalRatesResponse.java new file mode 100644 index 00000000..ef2d9bdd --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/model/HistoricalRatesResponse.java @@ -0,0 +1,26 @@ +package com.allobank.frankfurter.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; +import java.util.Map; + +public class HistoricalRatesResponse { + private Map> rates; + private String startDate; + private String endDate; + private String base; + + public Map> getRates() { return rates; } + public void setRates(Map> rates) { this.rates = rates; } + + public String getStartDate() { return startDate; } + @JsonProperty("start_date") + public void setStartDate(String startDate) { this.startDate = startDate; } + + public String getEndDate() { return endDate; } + @JsonProperty("end_date") + public void setEndDate(String endDate) { this.endDate = endDate; } + + public String getBase() { return base; } + public void setBase(String base) { this.base = base; } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/model/LatestRatesResponse.java b/src/main/java/com/allobank/frankfurter/model/LatestRatesResponse.java new file mode 100644 index 00000000..bbf4c24b --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/model/LatestRatesResponse.java @@ -0,0 +1,22 @@ +package com.allobank.frankfurter.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; +import java.util.Map; + +public class LatestRatesResponse { + private Map rates; + private String base; + private String date; + + public Map getRates() { return rates; } + public void setRates(Map rates) { this.rates = rates; } + + public String getBase() { return base; } + @JsonProperty("base") + public void setBase(String base) { this.base = base; } + + public String getDate() { return date; } + @JsonProperty("date") + public void setDate(String date) { this.date = date; } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/runner/DataLoader.java b/src/main/java/com/allobank/frankfurter/runner/DataLoader.java new file mode 100644 index 00000000..8ae360fc --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/runner/DataLoader.java @@ -0,0 +1,42 @@ +package com.allobank.frankfurter.runner; + +import com.allobank.frankfurter.service.InMemoryDataStore; +import com.allobank.frankfurter.service.strategy.IDRDataFetcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class DataLoader implements ApplicationRunner { + + private static final Logger logger = LoggerFactory.getLogger(DataLoader.class); + + private final List fetchers; + private final InMemoryDataStore dataStore; + + public DataLoader(List fetchers, InMemoryDataStore dataStore) { + this.fetchers = fetchers; + this.dataStore = dataStore; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + logger.info("Loading data from Frankfurter API..."); + for (IDRDataFetcher fetcher : fetchers) { + try { + var result = fetcher.fetchData(); + dataStore.put(result); + logger.info("Loaded data for resource: {}", result.getResourceType()); + } catch (Exception e) { + logger.error("Failed to load data for resource: {}", fetcher.getResourceType(), e); + // Rethrow to prevent app from starting with incomplete data. + throw new RuntimeException("Data loading failed", e); + } + } + logger.info("Data loading completed."); + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/service/InMemoryDataStore.java b/src/main/java/com/allobank/frankfurter/service/InMemoryDataStore.java new file mode 100644 index 00000000..b8c832f3 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/service/InMemoryDataStore.java @@ -0,0 +1,25 @@ +package com.allobank.frankfurter.service; + +import com.allobank.frankfurter.model.DataResult; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class InMemoryDataStore { + + private final Map store = new ConcurrentHashMap<>(); + + public void put(DataResult result) { + store.put(result.getResourceType(), result); + } + + public DataResult get(String resourceType) { + return store.get(resourceType); + } + + public Map getAll() { + return Map.copyOf(store); + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcher.java b/src/main/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcher.java new file mode 100644 index 00000000..627064da --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcher.java @@ -0,0 +1,38 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.Map; + +@Component +public class CurrenciesFetcher implements IDRDataFetcher { + + private final WebClient webClient; + private final String currenciesPath; + + public CurrenciesFetcher(WebClientFactoryBean webClientFactoryBean, + @Value("${frankfurter.api.currencies-path}") String currenciesPath) throws Exception { + this.webClient = webClientFactoryBean.getObject(); + this.currenciesPath = currenciesPath; + } + + @Override + public DataResult fetchData() { + Map currencies = webClient.get() + .uri(currenciesPath) + .retrieve() + .bodyToMono(Map.class) + .block(); + + return new DataResult(getResourceType(), currencies); + } + + @Override + public String getResourceType() { + return "supported_currencies"; + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcher.java b/src/main/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcher.java new file mode 100644 index 00000000..3098d6a9 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcher.java @@ -0,0 +1,44 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import com.allobank.frankfurter.model.HistoricalRatesResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; + +@Component +public class HistoricalRatesFetcher implements IDRDataFetcher { + + private final WebClient webClient; + private final String historicalRatesPath; + private final String historicalRatesStartDate; + private final String historicalRatesEndDate; + + public HistoricalRatesFetcher(WebClientFactoryBean webClientFactoryBean, + @Value("${frankfurter.api.historical-rates-path}") String historicalRatesPath, + @Value("${frankfurter.api.historical-rates-start-date}") String historicalRatesStartDate, + @Value("${frankfurter.api.historical-rates-end-date}") String historicalRatesEndDate) throws Exception { + this.webClient = webClientFactoryBean.getObject(); + this.historicalRatesPath = historicalRatesPath; + this.historicalRatesStartDate = historicalRatesStartDate; + this.historicalRatesEndDate = historicalRatesEndDate; + } + + @Override + public DataResult fetchData() { + String path = String.format(historicalRatesPath, historicalRatesStartDate, historicalRatesEndDate); + HistoricalRatesResponse response = webClient.get() + .uri(path) + .retrieve() + .bodyToMono(HistoricalRatesResponse.class) + .block(); + + return new DataResult(getResourceType(), response); + } + + @Override + public String getResourceType() { + return "historical_idr_usd"; + } +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/service/strategy/IDRDataFetcher.java b/src/main/java/com/allobank/frankfurter/service/strategy/IDRDataFetcher.java new file mode 100644 index 00000000..b7e1b454 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/service/strategy/IDRDataFetcher.java @@ -0,0 +1,8 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.model.DataResult; + +public interface IDRDataFetcher { + DataResult fetchData(); + String getResourceType(); +} \ No newline at end of file diff --git a/src/main/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcher.java b/src/main/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcher.java new file mode 100644 index 00000000..09c724e6 --- /dev/null +++ b/src/main/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcher.java @@ -0,0 +1,64 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import com.allobank.frankfurter.model.LatestRatesResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.HashMap; +import java.util.Map; + +@Component +public class LatestRatesFetcher implements IDRDataFetcher { + + private final WebClient webClient; + private final String githubUsername; + private final String latestRatesPath; + + public LatestRatesFetcher(WebClientFactoryBean webClientFactoryBean, + @Value("${github.username}") String githubUsername, + @Value("${frankfurter.api.latest-rates-path}") String latestRatesPath) throws Exception { + this.webClient = webClientFactoryBean.getObject(); + this.githubUsername = githubUsername; + this.latestRatesPath = latestRatesPath; + } + + @Override + public DataResult fetchData() { + LatestRatesResponse response = webClient.get() + .uri(latestRatesPath) + .retrieve() + .bodyToMono(LatestRatesResponse.class) + .block(); + + BigDecimal rateUSD = response.getRates().get("USD"); + BigDecimal spreadFactor = calculateSpreadFactor(); + BigDecimal usdBuySpreadIdr = BigDecimal.ONE.divide(rateUSD, MathContext.DECIMAL64) + .multiply(BigDecimal.ONE.add(spreadFactor)) + .setScale(2, RoundingMode.HALF_UP); + + Map result = new HashMap<>(); + result.put("base", response.getBase()); + result.put("date", response.getDate()); + result.put("rates", response.getRates()); + result.put("USD_BuySpread_IDR", usdBuySpreadIdr); + + return new DataResult(getResourceType(), result); + } + + private BigDecimal calculateSpreadFactor() { + long sum = githubUsername.toLowerCase().chars().sum(); + double spread = (sum % 1000) / 100000.0; + return BigDecimal.valueOf(spread); + } + + @Override + public String getResourceType() { + return "latest_idr_rates"; + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..6ce5e9e6 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,15 @@ +spring.application.name=frankfurter + +# Frankfurter API +frankfurter.api.base-url=https://api.frankfurter.app +frankfurter.api.currencies-path=/currencies +frankfurter.api.latest-rates-path=/latest?base=IDR +frankfurter.api.historical-rates-path=/%s..%s?from=IDR&to=USD +frankfurter.api.historical-rates-start-date=2024-01-01 +frankfurter.api.historical-rates-end-date=2024-01-05 + +# WebClient timeouts +# frankfurter.api.connect-timeout=5000 +# frankfurter.api.read-timeout=5000 + +github.username=nflhm \ No newline at end of file diff --git a/src/test/java/com/allobank/frankfurter/FrankfurterApplicationTests.java b/src/test/java/com/allobank/frankfurter/FrankfurterApplicationTests.java new file mode 100644 index 00000000..6665c1df --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/FrankfurterApplicationTests.java @@ -0,0 +1,13 @@ +package com.allobank.frankfurter; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class FrankfurterApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/allobank/frankfurter/controller/FinanceControllerTest.java b/src/test/java/com/allobank/frankfurter/controller/FinanceControllerTest.java new file mode 100644 index 00000000..65b73097 --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/controller/FinanceControllerTest.java @@ -0,0 +1,52 @@ +package com.allobank.frankfurter.controller; + +import com.allobank.frankfurter.service.InMemoryDataStore; +import com.allobank.frankfurter.service.strategy.IDRDataFetcher; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(FinanceController.class) +class FinanceControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private InMemoryDataStore dataStore; + + @MockBean + private Map fetcherMap; // to satisfy bean injection + + @Test + void getData_shouldReturnDataWhenExists() throws Exception { + Map mockData = new HashMap<>(); + mockData.put("base", "IDR"); + mockData.put("USD_BuySpread_IDR", 15764.84); + + when(dataStore.get("latest_idr_rates")).thenReturn(new com.allobank.frankfurter.model.DataResult("latest_idr_rates", mockData)); + + mockMvc.perform(get("/api/finance/data/latest_idr_rates")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.base").value("IDR")) + .andExpect(jsonPath("$.USD_BuySpread_IDR").value(15764.84)); + } + + @Test + void getData_shouldReturnNotFoundWhenMissing() throws Exception { + when(dataStore.get("nonexistent")).thenReturn(null); + + mockMvc.perform(get("/api/finance/data/nonexistent")) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/allobank/frankfurter/runner/DataLoaderIntegrationTest.java b/src/test/java/com/allobank/frankfurter/runner/DataLoaderIntegrationTest.java new file mode 100644 index 00000000..1f9a9c1c --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/runner/DataLoaderIntegrationTest.java @@ -0,0 +1,49 @@ +package com.allobank.frankfurter.runner; + +import com.allobank.frankfurter.model.DataResult; +import com.allobank.frankfurter.service.InMemoryDataStore; +import com.allobank.frankfurter.service.strategy.IDRDataFetcher; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@SpringBootTest +@AutoConfigureMockMvc +class DataLoaderIntegrationTest { + + @Autowired + private InMemoryDataStore dataStore; + + @MockBean(name = "latestRatesFetcher") + private IDRDataFetcher latestRatesFetcher; + + @MockBean(name = "historicalRatesFetcher") + private IDRDataFetcher historicalRatesFetcher; + + @MockBean(name = "currenciesFetcher") + private IDRDataFetcher currenciesFetcher; + + @Test + void dataLoader_shouldPopulateDataStore_whenFetchersReturnValidData() { + when(latestRatesFetcher.getResourceType()).thenReturn("latest_idr_rates"); + when(latestRatesFetcher.fetchData()).thenReturn(new DataResult("latest_idr_rates", Map.of("base", "IDR"))); + + when(historicalRatesFetcher.getResourceType()).thenReturn("historical_idr_usd"); + when(historicalRatesFetcher.fetchData()).thenReturn(new DataResult("historical_idr_usd", Map.of("base", "IDR"))); + + when(currenciesFetcher.getResourceType()).thenReturn("supported_currencies"); + when(currenciesFetcher.fetchData()).thenReturn(new DataResult("supported_currencies", Map.of("IDR", "Indonesian Rupiah"))); + + // DataLoader is ApplicationRunner and runs during startup; verify the store was populated. + assertThat(dataStore.get("latest_idr_rates")).isNotNull(); + assertThat(dataStore.get("historical_idr_usd")).isNotNull(); + assertThat(dataStore.get("supported_currencies")).isNotNull(); + } +} diff --git a/src/test/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcherTest.java b/src/test/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcherTest.java new file mode 100644 index 00000000..1c2d833c --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/service/strategy/CurrenciesFetcherTest.java @@ -0,0 +1,69 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.reactive.function.client.WebClient; + +import java.io.IOException; +import java.time.Duration; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class CurrenciesFetcherTest { + + private MockWebServer mockWebServer; + private CurrenciesFetcher fetcher; + + @BeforeEach + void setUp() throws Exception { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + + WebClient webClient = WebClient.builder() + .baseUrl(mockWebServer.url("/").toString()) + .build(); + + WebClientFactoryBean factoryBean = new WebClientFactoryBean( + mockWebServer.url("/").toString(), + Duration.ofMillis(5000), + Duration.ofMillis(5000)) { + @Override + public WebClient getObject() { + return webClient; + } + }; + + fetcher = new CurrenciesFetcher(factoryBean, "/currencies"); + } + + @AfterEach + void tearDown() throws IOException { + mockWebServer.shutdown(); + } + + @Test + void fetchData_shouldReturnCurrenciesMap() { + String jsonResponse = """ + { + "USD": "US Dollar", + "EUR": "Euro", + "IDR": "Indonesian Rupiah" + } + """; + mockWebServer.enqueue(new MockResponse().setBody(jsonResponse).addHeader("Content-Type", "application/json")); + + DataResult result = fetcher.fetchData(); + + assertThat(result.getResourceType()).isEqualTo("supported_currencies"); + Map data = (Map) result.getData(); + assertThat(data).containsEntry("USD", "US Dollar"); + assertThat(data).containsEntry("EUR", "Euro"); + assertThat(data).containsEntry("IDR", "Indonesian Rupiah"); + } +} \ No newline at end of file diff --git a/src/test/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcherTest.java b/src/test/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcherTest.java new file mode 100644 index 00000000..aa8b68e0 --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/service/strategy/HistoricalRatesFetcherTest.java @@ -0,0 +1,75 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import com.allobank.frankfurter.model.HistoricalRatesResponse; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.reactive.function.client.WebClient; + +import java.io.IOException; +import java.time.Duration; + +import static org.assertj.core.api.Assertions.assertThat; + +class HistoricalRatesFetcherTest { + + private MockWebServer mockWebServer; + private HistoricalRatesFetcher fetcher; + + @BeforeEach + void setUp() throws Exception { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + + WebClient webClient = WebClient.builder() + .baseUrl(mockWebServer.url("/").toString()) + .build(); + + WebClientFactoryBean factoryBean = new WebClientFactoryBean( + mockWebServer.url("/").toString(), + Duration.ofMillis(5000), + Duration.ofMillis(5000)) { + @Override + public WebClient getObject() { + return webClient; + } + }; + + fetcher = new HistoricalRatesFetcher(factoryBean, "/%s..%s?from=IDR&to=USD", "2024-01-01", "2024-01-05"); + } + + @AfterEach + void tearDown() throws IOException { + mockWebServer.shutdown(); + } + + @Test + void fetchData_shouldReturnHistoricalRates() { + String jsonResponse = """ + { + "rates": { + "2024-01-01": {"USD": 0.000064}, + "2024-01-02": {"USD": 0.000063}, + "2024-01-03": {"USD": 0.000065} + }, + "start_date": "2024-01-01", + "end_date": "2024-01-05", + "base": "IDR" + } + """; + mockWebServer.enqueue(new MockResponse().setBody(jsonResponse).addHeader("Content-Type", "application/json")); + + DataResult result = fetcher.fetchData(); + + assertThat(result.getResourceType()).isEqualTo("historical_idr_usd"); + HistoricalRatesResponse data = (HistoricalRatesResponse) result.getData(); + assertThat(data.getRates()).isNotNull(); + assertThat(data.getStartDate()).isEqualTo("2024-01-01"); + assertThat(data.getEndDate()).isEqualTo("2024-01-05"); + assertThat(data.getBase()).isEqualTo("IDR"); + } +} \ No newline at end of file diff --git a/src/test/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcherTest.java b/src/test/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcherTest.java new file mode 100644 index 00000000..52b3c9cb --- /dev/null +++ b/src/test/java/com/allobank/frankfurter/service/strategy/LatestRatesFetcherTest.java @@ -0,0 +1,67 @@ +package com.allobank.frankfurter.service.strategy; + +import com.allobank.frankfurter.client.WebClientFactoryBean; +import com.allobank.frankfurter.model.DataResult; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.reactive.function.client.WebClient; + +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class LatestRatesFetcherTest { + + private MockWebServer mockWebServer; + private WebClientFactoryBean factoryBean; + private LatestRatesFetcher fetcher; + + @BeforeEach + void setUp() throws Exception { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + + WebClient webClient = WebClient.builder() + .baseUrl(mockWebServer.url("/").toString()) + .build(); + + // Create a mock factory bean that returns the mock WebClient + factoryBean = new WebClientFactoryBean(mockWebServer.url("/").toString(), Duration.ofMillis(5000), Duration.ofMillis(5000)) { + @Override + public WebClient getObject() { + return webClient; + } + }; + + fetcher = new LatestRatesFetcher(factoryBean, "testuser", "/latest?base=IDR"); + } + + @AfterEach + void tearDown() throws IOException { + mockWebServer.shutdown(); + } + + @Test + void fetchData_shouldCalculateSpreadCorrectly() { + String jsonResponse = """ + { + "base": "IDR", + "date": "2024-01-01", + "rates": {"USD": 0.000064} + } + """; + mockWebServer.enqueue(new MockResponse().setBody(jsonResponse).addHeader("Content-Type", "application/json")); + + DataResult result = fetcher.fetchData(); + + Map data = (Map) result.getData(); + assertThat(data.get("base")).isEqualTo("IDR"); + assertThat(data.get("USD_BuySpread_IDR")).isEqualTo(new BigDecimal("15764.84")); + } +} \ No newline at end of file