From 21d835b9ca13eb42c1d1ad1a7b8d3c6d559a5aef Mon Sep 17 00:00:00 2001 From: Marcus Fihlon Date: Sun, 19 Apr 2026 21:07:46 +0200 Subject: [PATCH] =?UTF-8?q?feat(exercises):=20add=20JSR-354=20workshop=20e?= =?UTF-8?q?xercises=20(part1=E2=80=93part3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .gitattributes | 2 + .gitignore | 43 +++ .mvn/wrapper/maven-wrapper.properties | 3 + .sdkmanrc | 3 + mvnw | 295 ++++++++++++++++++ mvnw.cmd | 189 +++++++++++ pom.xml | 52 +++ .../money/part1/ArithmeticExercises.java | 65 ++++ .../money/part1/FormattingExercises.java | 50 +++ .../money/part1/IntegrationExercises.java | 27 ++ .../workshop/money/part1/MoneyExercises.java | 54 ++++ .../money/part1/ParsingExercises.java | 66 ++++ .../money/part1/RoundingExercises.java | 38 +++ .../part2/CurrencyConversionExercises.java | 63 ++++ .../money/part2/MonetaryContextExercises.java | 64 ++++ .../part2/MonetaryOperatorExercises.java | 61 ++++ .../money/part2/MonetaryQueryExercises.java | 62 ++++ .../part2/RoundingStrategyExercises.java | 61 ++++ .../workshop/money/part3/OrderExercises.java | 89 ++++++ .../money/part1/ArithmeticExercisesTest.java | 72 +++++ .../money/part1/FormattingExercisesTest.java | 39 +++ .../money/part1/IntegrationExercisesTest.java | 17 + .../money/part1/MoneyExercisesTest.java | 48 +++ .../money/part1/ParsingExercisesTest.java | 47 +++ .../money/part1/RoundingExercisesTest.java | 57 ++++ .../CurrencyConversionExercisesTest.java | 53 ++++ .../part2/MonetaryContextExercisesTest.java | 63 ++++ .../part2/MonetaryOperatorExercisesTest.java | 62 ++++ .../part2/MonetaryQueryExercisesTest.java | 54 ++++ .../part2/RoundingStrategyExercisesTest.java | 65 ++++ .../money/part3/OrderExercisesTest.java | 79 +++++ 31 files changed, 1943 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 .sdkmanrc create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/ArithmeticExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/FormattingExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/IntegrationExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/MoneyExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/ParsingExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part1/RoundingExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercises.java create mode 100644 src/main/java/swiss/fihlon/workshop/money/part3/OrderExercises.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/ArithmeticExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/FormattingExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/IntegrationExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/MoneyExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/ParsingExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part1/RoundingExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercisesTest.java create mode 100644 src/test/java/swiss/fihlon/workshop/money/part3/OrderExercisesTest.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..409052b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.bat text eol=crlf +mvnw eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1db2942 --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5291372 --- /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.15/apache-maven-3.9.15-bin.zip diff --git a/.sdkmanrc b/.sdkmanrc new file mode 100644 index 0000000..5e93e02 --- /dev/null +++ b/.sdkmanrc @@ -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 diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..bd8896b --- /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 0000000..92450f9 --- /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 0000000..57e82d9 --- /dev/null +++ b/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + swiss.fihlon.workshop.money + money-currency-api-workshop + 1.0-SNAPSHOT + + + 25 + 25 + UTF-8 + + + + + javax.money + money-api + 1.1 + + + org.javamoney.moneta + moneta-core + 1.4.5 + + + org.javamoney.moneta + moneta-convert-ecb + 1.4.5 + + + org.javamoney.moneta + moneta-convert-imf + 1.4.5 + + + org.junit.jupiter + junit-jupiter + 5.14.3 + test + + + org.assertj + assertj-core + 3.27.7 + test + + + + diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/ArithmeticExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/ArithmeticExercises.java new file mode 100644 index 0000000..1886e7e --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/ArithmeticExercises.java @@ -0,0 +1,65 @@ +package swiss.fihlon.workshop.money.part1; + +import javax.money.MonetaryAmount; + +/** + *

Part 1 workshop exercises for arithmetic operations on monetary amounts using JSR-354.

+ * + *

The exercises focus on performing calculations directly on monetary amounts instead of primitive numbers.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class ArithmeticExercises { + + /** + *

Add two monetary amounts that use the same currency.

+ * + *

Use monetary arithmetic and return the computed sum.

+ * + * @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"); + } + + /** + *

Subtract one monetary amount from another amount of the same currency.

+ * + *

Use monetary arithmetic and return the computed difference.

+ * + * @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"); + } + + /** + *

Multiply a monetary amount by a numeric factor.

+ * + *

Use monetary arithmetic and return the resulting amount.

+ * + * @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"); + } + + /** + *

Compare two monetary amounts that use the same currency.

+ * + *

Return {@code true} only when the first amount is greater than the second amount.

+ * + * @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"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/FormattingExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/FormattingExercises.java new file mode 100644 index 0000000..b1fa413 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/FormattingExercises.java @@ -0,0 +1,50 @@ +package swiss.fihlon.workshop.money.part1; + +import javax.money.MonetaryAmount; + +/** + *

Part 1 workshop exercises for formatting monetary amounts using JSR-354.

+ * + *

The exercises focus on locale-dependent representation of monetary amounts + * and demonstrate that formatting is separate from the monetary model.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class FormattingExercises { + + /** + *

Format the given amount using Swiss German locale conventions.

+ * + *

Use locale {@code de-CH} formatting rules.

+ * + * @param amount the amount to format + * @return formatted amount string for Swiss German locale + */ + public String formatSwissGerman(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Format the given amount using German locale conventions.

+ * + *

Use locale {@code de-DE} formatting rules.

+ * + * @param amount the amount to format + * @return formatted amount string for German locale + */ + public String formatGerman(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Format the given amount using US locale conventions.

+ * + *

Use locale {@code en-US} formatting rules.

+ * + * @param amount the amount to format + * @return formatted amount string for US locale + */ + public String formatUs(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/IntegrationExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/IntegrationExercises.java new file mode 100644 index 0000000..9036e31 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/IntegrationExercises.java @@ -0,0 +1,27 @@ +package swiss.fihlon.workshop.money.part1; + +/** + *

Part 1 workshop exercises for combining parsing, arithmetic, rounding, and formatting with JSR-354.

+ * + *

The exercises focus on applying the previously learned concepts in one coherent workflow.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class IntegrationExercises { + + /** + *

Calculate the final price from a Swiss German formatted input amount.

+ * + *

Parse the input using locale {@code de-CH}.

+ * + *

Add shipping costs of {@code CHF 4.95} and subtract a discount of {@code CHF 2.00}.

+ * + *

Apply default rounding and format the result using locale {@code de-CH}.

+ * + * @param priceText input price text + * @return formatted final price text + */ + public String calculateFinalPrice(String priceText) { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/MoneyExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/MoneyExercises.java new file mode 100644 index 0000000..e63510e --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/MoneyExercises.java @@ -0,0 +1,54 @@ +package swiss.fihlon.workshop.money.part1; + +import javax.money.CurrencyUnit; +import javax.money.MonetaryAmount; + +/** + *

Part 1 workshop exercises for creating currencies and monetary amounts using JSR-354.

+ * + *

The exercises focus on modeling money as a domain concept (amount and currency).

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class MoneyExercises { + + /** + *

Create a {@link CurrencyUnit} for Swiss franc.

+ *

Implement using the ISO currency code {@code CHF}.

+ * + * @return Swiss franc currency unit ({@code CHF}) + */ + public CurrencyUnit createSwissFranc() { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a {@link MonetaryAmount} representing 19.95 Swiss francs.

+ *

Use currency code {@code CHF} and preserve the decimal value exactly.

+ * + * @return monetary amount {@code 19.95 CHF} + */ + public MonetaryAmount createSwissFrancAmount() { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a {@link MonetaryAmount} representing 2500 Japanese yen.

+ *

Use currency code {@code JPY} and note that yen commonly has no fraction digits.

+ * + * @return monetary amount {@code 2500 JPY} + */ + public MonetaryAmount createJapaneseYenAmount() { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a {@link MonetaryAmount} representing 12.345 Tunisian dinar.

+ *

Use currency code {@code TND} and keep all three fraction digits.

+ * + * @return monetary amount {@code 12.345 TND} + */ + public MonetaryAmount createTunisianDinarAmount() { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/ParsingExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/ParsingExercises.java new file mode 100644 index 0000000..301c76a --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/ParsingExercises.java @@ -0,0 +1,66 @@ +package swiss.fihlon.workshop.money.part1; + +import javax.money.MonetaryAmount; +import java.util.Locale; + +/** + *

Part 1 workshop exercises for parsing monetary amounts using JSR-354.

+ * + *

The exercises focus on converting textual representations into monetary amounts + * using locale-specific parsing rules.

+ * + *

The exercises demonstrate that parsing depends on the locale and must match the expected format.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class ParsingExercises { + + /** + *

Parse a monetary amount string using Swiss German locale conventions.

+ * + *

Use locale {@code de-CH} parsing rules.

+ * + * @param text the input text to parse + * @return parsed monetary amount + */ + public MonetaryAmount parseSwissGerman(String text) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Parse a monetary amount string using German locale conventions.

+ * + *

Use locale {@code de-DE} parsing rules.

+ * + * @param text the input text to parse + * @return parsed monetary amount + */ + public MonetaryAmount parseGerman(String text) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Parse a monetary amount string using US locale conventions.

+ * + *

Use locale {@code en-US} parsing rules.

+ * + * @param text the input text to parse + * @return parsed monetary amount + */ + public MonetaryAmount parseUs(String text) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Try to parse an input text with the given locale and indicate whether parsing succeeds.

+ * + *

Return {@code false} if parsing fails due to mismatched format or locale.

+ * + * @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"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part1/RoundingExercises.java b/src/main/java/swiss/fihlon/workshop/money/part1/RoundingExercises.java new file mode 100644 index 0000000..ac299e8 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part1/RoundingExercises.java @@ -0,0 +1,38 @@ +package swiss.fihlon.workshop.money.part1; + +import javax.money.MonetaryAmount; + +/** + *

Part 1 workshop exercises for currency-aware rounding with JSR-354.

+ * + *

The exercises focus on explicit, currency-dependent rounding as part of domain logic.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class RoundingExercises { + + /** + *

Apply the default rounding for the currency of the given amount.

+ * + *

Use the rounding rules defined by the currency.

+ * + * @param amount the amount to round + * @return rounded amount + */ + public MonetaryAmount applyDefaultRounding(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Divide the given amount by an integer and apply default currency rounding.

+ * + *

Perform rounding as an explicit step after division.

+ * + * @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"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercises.java b/src/main/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercises.java new file mode 100644 index 0000000..7fd4b9e --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercises.java @@ -0,0 +1,63 @@ +package swiss.fihlon.workshop.money.part2; + +import java.time.LocalDateTime; +import javax.money.MonetaryAmount; +import javax.money.convert.CurrencyConversion; + +/** + *

Part 2 workshop exercises for currency conversion using JSR-354.

+ * + *

The exercises focus on obtaining conversions from providers and applying them to monetary amounts.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class CurrencyConversionExercises { + + /** + *

Create a currency conversion to EUR using a conversion provider.

+ * + *

Use a provider such as {@code ECB}.

+ * + * @return currency conversion to EUR + */ + public CurrencyConversion getEurConversion() { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Convert a CHF amount to EUR using a currency conversion.

+ * + *

Use JSR-354 conversion APIs and return the converted amount.

+ * + * @param amount amount in CHF + * @return converted amount in EUR + */ + public MonetaryAmount convertChfToEur(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a currency conversion to EUR using a timestamp-based conversion query.

+ * + *

Include the given {@link LocalDateTime} in the query.

+ * + * @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"); + } + + /** + *

Convert a CHF amount to EUR using a timestamp-based conversion query.

+ * + *

Build the conversion query with the given timestamp and return the converted amount.

+ * + * @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"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercises.java b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercises.java new file mode 100644 index 0000000..395a7be --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercises.java @@ -0,0 +1,64 @@ +package swiss.fihlon.workshop.money.part2; + +import javax.money.MonetaryAmount; +import javax.money.MonetaryContext; + +/** + *

Part 2 workshop exercises for understanding the role of MonetaryContext in JSR-354.

+ * + *

The exercises focus on how context influences the behavior of monetary amounts, + * such as precision and maximum scale.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class MonetaryContextExercises { + + /** + *

Return the monetary context of the given amount.

+ * + *

Use the JSR-354 context API.

+ * + * @param amount amount whose context should be returned + * @return monetary context of the amount + */ + public MonetaryContext getMonetaryContext(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Return the maximum scale from the monetary context of the given amount.

+ * + *

Use context metadata to read the maximum scale of the implementation.

+ * + * @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"); + } + + /** + *

Compare the monetary contexts of two amounts.

+ * + *

Return whether both contexts are equal.

+ * + * @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"); + } + + /** + *

Create a context description string for the given amount.

+ * + *

Include precision and max scale in the format {@code precision=..., maxScale=...}.

+ * + * @param amount amount whose context should be described + * @return formatted context description + */ + public String describeContext(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercises.java b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercises.java new file mode 100644 index 0000000..3147e8f --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercises.java @@ -0,0 +1,61 @@ +package swiss.fihlon.workshop.money.part2; + +import javax.money.MonetaryAmount; +import javax.money.MonetaryOperator; + +/** + *

Part 2 workshop exercises for encapsulating domain logic with MonetaryOperator.

+ * + *

The exercises focus on applying reusable monetary operations such as discounts and VAT.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class MonetaryOperatorExercises { + + /** + *

Apply a 10% discount to the given amount using a monetary operator.

+ * + *

Apply the operator with {@code with(...)}.

+ * + * @param amount amount to discount + * @return discounted amount + */ + public MonetaryAmount applyDiscount(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Apply 7.7% VAT to the given amount using a monetary operator.

+ * + *

Apply the operator with {@code with(...)}.

+ * + * @param amount amount before VAT + * @return amount after VAT + */ + public MonetaryAmount applyVat(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Apply a 10% discount and then 7.7% VAT using monetary operators.

+ * + *

Apply both operators in sequence with {@code with(...)}.

+ * + * @param amount original amount + * @return amount after discount and VAT + */ + public MonetaryAmount applyDiscountThenVat(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a reusable 10% discount monetary operator.

+ * + *

Apply the returned operator to amounts with {@code with(...)}.

+ * + * @return reusable discount operator + */ + public MonetaryOperator createDiscountOperator() { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercises.java b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercises.java new file mode 100644 index 0000000..79d3d76 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercises.java @@ -0,0 +1,62 @@ +package swiss.fihlon.workshop.money.part2; + +import java.math.BigDecimal; +import javax.money.MonetaryAmount; +import javax.money.MonetaryQuery; + +/** + *

Part 2 workshop exercises for extracting information from monetary amounts with MonetaryQuery.

+ * + *

The exercises focus on encapsulating reusable query logic for monetary values and currencies.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class MonetaryQueryExercises { + + /** + *

Extract the currency code from the given amount using a monetary query.

+ * + *

Apply the query with {@code query(...)}.

+ * + * @param amount amount to query + * @return currency code + */ + public String queryCurrencyCode(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Extract the default fraction digits from the given amount using a monetary query.

+ * + *

Apply the query with {@code query(...)}.

+ * + * @param amount amount to query + * @return default fraction digits of the currency + */ + public int queryDefaultFractionDigits(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Extract the numeric value from the given amount as {@link BigDecimal} using a monetary query.

+ * + *

Apply the query with {@code query(...)}.

+ * + * @param amount amount to query + * @return numeric value as BigDecimal + */ + public BigDecimal queryNumberAsBigDecimal(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Create a reusable monetary query that extracts a currency code.

+ * + *

Return the query so it can be applied to different amounts.

+ * + * @return reusable query returning a currency code + */ + public MonetaryQuery createCurrencyCodeQuery() { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercises.java b/src/main/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercises.java new file mode 100644 index 0000000..99f7615 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercises.java @@ -0,0 +1,61 @@ +package swiss.fihlon.workshop.money.part2; + +import javax.money.MonetaryAmount; +import javax.money.MonetaryOperator; + +/** + *

Part 2 workshop exercises for applying different rounding strategies with JSR-354.

+ * + *

The exercises focus on treating rounding as an explicit domain decision that depends on the use case.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class RoundingStrategyExercises { + + /** + *

Apply the default currency rounding to the given amount.

+ * + *

Use JSR-354 rounding APIs and return the rounded value.

+ * + * @param amount amount to round + * @return amount rounded with default currency rounding + */ + public MonetaryAmount applyDefaultRounding(MonetaryAmount amount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Apply explicit default rounding to a VAT amount.

+ * + *

Use rounding as a separate, explicit step.

+ * + * @param taxAmount tax amount to round + * @return rounded tax amount + */ + public MonetaryAmount roundVatAmount(MonetaryAmount taxAmount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Apply Swiss cash rounding to the nearest 0.05 for CHF amounts.

+ * + *

Return the rounded amount after applying the cash rounding rule.

+ * + * @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"); + } + + /** + *

Create a reusable monetary operator for Swiss cash rounding.

+ * + *

The operator rounds CHF amounts to the nearest 0.05.

+ * + * @return reusable Swiss cash rounding operator + */ + public MonetaryOperator createSwissCashRounding() { + throw new UnsupportedOperationException("TODO"); + } +} diff --git a/src/main/java/swiss/fihlon/workshop/money/part3/OrderExercises.java b/src/main/java/swiss/fihlon/workshop/money/part3/OrderExercises.java new file mode 100644 index 0000000..3ada081 --- /dev/null +++ b/src/main/java/swiss/fihlon/workshop/money/part3/OrderExercises.java @@ -0,0 +1,89 @@ +package swiss.fihlon.workshop.money.part3; + +import javax.money.CurrencyUnit; +import javax.money.MonetaryAmount; + +/** + *

Part 3 workshop exercises for integrating monetary calculations into a small order workflow.

+ * + *

The exercises focus on combining subtotal calculation, discount, VAT, rounding, and formatting.

+ * + *

The methods are intentionally incomplete and should be implemented by making tests pass.

+ */ +public class OrderExercises { + + /** + *

Calculate the subtotal by multiplying unit price with quantity.

+ * + *

Use monetary multiplication and return the subtotal in CHF.

+ * + * @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"); + } + + /** + *

Apply a 10% discount to the given subtotal using a monetary operator.

+ * + *

Return the discounted amount.

+ * + * @param subtotal subtotal before discount + * @return discounted amount + */ + public MonetaryAmount applyDiscount(MonetaryAmount subtotal) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Calculate the VAT-inclusive amount by applying 7.7% VAT to the given discounted amount.

+ * + *

Apply default currency rounding as an explicit step and return the VAT-inclusive amount.

+ * + * @param discountedAmount amount after discount + * @return VAT-inclusive amount + */ + public MonetaryAmount applyVat(MonetaryAmount discountedAmount) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Calculate the final total from unit price and quantity.

+ * + *

Combine subtotal calculation, discount application, and VAT calculation.

+ * + * @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"); + } + + /** + *

Format the given total amount using Swiss German locale conventions.

+ * + *

Use locale {@code de-CH} and return the formatted amount string.

+ * + * @param total total amount to format + * @return formatted total string + */ + public String formatTotal(MonetaryAmount total) { + throw new UnsupportedOperationException("TODO"); + } + + /** + *

Convert the given amount to the specified target currency.

+ * + *

Use a currency conversion and return the converted amount.

+ * + * @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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/ArithmeticExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/ArithmeticExercisesTest.java new file mode 100644 index 0000000..1ffc91e --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/ArithmeticExercisesTest.java @@ -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(); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/FormattingExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/FormattingExercisesTest.java new file mode 100644 index 0000000..a887279 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/FormattingExercisesTest.java @@ -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 1’234.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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/IntegrationExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/IntegrationExercisesTest.java new file mode 100644 index 0000000..3fb0b2a --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/IntegrationExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/MoneyExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/MoneyExercisesTest.java new file mode 100644 index 0000000..18d6e0e --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/MoneyExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/ParsingExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/ParsingExercisesTest.java new file mode 100644 index 0000000..a2e3ce5 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/ParsingExercisesTest.java @@ -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 1’234.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(); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part1/RoundingExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part1/RoundingExercisesTest.java new file mode 100644 index 0000000..31b9a85 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part1/RoundingExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercisesTest.java new file mode 100644 index 0000000..1ad9a00 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part2/CurrencyConversionExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercisesTest.java new file mode 100644 index 0000000..a3ec903 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryContextExercisesTest.java @@ -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()); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercisesTest.java new file mode 100644 index 0000000..bf14943 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryOperatorExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercisesTest.java new file mode 100644 index 0000000..ff9d959 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part2/MonetaryQueryExercisesTest.java @@ -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 query = exercises.createCurrencyCodeQuery(); + String firstResult = firstAmount.query(query); + String secondResult = secondAmount.query(query); + + assertThat(firstResult).isEqualTo("CHF"); + assertThat(secondResult).isEqualTo("CHF"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercisesTest.java new file mode 100644 index 0000000..6904009 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part2/RoundingStrategyExercisesTest.java @@ -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"); + } +} diff --git a/src/test/java/swiss/fihlon/workshop/money/part3/OrderExercisesTest.java b/src/test/java/swiss/fihlon/workshop/money/part3/OrderExercisesTest.java new file mode 100644 index 0000000..de49979 --- /dev/null +++ b/src/test/java/swiss/fihlon/workshop/money/part3/OrderExercisesTest.java @@ -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); + } +}