feat(exercises): add JSR-354 workshop exercises (part1–part3)

Introduce hands-on exercises with tests covering:

* part1: MoneyExercises, ArithmeticExercises, RoundingExercises,
  FormattingExercises, ParsingExercises, IntegrationExercises
* part2: CurrencyConversionExercises, MonetaryOperatorExercises,
  MonetaryQueryExercises, MonetaryContextExercises,
  RoundingStrategyExercises
* part3: OrderExercises (end-to-end order workflow)

Use incomplete production methods with TODOs and complete JUnit 5 tests
(AssertJ only). Tests focus on observable behavior and avoid fragile
assertions (e.g., no fixed FX rates). Ensure clear progression from
basics to advanced concepts and final integration task.
This commit is contained in:
Marcus Fihlon 2026-04-19 21:07:46 +02:00
parent e83a9a5b93
commit 21d835b9ca
Signed by: McPringle
GPG key ID: C6B7F469EE363E1F
31 changed files with 1943 additions and 0 deletions

2
.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
*.bat text eol=crlf
mvnw eol=lf

43
.gitignore vendored Normal file
View file

@ -0,0 +1,43 @@
/target/
/.gradle
/build/
!**/src/main/**/target/
!**/src/test/**/target/
!**/src/main/**/build/
!**/src/test/**/build/
# The following files are often generated by operating systems or desktop environments
.DS_Store
Thumbs.db
# Eclipse and STS
/.apt_generated
/.classpath
/.factorypath
/.project
/.settings
/.springBeans
/.sts4-cache
# IntelliJ IDEA
/.idea
/*.iws
/*.iml
/*.ipr
/out/
!**/src/main/**/out/
!**/src/test/**/out/
# NetBeans
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
nb-configuration.xml
# VS Code
/.vscode/
# Moneta Exchange Rate Provider Cache
/.resourceCache/

3
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View file

@ -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.15/apache-maven-3.9.15-bin.zip

3
.sdkmanrc Normal file
View file

@ -0,0 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=25.0.2-tem

295
mvnw vendored Executable file
View file

@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -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 "$@"

189
mvnw.cmd vendored Normal file
View file

@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
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"

52
pom.xml Normal file
View file

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>swiss.fihlon.workshop.money</groupId>
<artifactId>money-currency-api-workshop</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax.money</groupId>
<artifactId>money-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.javamoney.moneta</groupId>
<artifactId>moneta-core</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.javamoney.moneta</groupId>
<artifactId>moneta-convert-ecb</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.javamoney.moneta</groupId>
<artifactId>moneta-convert-imf</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.27.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,65 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.MonetaryAmount;
/**
* <p>Part 1 workshop exercises for arithmetic operations on monetary amounts using JSR-354.</p>
*
* <p>The exercises focus on performing calculations directly on monetary amounts instead of primitive numbers.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class ArithmeticExercises {
/**
* <p>Add two monetary amounts that use the same currency.</p>
*
* <p>Use monetary arithmetic and return the computed sum.</p>
*
* @param firstAmount the first amount
* @param secondAmount the second amount
* @return sum of both amounts in the same currency
*/
public MonetaryAmount addAmounts(MonetaryAmount firstAmount, MonetaryAmount secondAmount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Subtract one monetary amount from another amount of the same currency.</p>
*
* <p>Use monetary arithmetic and return the computed difference.</p>
*
* @param minuend the amount to subtract from
* @param subtrahend the amount to subtract
* @return difference after subtraction in the same currency
*/
public MonetaryAmount subtractAmounts(MonetaryAmount minuend, MonetaryAmount subtrahend) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Multiply a monetary amount by a numeric factor.</p>
*
* <p>Use monetary arithmetic and return the resulting amount.</p>
*
* @param amount the amount to multiply
* @param factor multiplication factor
* @return product amount in the same currency
*/
public MonetaryAmount multiplyAmount(MonetaryAmount amount, int factor) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Compare two monetary amounts that use the same currency.</p>
*
* <p>Return {@code true} only when the first amount is greater than the second amount.</p>
*
* @param firstAmount first amount to compare
* @param secondAmount second amount to compare
* @return {@code true} if first amount is greater, otherwise {@code false}
*/
public boolean compareAmounts(MonetaryAmount firstAmount, MonetaryAmount secondAmount) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,50 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.MonetaryAmount;
/**
* <p>Part 1 workshop exercises for formatting monetary amounts using JSR-354.</p>
*
* <p>The exercises focus on locale-dependent representation of monetary amounts
* and demonstrate that formatting is separate from the monetary model.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class FormattingExercises {
/**
* <p>Format the given amount using Swiss German locale conventions.</p>
*
* <p>Use locale {@code de-CH} formatting rules.</p>
*
* @param amount the amount to format
* @return formatted amount string for Swiss German locale
*/
public String formatSwissGerman(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Format the given amount using German locale conventions.</p>
*
* <p>Use locale {@code de-DE} formatting rules.</p>
*
* @param amount the amount to format
* @return formatted amount string for German locale
*/
public String formatGerman(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Format the given amount using US locale conventions.</p>
*
* <p>Use locale {@code en-US} formatting rules.</p>
*
* @param amount the amount to format
* @return formatted amount string for US locale
*/
public String formatUs(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,27 @@
package swiss.fihlon.workshop.money.part1;
/**
* <p>Part 1 workshop exercises for combining parsing, arithmetic, rounding, and formatting with JSR-354.</p>
*
* <p>The exercises focus on applying the previously learned concepts in one coherent workflow.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class IntegrationExercises {
/**
* <p>Calculate the final price from a Swiss German formatted input amount.</p>
*
* <p>Parse the input using locale {@code de-CH}.</p>
*
* <p>Add shipping costs of {@code CHF 4.95} and subtract a discount of {@code CHF 2.00}.</p>
*
* <p>Apply default rounding and format the result using locale {@code de-CH}.</p>
*
* @param priceText input price text
* @return formatted final price text
*/
public String calculateFinalPrice(String priceText) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,54 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.CurrencyUnit;
import javax.money.MonetaryAmount;
/**
* <p>Part 1 workshop exercises for creating currencies and monetary amounts using JSR-354.</p>
*
* <p>The exercises focus on modeling money as a domain concept (amount and currency).</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class MoneyExercises {
/**
* <p>Create a {@link CurrencyUnit} for Swiss franc.</p>
* <p>Implement using the ISO currency code {@code CHF}.</p>
*
* @return Swiss franc currency unit ({@code CHF})
*/
public CurrencyUnit createSwissFranc() {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a {@link MonetaryAmount} representing 19.95 Swiss francs.</p>
* <p>Use currency code {@code CHF} and preserve the decimal value exactly.</p>
*
* @return monetary amount {@code 19.95 CHF}
*/
public MonetaryAmount createSwissFrancAmount() {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a {@link MonetaryAmount} representing 2500 Japanese yen.</p>
* <p>Use currency code {@code JPY} and note that yen commonly has no fraction digits.</p>
*
* @return monetary amount {@code 2500 JPY}
*/
public MonetaryAmount createJapaneseYenAmount() {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a {@link MonetaryAmount} representing 12.345 Tunisian dinar.</p>
* <p>Use currency code {@code TND} and keep all three fraction digits.</p>
*
* @return monetary amount {@code 12.345 TND}
*/
public MonetaryAmount createTunisianDinarAmount() {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,66 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.MonetaryAmount;
import java.util.Locale;
/**
* <p>Part 1 workshop exercises for parsing monetary amounts using JSR-354.</p>
*
* <p>The exercises focus on converting textual representations into monetary amounts
* using locale-specific parsing rules.</p>
*
* <p>The exercises demonstrate that parsing depends on the locale and must match the expected format.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class ParsingExercises {
/**
* <p>Parse a monetary amount string using Swiss German locale conventions.</p>
*
* <p>Use locale {@code de-CH} parsing rules.</p>
*
* @param text the input text to parse
* @return parsed monetary amount
*/
public MonetaryAmount parseSwissGerman(String text) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Parse a monetary amount string using German locale conventions.</p>
*
* <p>Use locale {@code de-DE} parsing rules.</p>
*
* @param text the input text to parse
* @return parsed monetary amount
*/
public MonetaryAmount parseGerman(String text) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Parse a monetary amount string using US locale conventions.</p>
*
* <p>Use locale {@code en-US} parsing rules.</p>
*
* @param text the input text to parse
* @return parsed monetary amount
*/
public MonetaryAmount parseUs(String text) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Try to parse an input text with the given locale and indicate whether parsing succeeds.</p>
*
* <p>Return {@code false} if parsing fails due to mismatched format or locale.</p>
*
* @param text the input text to parse
* @param locale the locale used for parsing
* @return {@code true} if parsing succeeds, otherwise {@code false}
*/
public boolean parseInvalidInput(String text, Locale locale) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,38 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.MonetaryAmount;
/**
* <p>Part 1 workshop exercises for currency-aware rounding with JSR-354.</p>
*
* <p>The exercises focus on explicit, currency-dependent rounding as part of domain logic.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class RoundingExercises {
/**
* <p>Apply the default rounding for the currency of the given amount.</p>
*
* <p>Use the rounding rules defined by the currency.</p>
*
* @param amount the amount to round
* @return rounded amount
*/
public MonetaryAmount applyDefaultRounding(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Divide the given amount by an integer and apply default currency rounding.</p>
*
* <p>Perform rounding as an explicit step after division.</p>
*
* @param amount the amount to divide
* @param divisor the integer divisor
* @return divided and rounded amount
*/
public MonetaryAmount divideAndRound(MonetaryAmount amount, int divisor) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,63 @@
package swiss.fihlon.workshop.money.part2;
import java.time.LocalDateTime;
import javax.money.MonetaryAmount;
import javax.money.convert.CurrencyConversion;
/**
* <p>Part 2 workshop exercises for currency conversion using JSR-354.</p>
*
* <p>The exercises focus on obtaining conversions from providers and applying them to monetary amounts.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class CurrencyConversionExercises {
/**
* <p>Create a currency conversion to EUR using a conversion provider.</p>
*
* <p>Use a provider such as {@code ECB}.</p>
*
* @return currency conversion to EUR
*/
public CurrencyConversion getEurConversion() {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Convert a CHF amount to EUR using a currency conversion.</p>
*
* <p>Use JSR-354 conversion APIs and return the converted amount.</p>
*
* @param amount amount in CHF
* @return converted amount in EUR
*/
public MonetaryAmount convertChfToEur(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a currency conversion to EUR using a timestamp-based conversion query.</p>
*
* <p>Include the given {@link LocalDateTime} in the query.</p>
*
* @param timestamp timestamp used in the conversion query
* @return currency conversion to EUR for the given timestamp
*/
public CurrencyConversion getEurConversionForTimestamp(LocalDateTime timestamp) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Convert a CHF amount to EUR using a timestamp-based conversion query.</p>
*
* <p>Build the conversion query with the given timestamp and return the converted amount.</p>
*
* @param amount amount in CHF
* @param timestamp timestamp used in the conversion query
* @return converted amount in EUR
*/
public MonetaryAmount convertChfToEurAt(MonetaryAmount amount, LocalDateTime timestamp) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,64 @@
package swiss.fihlon.workshop.money.part2;
import javax.money.MonetaryAmount;
import javax.money.MonetaryContext;
/**
* <p>Part 2 workshop exercises for understanding the role of MonetaryContext in JSR-354.</p>
*
* <p>The exercises focus on how context influences the behavior of monetary amounts,
* such as precision and maximum scale.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class MonetaryContextExercises {
/**
* <p>Return the monetary context of the given amount.</p>
*
* <p>Use the JSR-354 context API.</p>
*
* @param amount amount whose context should be returned
* @return monetary context of the amount
*/
public MonetaryContext getMonetaryContext(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Return the maximum scale from the monetary context of the given amount.</p>
*
* <p>Use context metadata to read the maximum scale of the implementation.</p>
*
* @param amount amount whose maximum scale should be returned
* @return maximum scale from the monetary context
*/
public int getMaxScale(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Compare the monetary contexts of two amounts.</p>
*
* <p>Return whether both contexts are equal.</p>
*
* @param firstAmount first amount
* @param secondAmount second amount
* @return {@code true} if both contexts are equal, otherwise {@code false}
*/
public boolean compareContexts(MonetaryAmount firstAmount, MonetaryAmount secondAmount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a context description string for the given amount.</p>
*
* <p>Include precision and max scale in the format {@code precision=..., maxScale=...}.</p>
*
* @param amount amount whose context should be described
* @return formatted context description
*/
public String describeContext(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,61 @@
package swiss.fihlon.workshop.money.part2;
import javax.money.MonetaryAmount;
import javax.money.MonetaryOperator;
/**
* <p>Part 2 workshop exercises for encapsulating domain logic with MonetaryOperator.</p>
*
* <p>The exercises focus on applying reusable monetary operations such as discounts and VAT.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class MonetaryOperatorExercises {
/**
* <p>Apply a 10% discount to the given amount using a monetary operator.</p>
*
* <p>Apply the operator with {@code with(...)}.</p>
*
* @param amount amount to discount
* @return discounted amount
*/
public MonetaryAmount applyDiscount(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Apply 7.7% VAT to the given amount using a monetary operator.</p>
*
* <p>Apply the operator with {@code with(...)}.</p>
*
* @param amount amount before VAT
* @return amount after VAT
*/
public MonetaryAmount applyVat(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Apply a 10% discount and then 7.7% VAT using monetary operators.</p>
*
* <p>Apply both operators in sequence with {@code with(...)}.</p>
*
* @param amount original amount
* @return amount after discount and VAT
*/
public MonetaryAmount applyDiscountThenVat(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a reusable 10% discount monetary operator.</p>
*
* <p>Apply the returned operator to amounts with {@code with(...)}.</p>
*
* @return reusable discount operator
*/
public MonetaryOperator createDiscountOperator() {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,62 @@
package swiss.fihlon.workshop.money.part2;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import javax.money.MonetaryQuery;
/**
* <p>Part 2 workshop exercises for extracting information from monetary amounts with MonetaryQuery.</p>
*
* <p>The exercises focus on encapsulating reusable query logic for monetary values and currencies.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class MonetaryQueryExercises {
/**
* <p>Extract the currency code from the given amount using a monetary query.</p>
*
* <p>Apply the query with {@code query(...)}.</p>
*
* @param amount amount to query
* @return currency code
*/
public String queryCurrencyCode(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Extract the default fraction digits from the given amount using a monetary query.</p>
*
* <p>Apply the query with {@code query(...)}.</p>
*
* @param amount amount to query
* @return default fraction digits of the currency
*/
public int queryDefaultFractionDigits(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Extract the numeric value from the given amount as {@link BigDecimal} using a monetary query.</p>
*
* <p>Apply the query with {@code query(...)}.</p>
*
* @param amount amount to query
* @return numeric value as BigDecimal
*/
public BigDecimal queryNumberAsBigDecimal(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a reusable monetary query that extracts a currency code.</p>
*
* <p>Return the query so it can be applied to different amounts.</p>
*
* @return reusable query returning a currency code
*/
public MonetaryQuery<String> createCurrencyCodeQuery() {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,61 @@
package swiss.fihlon.workshop.money.part2;
import javax.money.MonetaryAmount;
import javax.money.MonetaryOperator;
/**
* <p>Part 2 workshop exercises for applying different rounding strategies with JSR-354.</p>
*
* <p>The exercises focus on treating rounding as an explicit domain decision that depends on the use case.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class RoundingStrategyExercises {
/**
* <p>Apply the default currency rounding to the given amount.</p>
*
* <p>Use JSR-354 rounding APIs and return the rounded value.</p>
*
* @param amount amount to round
* @return amount rounded with default currency rounding
*/
public MonetaryAmount applyDefaultRounding(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Apply explicit default rounding to a VAT amount.</p>
*
* <p>Use rounding as a separate, explicit step.</p>
*
* @param taxAmount tax amount to round
* @return rounded tax amount
*/
public MonetaryAmount roundVatAmount(MonetaryAmount taxAmount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Apply Swiss cash rounding to the nearest 0.05 for CHF amounts.</p>
*
* <p>Return the rounded amount after applying the cash rounding rule.</p>
*
* @param amount CHF amount to cash-round
* @return CHF amount rounded to the nearest 0.05
*/
public MonetaryAmount applySwissCashRounding(MonetaryAmount amount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Create a reusable monetary operator for Swiss cash rounding.</p>
*
* <p>The operator rounds CHF amounts to the nearest 0.05.</p>
*
* @return reusable Swiss cash rounding operator
*/
public MonetaryOperator createSwissCashRounding() {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,89 @@
package swiss.fihlon.workshop.money.part3;
import javax.money.CurrencyUnit;
import javax.money.MonetaryAmount;
/**
* <p>Part 3 workshop exercises for integrating monetary calculations into a small order workflow.</p>
*
* <p>The exercises focus on combining subtotal calculation, discount, VAT, rounding, and formatting.</p>
*
* <p>The methods are intentionally incomplete and should be implemented by making tests pass.</p>
*/
public class OrderExercises {
/**
* <p>Calculate the subtotal by multiplying unit price with quantity.</p>
*
* <p>Use monetary multiplication and return the subtotal in CHF.</p>
*
* @param unitPrice unit price in CHF
* @param quantity quantity to multiply
* @return subtotal amount
*/
public MonetaryAmount calculateSubtotal(MonetaryAmount unitPrice, int quantity) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Apply a 10% discount to the given subtotal using a monetary operator.</p>
*
* <p>Return the discounted amount.</p>
*
* @param subtotal subtotal before discount
* @return discounted amount
*/
public MonetaryAmount applyDiscount(MonetaryAmount subtotal) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Calculate the VAT-inclusive amount by applying 7.7% VAT to the given discounted amount.</p>
*
* <p>Apply default currency rounding as an explicit step and return the VAT-inclusive amount.</p>
*
* @param discountedAmount amount after discount
* @return VAT-inclusive amount
*/
public MonetaryAmount applyVat(MonetaryAmount discountedAmount) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Calculate the final total from unit price and quantity.</p>
*
* <p>Combine subtotal calculation, discount application, and VAT calculation.</p>
*
* @param unitPrice unit price in CHF
* @param quantity quantity to multiply
* @return final total amount
*/
public MonetaryAmount calculateTotal(MonetaryAmount unitPrice, int quantity) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Format the given total amount using Swiss German locale conventions.</p>
*
* <p>Use locale {@code de-CH} and return the formatted amount string.</p>
*
* @param total total amount to format
* @return formatted total string
*/
public String formatTotal(MonetaryAmount total) {
throw new UnsupportedOperationException("TODO");
}
/**
* <p>Convert the given amount to the specified target currency.</p>
*
* <p>Use a currency conversion and return the converted amount.</p>
*
* @param amount amount to convert
* @param targetCurrency target currency
* @return amount converted to the target currency
*/
public MonetaryAmount convertToCurrency(MonetaryAmount amount, CurrencyUnit targetCurrency) {
throw new UnsupportedOperationException("TODO");
}
}

View file

@ -0,0 +1,72 @@
package swiss.fihlon.workshop.money.part1;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ArithmeticExercisesTest {
private final ArithmeticExercises exercises = new ArithmeticExercises();
@Test
void shouldAddAmountsWithSameCurrency() {
MonetaryAmount first = Money.of(19.95, "CHF");
MonetaryAmount second = Money.of(5.05, "CHF");
MonetaryAmount result = exercises.addAmounts(first, second);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("25.00");
}
@Test
void shouldSubtractAmountsWithSameCurrency() {
MonetaryAmount minuend = Money.of(20.00, "CHF");
MonetaryAmount subtrahend = Money.of(3.50, "CHF");
MonetaryAmount result = exercises.subtractAmounts(minuend, subtrahend);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("16.50");
}
@Test
void shouldMultiplyAmountByFactor() {
MonetaryAmount amount = Money.of(12.30, "CHF");
MonetaryAmount result = exercises.multiplyAmount(amount, 3);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("36.90");
}
@Test
void shouldReturnTrueWhenFirstAmountIsGreater() {
MonetaryAmount higher = Money.of(10.00, "CHF");
MonetaryAmount lower = Money.of(9.99, "CHF");
assertThat(exercises.compareAmounts(higher, lower)).isTrue();
}
@Test
void shouldReturnFalseWhenFirstAmountIsSmaller() {
MonetaryAmount lower = Money.of(9.99, "CHF");
MonetaryAmount higher = Money.of(10.00, "CHF");
assertThat(exercises.compareAmounts(lower, higher)).isFalse();
}
@Test
void shouldReturnFalseWhenAmountsAreEqual() {
MonetaryAmount first = Money.of(10.00, "CHF");
MonetaryAmount second = Money.of(10.00, "CHF");
assertThat(exercises.compareAmounts(first, second)).isFalse();
}
}

View file

@ -0,0 +1,39 @@
package swiss.fihlon.workshop.money.part1;
import javax.money.MonetaryAmount;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class FormattingExercisesTest {
private final FormattingExercises exercises = new FormattingExercises();
@Test
void shouldFormatSwissGerman() {
MonetaryAmount amount = Money.of(1234.56, "CHF");
String result = exercises.formatSwissGerman(amount);
assertThat(result).isEqualTo("CHF 1234.56");
}
@Test
void shouldFormatGerman() {
MonetaryAmount amount = Money.of(1234.56, "CHF");
String result = exercises.formatGerman(amount);
assertThat(result).isEqualTo("1.234,56 CHF");
}
@Test
void shouldFormatUs() {
MonetaryAmount amount = Money.of(1234.56, "CHF");
String result = exercises.formatUs(amount);
assertThat(result).isEqualTo("CHF1,234.56");
}
}

View file

@ -0,0 +1,17 @@
package swiss.fihlon.workshop.money.part1;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class IntegrationExercisesTest {
private final IntegrationExercises exercises = new IntegrationExercises();
@Test
void shouldCalculateFinalPrice() {
String result = exercises.calculateFinalPrice("CHF 19.95");
assertThat(result).isEqualTo("CHF 22.90");
}
}

View file

@ -0,0 +1,48 @@
package swiss.fihlon.workshop.money.part1;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MoneyExercisesTest {
private final MoneyExercises exercises = new MoneyExercises();
@Test
void shouldCreateSwissFranc() {
var currency = exercises.createSwissFranc();
assertThat(currency).isNotNull();
assertThat(currency.getCurrencyCode()).isEqualTo("CHF");
assertThat(currency.getDefaultFractionDigits()).isEqualTo(2);
}
@Test
void shouldCreateSwissFrancAmount() {
MonetaryAmount amount = exercises.createSwissFrancAmount();
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("19.95");
}
@Test
void shouldCreateJapaneseYenAmount() {
MonetaryAmount amount = exercises.createJapaneseYenAmount();
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("JPY");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("2500");
}
@Test
void shouldCreateTunisianDinarAmount() {
MonetaryAmount amount = exercises.createTunisianDinarAmount();
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("TND");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("12.345");
}
}

View file

@ -0,0 +1,47 @@
package swiss.fihlon.workshop.money.part1;
import java.math.BigDecimal;
import java.util.Locale;
import javax.money.MonetaryAmount;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ParsingExercisesTest {
private final ParsingExercises exercises = new ParsingExercises();
@Test
void shouldParseSwissGermanAmount() {
MonetaryAmount amount = exercises.parseSwissGerman("CHF 1234.56");
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("1234.56");
}
@Test
void shouldParseGermanAmount() {
MonetaryAmount amount = exercises.parseGerman("1.234,56 CHF");
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("1234.56");
}
@Test
void shouldParseUsAmount() {
MonetaryAmount amount = exercises.parseUs("CHF1,234.56");
assertThat(amount).isNotNull();
assertThat(amount.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(amount.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("1234.56");
}
@Test
void shouldReturnFalseForInvalidInputInGivenLocale() {
boolean parsingSucceeded = exercises.parseInvalidInput("1.234,56 CHF", Locale.forLanguageTag("de-CH"));
assertThat(parsingSucceeded).isFalse();
}
}

View file

@ -0,0 +1,57 @@
package swiss.fihlon.workshop.money.part1;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class RoundingExercisesTest {
private final RoundingExercises exercises = new RoundingExercises();
@Test
void shouldApplyDefaultRoundingToSwissFranc() {
MonetaryAmount amount = Money.of(3.3333, "CHF");
MonetaryAmount result = exercises.applyDefaultRounding(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("3.33");
}
@Test
void shouldApplyDefaultRoundingToJapaneseYen() {
MonetaryAmount amount = Money.of(123.45, "JPY");
MonetaryAmount result = exercises.applyDefaultRounding(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("JPY");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("123");
}
@Test
void shouldApplyDefaultRoundingToTunisianDinar() {
MonetaryAmount amount = Money.of(12.3456, "TND");
MonetaryAmount result = exercises.applyDefaultRounding(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("TND");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("12.346");
}
@Test
void shouldDivideAndRoundSwissFranc() {
MonetaryAmount amount = Money.of(10.00, "CHF");
MonetaryAmount result = exercises.divideAndRound(amount, 3);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("3.33");
}
}

View file

@ -0,0 +1,53 @@
package swiss.fihlon.workshop.money.part2;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import javax.money.MonetaryAmount;
import javax.money.convert.CurrencyConversion;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
class CurrencyConversionExercisesTest {
private final CurrencyConversionExercises exercises = new CurrencyConversionExercises();
@Test
void shouldCreateEurConversion() {
CurrencyConversion conversion = exercises.getEurConversion();
assertThat(conversion).isNotNull();
assertThat(conversion.getCurrency().getCurrencyCode()).isEqualTo("EUR");
}
@Test
void shouldConvertChfToEur() {
MonetaryAmount chfAmount = Money.of(10, "CHF");
MonetaryAmount result = exercises.convertChfToEur(chfAmount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("EUR");
}
@Test
void shouldCreateEurConversionForTimestamp() {
LocalDateTime timestamp = LocalDateTime.of(2024, 1, 15, 10, 30);
CurrencyConversion conversion = exercises.getEurConversionForTimestamp(timestamp);
assertThat(conversion).isNotNull();
assertThat(conversion.getCurrency().getCurrencyCode()).isEqualTo("EUR");
}
@Test
void shouldConvertChfToEurAtTimestamp() {
MonetaryAmount chfAmount = Money.of(10, "CHF");
LocalDateTime timestamp = LocalDateTime.of(2024, 1, 15, 10, 30);
MonetaryAmount result = exercises.convertChfToEurAt(chfAmount, timestamp);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("EUR");
}
}

View file

@ -0,0 +1,63 @@
package swiss.fihlon.workshop.money.part2;
import javax.money.MonetaryAmount;
import javax.money.MonetaryContext;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MonetaryContextExercisesTest {
private final MonetaryContextExercises exercises = new MonetaryContextExercises();
@Test
void shouldReturnMonetaryContext() {
MonetaryAmount amount = Money.of(19.95, "CHF");
MonetaryContext result = exercises.getMonetaryContext(amount);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(amount.getContext());
}
@Test
void shouldReturnMaxScaleFromMonetaryContext() {
MonetaryAmount amount = Money.of(19.95, "CHF");
int result = exercises.getMaxScale(amount);
assertThat(result).isEqualTo(amount.getContext().getMaxScale());
}
@Test
void shouldReturnTrueWhenContextsAreFromSameImplementation() {
MonetaryAmount firstAmount = Money.of(10, "CHF");
MonetaryAmount secondAmount = Money.of(25.50, "EUR");
boolean result = exercises.compareContexts(firstAmount, secondAmount);
assertThat(result).isTrue();
}
@Test
void shouldReturnFalseWhenContextsAreFromDifferentImplementations() {
MonetaryAmount firstAmount = Money.of(10, "CHF");
MonetaryAmount secondAmount = FastMoney.of(10, "CHF");
boolean result = exercises.compareContexts(firstAmount, secondAmount);
assertThat(result).isFalse();
}
@Test
void shouldDescribeContextWithPrecisionAndMaxScale() {
MonetaryAmount amount = Money.of(19.95, "CHF");
MonetaryContext context = amount.getContext();
String result = exercises.describeContext(amount);
assertThat(result).isEqualTo("precision=" + context.getPrecision() + ", maxScale=" + context.getMaxScale());
}
}

View file

@ -0,0 +1,62 @@
package swiss.fihlon.workshop.money.part2;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import javax.money.MonetaryOperator;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MonetaryOperatorExercisesTest {
private final MonetaryOperatorExercises exercises = new MonetaryOperatorExercises();
@Test
void shouldApplyDiscount() {
MonetaryAmount amount = Money.of(100, "CHF");
MonetaryAmount result = exercises.applyDiscount(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("90.00");
}
@Test
void shouldApplyVat() {
MonetaryAmount amount = Money.of(100, "CHF");
MonetaryAmount result = exercises.applyVat(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("107.70");
}
@Test
void shouldApplyDiscountThenVat() {
MonetaryAmount amount = Money.of(100, "CHF");
MonetaryAmount result = exercises.applyDiscountThenVat(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("96.93");
}
@Test
void shouldCreateReusableDiscountOperator() {
MonetaryAmount firstAmount = Money.of(50, "CHF");
MonetaryAmount secondAmount = Money.of(20, "CHF");
MonetaryOperator discountOperator = exercises.createDiscountOperator();
MonetaryAmount firstResult = firstAmount.with(discountOperator);
MonetaryAmount secondResult = secondAmount.with(discountOperator);
assertThat(firstResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(firstResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("45.00");
assertThat(secondResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(secondResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("18.00");
}
}

View file

@ -0,0 +1,54 @@
package swiss.fihlon.workshop.money.part2;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import javax.money.MonetaryQuery;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MonetaryQueryExercisesTest {
private final MonetaryQueryExercises exercises = new MonetaryQueryExercises();
@Test
void shouldQueryCurrencyCode() {
MonetaryAmount amount = Money.of(19.95, "CHF");
String result = exercises.queryCurrencyCode(amount);
assertThat(result).isEqualTo("CHF");
}
@Test
void shouldQueryDefaultFractionDigits() {
MonetaryAmount amount = Money.of(19.95, "CHF");
int result = exercises.queryDefaultFractionDigits(amount);
assertThat(result).isEqualTo(2);
}
@Test
void shouldQueryNumberAsBigDecimal() {
MonetaryAmount amount = Money.of(19.95, "CHF");
BigDecimal result = exercises.queryNumberAsBigDecimal(amount);
assertThat(result).isEqualByComparingTo("19.95");
}
@Test
void shouldCreateReusableCurrencyCodeQuery() {
MonetaryAmount firstAmount = Money.of(10, "CHF");
MonetaryAmount secondAmount = Money.of(5.50, "CHF");
MonetaryQuery<String> query = exercises.createCurrencyCodeQuery();
String firstResult = firstAmount.query(query);
String secondResult = secondAmount.query(query);
assertThat(firstResult).isEqualTo("CHF");
assertThat(secondResult).isEqualTo("CHF");
}
}

View file

@ -0,0 +1,65 @@
package swiss.fihlon.workshop.money.part2;
import java.math.BigDecimal;
import javax.money.MonetaryAmount;
import javax.money.MonetaryOperator;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class RoundingStrategyExercisesTest {
private final RoundingStrategyExercises exercises = new RoundingStrategyExercises();
@Test
void shouldApplyDefaultRounding() {
MonetaryAmount amount = Money.of(10.024, "CHF");
MonetaryAmount result = exercises.applyDefaultRounding(amount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("10.02");
}
@Test
void shouldRoundVatAmount() {
MonetaryAmount taxAmount = Money.of(1.537, "CHF");
MonetaryAmount result = exercises.roundVatAmount(taxAmount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("1.54");
}
@Test
void shouldApplySwissCashRounding() {
MonetaryAmount firstAmount = Money.of(10.02, "CHF");
MonetaryAmount secondAmount = Money.of(10.03, "CHF");
MonetaryAmount firstResult = exercises.applySwissCashRounding(firstAmount);
MonetaryAmount secondResult = exercises.applySwissCashRounding(secondAmount);
assertThat(firstResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(firstResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("10.00");
assertThat(secondResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(secondResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("10.05");
}
@Test
void shouldCreateSwissCashRoundingOperator() {
MonetaryOperator rounding = exercises.createSwissCashRounding();
MonetaryAmount firstAmount = Money.of(10.02, "CHF");
MonetaryAmount secondAmount = Money.of(10.03, "CHF");
MonetaryAmount firstResult = firstAmount.with(rounding);
MonetaryAmount secondResult = secondAmount.with(rounding);
assertThat(firstResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(firstResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("10.00");
assertThat(secondResult.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(secondResult.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("10.05");
}
}

View file

@ -0,0 +1,79 @@
package swiss.fihlon.workshop.money.part3;
import java.math.BigDecimal;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class OrderExercisesTest {
private final OrderExercises exercises = new OrderExercises();
@Test
void shouldCalculateSubtotal() {
MonetaryAmount unitPrice = Money.of(10.00, "CHF");
MonetaryAmount result = exercises.calculateSubtotal(unitPrice, 3);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("30.00");
}
@Test
void shouldApplyDiscount() {
MonetaryAmount subtotal = Money.of(30.00, "CHF");
MonetaryAmount result = exercises.applyDiscount(subtotal);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("27.00");
}
@Test
void shouldApplyVat() {
MonetaryAmount discountedAmount = Money.of(27.00, "CHF");
MonetaryAmount result = exercises.applyVat(discountedAmount);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("29.08");
}
@Test
void shouldCalculateTotal() {
MonetaryAmount unitPrice = Money.of(10.00, "CHF");
MonetaryAmount result = exercises.calculateTotal(unitPrice, 3);
assertThat(result).isNotNull();
assertThat(result.getCurrency().getCurrencyCode()).isEqualTo("CHF");
assertThat(result.getNumber().numberValueExact(BigDecimal.class)).isEqualByComparingTo("29.08");
}
@Test
void shouldFormatTotalInSwissGermanLocale() {
MonetaryAmount total = Money.of(29.08, "CHF");
String result = exercises.formatTotal(total);
assertThat(result).isEqualTo("CHF 29.08");
}
@Test
void shouldConvertAmountToTargetCurrency() {
MonetaryAmount amount = Money.of(29.08, "CHF");
CurrencyUnit eur = Monetary.getCurrency("EUR");
MonetaryAmount result = exercises.convertToCurrency(amount, eur);
assertThat(result).isNotNull();
assertThat(result.getCurrency()).isEqualTo(eur);
}
}