diff --git a/README.md b/README.md
index 026b47a..82dbb7d 100644
--- a/README.md
+++ b/README.md
@@ -68,8 +68,8 @@ A collection of hands-on coding interview projects organized by language. Each p
> **Backend concepts:** [java/concepts/](java/concepts/) is a different kind of project: not a timed
> round, but one concept taught step by step. Each is broken first (you run it and watch the problem
> happen), has challenge tasks and a guided version, tests as acceptance criteria, and `start/` and
-> `solution/` folders side by side. There are eleven so far, numbered in the suggested order from
-> `01-transactional` to `11-pagination`: see the [list](java/concepts/README.md).
+> `solution/` folders side by side. There are fifteen so far, numbered in the suggested order from
+> `01-transactional` to `15-equals-and-hashcode`: see the [list](java/concepts/README.md).
## Structure
@@ -97,7 +97,7 @@ interview-prep/
│ ├── karat-drills/
│ ├── secret-storage/
│ ├── concepts/
-│ │ └── junior-mid/ (01-transactional ... 11-pagination)
+│ │ └── junior-mid/ (01-transactional ... 15-equals-and-hashcode)
│ ├── DELIVERY_HERO.md
│ └── KARAT.md
├── python/
diff --git a/java/concepts/README.md b/java/concepts/README.md
index 8385dfc..eefafd6 100644
--- a/java/concepts/README.md
+++ b/java/concepts/README.md
@@ -22,6 +22,10 @@ under [`java/`](../).
| 09 | Junior / mid | [Isolation levels](junior-mid/09-isolation-levels/) | A bank statement whose lines add up to 1000 and whose total says 1100 |
| 10 | Junior / mid | [Constraints and races](junior-mid/10-constraints-and-races/) | Two signups with the same email both succeed |
| 11 | Junior / mid | [Pagination](junior-mid/11-pagination/) | Page 5,000 reads 100,000 rows to return 20 |
+| 12 | Junior / mid | [Caching with Redis](junior-mid/12-caching-with-redis/) | 20 requests for the same product, 20 calls to the slow source |
+| 13 | Junior / mid | [Money as double](junior-mid/13-money-as-double/) | 1,000 payments of 0.10 add up to 100.00 and 99.99 is paid out |
+| 14 | Junior / mid | [Authorisation and JWT](junior-mid/14-authorisation-and-jwt/) | Merchant A reads merchant B's invoices by changing the id in the URL |
+| 15 | Junior / mid | [equals and hashCode](junior-mid/15-equals-and-hashcode/) | An item goes into a set, its quantity changes, and the set can no longer find it |
The numbers are the suggested order. Each project stands on its own, so you can start anywhere.
diff --git a/java/concepts/ci-projects.json b/java/concepts/ci-projects.json
index 4d2e2a3..9f80ccc 100644
--- a/java/concepts/ci-projects.json
+++ b/java/concepts/ci-projects.json
@@ -9,5 +9,9 @@
{ "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 },
{ "path": "java/concepts/junior-mid/09-isolation-levels", "startPass": 22, "total": 31 },
{ "path": "java/concepts/junior-mid/10-constraints-and-races", "startPass": 19, "total": 35 },
- { "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 }
+ { "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 },
+ { "path": "java/concepts/junior-mid/12-caching-with-redis", "startPass": 13, "total": 28 },
+ { "path": "java/concepts/junior-mid/13-money-as-double", "startPass": 9, "total": 34 },
+ { "path": "java/concepts/junior-mid/14-authorisation-and-jwt", "startPass": 15, "total": 31 },
+ { "path": "java/concepts/junior-mid/15-equals-and-hashcode", "startPass": 14, "total": 34 }
]
diff --git a/java/concepts/junior-mid/12-caching-with-redis/INTERVIEW_TASKS.md b/java/concepts/junior-mid/12-caching-with-redis/INTERVIEW_TASKS.md
new file mode 100644
index 0000000..c6134e7
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/INTERVIEW_TASKS.md
@@ -0,0 +1,326 @@
+# Interview Tasks — Caching with Redis
+
+> **In `start/`, `./check` FAILS on purpose: 13 of 28 checks pass.** Tasks 2, 4, 5, 6, 7 and 8 turn
+> the other 15 green. Tasks 1, 3 and 9 are inspection tasks: you run things, look, and answer
+> questions. Some checks of Tasks 4 and 8 pass now only because nothing is cached yet. Expect Task 2
+> to turn them red.
+
+Do the tasks in order. A green test tells you the fix works; the inspection steps tell you **why**,
+and the why is what an interviewer asks for.
+
+Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks
+you through it with the expected output.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+**Rules:** work in `start/`. Never edit, delete or disable a test. Keep the constructors of
+`ProductController` and `ProductService` as they are: the baseline tests build them. Do not touch
+`SlowProductSource`: it is the slow thing you are protecting, not the thing you fix. Everything you
+need is already in `pom.xml`.
+
+---
+
+## Task 1: See Every Request Pay for the Slow Source (10 min)
+
+**Story:** *The product page takes over 200 ms, and the most popular products are opened thousands
+of times an hour. Before you add anything, measure what one request costs and what it is spent on.*
+
+**Steps:**
+1. `docker compose up -d`, then `./demo`. How many of the 20 requests called the slow source? How
+ long did each one take?
+2. Open `SlowProductSource` and `ProductService.findById`. What does one request do?
+3. `./demo --requests 50 --delay-ms 500`. How does the total time grow?
+4. `./inspect`. What is in Redis? Redis is running: why is it empty?
+5. `./demo --scenario basket`. The basket shows 3 products. How many calls to the slow source per
+ basket?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can say how many times the slow source is called for N requests, and why
+- [ ] You can say what would have to be true about a product for a cache to be safe for it
+- [ ] You can name one thing a cache would make worse
+
+**Hints:**
+- The price of a product changes a few times a day. It is read thousands of times an hour
+
+---
+
+## Task 2: Cache Products in Redis, as JSON (25 min)
+
+**Story:** *Cache the product page in Redis. Somebody on the team will want to look at what is in
+Redis during an incident, so it has to be readable. Change `CacheConfig` and `ProductService`.*
+
+**Acceptance Criteria** (`./check 2`)
+- [ ] Caching is switched on and backed by a `RedisCacheManager` — `CacheIT.theCacheIsRedis`
+- [ ] 5 GETs for product 1 call the slow source once — `CacheIT.repeatedReadsHitTheCache`
+- [ ] Every product has its own entry — `CacheIT.eachProductIsCachedSeparately`
+- [ ] Product 1 is stored under the key `products::1` — `CacheIT.theKeyIsTheCacheNameAndTheId`
+- [ ] The value in Redis is readable JSON with the name and price, not Java serialization bytes
+ — `CacheIT.theValueIsJson`
+- [ ] An unknown product is a 404 every time and leaves nothing in Redis
+ — `CacheIT.anUnknownProductIsNotCached` (already passing: keep it that way)
+- [ ] `./demo` prints `RESULT: OK` with 1 call to the slow source
+
+**Hints:**
+- Two annotations are enough to get something cached. Run `./demo` straight after adding them, and
+ read the `Cause:` line
+- The quick fix for that error works. Look at what it stored with `./inspect` before you keep it
+- Spring Boot builds the `RedisCacheManager` for you. A `RedisCacheManagerBuilderCustomizer` bean
+ lets you give one cache its own `RedisCacheConfiguration`
+- Spring Data Redis 4 has `JacksonJsonRedisSerializer`, for one known type
+
+**Then inspect:** `./inspect`. How many bytes is the entry now? What is its TTL? Run `./check`: which
+checks of Task 4 and Task 8 were green before your change and are red now?
+
+---
+
+## Task 3: Inspect the Cache, and Watch It Go Stale (15 min)
+
+**Story:** *The cache is live and the product page is fast. On the first day the back office lowers
+a price, and the shop keeps showing the old one. Find out what is in Redis and why.*
+
+**Steps:**
+1. `./demo --scenario update`. Which step returned which price? Which steps called the slow source?
+2. `./inspect`. Find product 1 in both tables. What does Postgres say, what does Redis say?
+3. Read `ProductService.changePrice`. What does it change, and what does it not know about?
+4. Look at the `ttl` column. If nothing changes in the code, when will the shop show the right
+ price?
+5. Somebody runs `update product set price = 70.00 where id = 2` straight in the database. Can any
+ annotation in your code fix that case?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can explain why the cache and the database disagree
+- [ ] You can explain why a TTL alone is not the fix, and why you still want one
+- [ ] You can name two ways a price can change without `changePrice` being called
+
+---
+
+## Task 4: Fix the Stale Price After an Update (20 min)
+
+**Story:** *When the price changes, the cached copy has to go. Fix `ProductService.changePrice`.*
+
+**Acceptance Criteria** (`./check 4`)
+- [ ] After `PUT` a new price, `GET` returns it — `StaleDataIT.getReturnsTheNewPrice`
+- [ ] After the `PUT`, Redis no longer holds the old price — `StaleDataIT.redisDoesNotKeepTheOldPrice`
+- [ ] Changing product 1 does not empty the whole cache — `StaleDataIT.otherProductsStayCached`
+- [ ] The entry is removed after the new price is committed, so a `GET` in between cannot put the
+ old price back — `StaleDataIT.evictionHappensAfterTheCommit`
+- [ ] `./demo --scenario update` prints `RESULT: OK`
+
+**Hints:**
+- `@CacheEvict` and `@CachePut` both pass. Be ready to say which one you chose and why
+- `changePrice` is `@Transactional`. When does the commit happen, and when does your eviction?
+- Try `beforeInvocation = true` once and run `./check 4`. The demo says OK. Why does the test not?
+
+**Then inspect:** `./demo --scenario update` and `./inspect`. Which step called the slow source now?
+How many keys are in Redis, and what is in `PRICE CHANGES`?
+
+---
+
+## Task 5: Fix the Cache That the Basket Skips (15 min)
+
+**Story:** *The product page is fast, but the basket page still takes over 600 ms, every time, even
+for products that are in the cache. Find out why. Do not cache the basket as a whole.*
+
+**Acceptance Criteria** (`./check 5`)
+- [ ] A basket of products 1, 2 and 3, asked for twice, loads each product once
+ — `SelfInvocationIT.theBasketIsCached`
+- [ ] A product cached by the product page is not loaded again by the basket
+ — `SelfInvocationIT.theBasketUsesWhatTheProductPageCached`
+- [ ] What the basket loaded is cached for the product page too
+ — `SelfInvocationIT.theProductPageUsesWhatTheBasketCached`
+- [ ] `./demo --scenario basket` prints `RESULT: OK`
+- [ ] The baseline is still green (`./check`)
+
+**Hints:**
+- `./demo --scenario basket` first. Product 1 is in Redis. Did the basket even look?
+- Read `ProductService.findAll`. Who calls `findById` there, and is that caller the Spring proxy?
+- [`../01-transactional`](../01-transactional) has the same bug with `@Transactional`
+- Two fixes work here: call `findById` from another bean, or inject the proxy into
+ `ProductService`. Which one would you choose in a real codebase?
+
+---
+
+## Task 6: Give Cached Products a TTL (15 min)
+
+**Story:** *A supplier changes a price through a nightly SQL import, which never calls the API.
+Those prices stay wrong in the shop for ever. Cached products must expire after
+`catalogue.cache.products-ttl` (10 minutes). Change `CacheConfig`.*
+
+**Acceptance Criteria** (`./check 6`)
+- [ ] Redis reports a TTL of more than 0 and at most 10 minutes for `products::1`
+ — `TtlIT.entriesHaveATtl`
+- [ ] The TTL comes from `catalogue.cache.products-ttl`, not from a number in the code
+ — `ShortTtlIT.theTtlIsConfigured`
+- [ ] Once the entry expires, the next `GET` loads the product again and sees a price that was
+ changed straight in the database — `ShortTtlIT.anExpiredEntryIsLoadedAgain`
+
+**Hints:**
+- `RedisCacheConfiguration` has a method for it
+- `spring.cache.redis.time-to-live` looks like the answer. Try it and run `./inspect`. Why does it
+ not apply to your `products` cache?
+
+**Then inspect:** `./demo --requests 1 --ttl 15`, then `./inspect --watch`. Watch the `ttl` column.
+What happens at 0? What does the next request cost?
+
+---
+
+## Task 7: Fix the Cache Stampede (25 min)
+
+**Story:** *Product 1 is on the home page. Every 10 minutes its entry expires, and in that moment
+hundreds of requests miss the cache together and all of them run the expensive query. The database
+team calls it a thundering herd. Make sure only one request loads a missing product.*
+
+**Acceptance Criteria** (`./check 7`)
+- [ ] 10 requests for a product that is not cached call the slow source once
+ — `StampedeIT.onlyOneRequestLoads`
+- [ ] All 10 get the product — `StampedeIT.everybodyGetsTheProduct` (already passing)
+- [ ] While a product loads, the lock is a key in Redis (`products~lock`), so other instances of the
+ application wait for it too — `StampedeIT.theLockLivesInRedis`
+- [ ] The lock has a TTL, so an instance that dies while loading cannot block the cache for ever
+ — `StampedeIT.theLockExpires`
+- [ ] `./demo --scenario stampede` prints `RESULT: OK`
+
+**Hints:**
+- `./demo --scenario stampede` first. Then add the textbook answer, `sync = true`, and run it again.
+ What changed?
+- `sync = true` asks the cache to load a missing entry only once. Whether it does is up to the
+ cache. Look at `RedisCacheWriter`: there are two kinds
+- `RedisCacheWriter.create(connectionFactory, writer -> ...)` and `RedisCacheManagerBuilder.cacheWriter`
+- The default lock never expires
+
+**Then inspect:** `./demo --scenario stampede` again and read the line for product 2. It was cached
+the whole time: why did it take as long as the load? Then `./demo --scenario stampede --delay-ms 5000`
+with `./inspect --watch` in a second terminal: find the lock key and its TTL. What happens if a load
+takes as long as the lock's TTL? (`--delay-ms 10000` answers it, slowly.)
+
+---
+
+## Task 8: Keep the Shop Up When Redis Is Down (15 min)
+
+**Story:** *Redis is restarted for an upgrade, and for 30 seconds every product page is a 500. The
+cache was supposed to make the shop faster, not to become something it cannot live without. Change
+`CacheConfig`.*
+
+**Acceptance Criteria** (`./check 8`)
+- [ ] With Redis unreachable, `GET` still returns the product, from the slow source
+ — `RedisDownIT.readsStillWork`
+- [ ] With Redis unreachable, `PUT` still changes the price — `RedisDownIT.writesStillWork`
+ (green since the start: keep it that way)
+- [ ] `./demo --scenario redis-down` prints `RESULT: OK`
+- [ ] `./check` prints 28 passes and no failures
+
+**Hints:**
+- `./demo --scenario redis-down` first. Read the `Cause:` line
+- Spring's cache abstraction lets you decide what happens when the cache itself fails: look for
+ `CacheErrorHandler`, and how `CachingConfigurer` provides one
+- Spring already ships an implementation that logs and carries on
+
+**Then inspect:** what happens to the slow source, and to the database behind it, while Redis is
+down? Why does the `PUT` work even without your change, and what does that mean for the cached price
+when Redis comes back?
+
+---
+
+## Task 9: Compare, and Decide What to Cache (15 min)
+
+**Story:** *"So we should cache everything?" is the interview question. Collect the numbers, then
+give the honest answer.*
+
+**Steps:**
+1. In `solution/` (or your finished `start/`) run each scenario and note calls to the slow source
+ and time taken: `./demo`, `./demo --scenario basket`, `./demo --scenario stampede`,
+ `./demo --scenario stampede --requests 100`, `./demo --scenario redis-down`.
+2. Compare with the same scenarios in a fresh copy of `start/`.
+3. For each, say what could be wrong in the answer the user got, and for how long at most.
+4. Which of these would you cache, and for how long? A product's name and price. A customer's
+ basket. The stock level on a product page. The stock level checked when an order is placed. A
+ user's account balance. The list of product categories.
+5. Two instances of the application run behind a load balancer. Which of your fixes still work,
+ and which assumptions break?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can say what a cache costs in correctness, not only what it saves in time
+- [ ] You can explain cache-aside, and how it differs from write-through
+- [ ] You can name data you would never cache, and say why
+- [ ] You can say what `sync = true` does on Redis, and what it costs with the locking writer
+
+---
+
+## Questions to Ask Afterwards
+
+Answer out loud, in full sentences, before reading the answer in brackets.
+
+- How does `@Cacheable` work? (Spring wraps the bean in a proxy. Before the method runs, the proxy
+ computes a key from the arguments and asks the cache. On a hit it returns the cached value and the
+ method does not run at all. On a miss it runs the method and stores the result. Nothing happens
+ without `@EnableCaching`, and nothing happens when the method is called from inside the same
+ object.)
+- What does Redis hold for `@Cacheable("products")` on `findById(1)`? (A string key `products::1`:
+ the cache name, two colons, the key. The value is whatever the value serializer produced. With
+ Spring Boot's defaults that is Java serialization: the class must be `Serializable`, the bytes
+ are unreadable, other languages cannot read them, and renaming or changing the class breaks the
+ entries already stored. Configure JSON.)
+- A user changes a price and the shop still shows the old one. Why? (The cache is a copy. Nothing
+ told it that the original changed. Remove the entry when you change the data (`@CacheEvict`), or
+ write the new value (`@CachePut`). And give every entry a TTL, for the changes your code never
+ sees: a SQL script, another service, a missed eviction.)
+- `@CacheEvict` or `@CachePut`? (Evict by default. It is simple and the next read loads the
+ current value. `@CachePut` saves that one slow read, but it stores what the update method
+ returned, which must be exactly what a read would return, and two concurrent updates can write
+ to the cache in a different order than they committed, leaving the older value cached.)
+- When must the eviction happen, before or after the commit? (After. If you evict first, a reader
+ can miss the cache, read the database before your commit, still see the old value, and put it
+ back in the cache, where it stays until the TTL. Even after the commit there is a smaller window:
+ a reader that loaded the old value just before the commit and writes it just after your
+ eviction. TTLs bound that window.)
+- Why does `@Cacheable` do nothing when another method in the same class calls it? (The annotation
+ works through the proxy around the bean. `this.findById()` is a plain Java call on the object
+ inside the proxy, so no caching code runs. Call it from another bean, inject the proxy, or use
+ AspectJ weaving. The same is true for `@Transactional` and `@Async`.)
+- What is a cache stampede? (A popular entry expires and many requests miss at the same moment.
+ All of them go to the slow source for the same value, which can overload the database exactly
+ when traffic is highest. Fixes: let one request load while the others wait (a lock, or
+ `sync = true` on a cache that honours it), refresh hot entries before they expire, and add random
+ jitter to TTLs so many entries do not expire together.)
+- Does `@Cacheable(sync = true)` fix it on Redis? (Only with a locking cache writer. `sync = true`
+ calls `Cache.get(key, loader)`, and Spring Data Redis's default writer does not lock, so every
+ request still loads. With `RedisCacheWriter` in locking mode the lock is a key in Redis, so it
+ works across instances, but it locks the whole cache, not one key: while one product loads,
+ reads of every other product in that cache wait too. And the lock needs a timeout, or a crashed
+ instance blocks the cache for ever.)
+- What if Redis is down? (By default every cache operation throws, so every request fails, even
+ though the data is right there in the database. A `CacheErrorHandler` that logs and carries on
+ turns a cache failure into a miss: the application gets slower and keeps working. Then check the
+ database can take the full load without a cache, and that a missed eviction cannot leave a stale
+ value behind when Redis returns. That is one more reason for a TTL.)
+- What would you not cache? (Anything where a stale answer causes real damage: an account balance,
+ the stock checked when an order is placed, permissions. Anything per user, unless the user is
+ part of the key and you are sure about it: a key that forgets the user shows one customer's data
+ to another. And anything that is cheap to compute anyway.)
+- Cache-aside or write-through? (Cache-aside, which is what `@Cacheable` does: the application
+ reads the cache, and on a miss loads from the database and fills the cache. Writes go to the
+ database and invalidate the cache. Write-through writes every change to the cache and the
+ database together, so reads are always warm, at the cost of writing data nobody may read. Most
+ Spring applications use cache-aside with eviction.)
+- Local cache or Redis? (A local cache, such as Caffeine, is faster and needs no network, but every
+ instance has its own copy: an eviction on one instance does not reach the others. Redis is
+ shared, so an eviction is seen by everyone, at the cost of a network call and one more thing that
+ can be down. Many systems use both: a short local cache in front of Redis.)
+
+## Tips for Interviewers
+
+- The most common weak answer is "I would add `@Cacheable`". Ask what is stored, under which key,
+ for how long, and what happens on an update. Most candidates have never looked inside Redis.
+- Ask the candidate to predict the result of `./demo --scenario update` after Task 2, before
+ running it. A strong candidate says "stale" without running anything.
+- In Task 4, ask when the eviction happens relative to the commit. A candidate who says "it does
+ not matter" should be shown `beforeInvocation = true` failing the ordering check while the demo
+ says OK.
+- In Task 5, a candidate who caches the whole basket under its list of ids has hidden the bug, not
+ fixed it. Ask what happens to that entry when one product's price changes.
+- In Task 7, the textbook answer (`sync = true`) does not work on Redis's default writer. Ask the
+ candidate how they would find that out. "Run it and count the calls" is the answer.
+- For senior candidates: per-key locking instead of a cache-wide lock, refresh-ahead and
+ probabilistic early expiration, TTL jitter, caching nulls to stop requests for ids that do not
+ exist (and what it costs), versioned keys so a deploy that changes the JSON does not read old
+ entries, and what the cache does during a Redis failover.
diff --git a/java/concepts/junior-mid/12-caching-with-redis/README.md b/java/concepts/junior-mid/12-caching-with-redis/README.md
new file mode 100644
index 0000000..e68c839
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/README.md
@@ -0,0 +1,176 @@
+# Caching with Redis — @Cacheable, Stale Data and the Stampede
+
+> **In `start/`, `./check` FAILS on purpose: 13 of 28 checks pass.** That is the exercise, not a
+> broken checkout. Tasks 2, 4, 5, 6, 7 and 8 turn the other 15 green. Some checks of Tasks 4 and 8
+> pass at the start only because nothing is cached yet: adding the cache in Task 2 turns them red.
+> That is part of the lesson.
+
+A shop's product page is slow: loading one product takes 200 ms, because it is an expensive query
+or a call to another service. Every visitor pays for it, every time. Everybody's first answer is
+"put a cache in front of it". This project lets you do exactly that with Spring and Redis, and then
+watch the five things that go wrong next: a price that does not change after an update, a cache
+that one endpoint silently skips, entries that live for ever, a hot key that expires and sends
+every request to the slow source at once, and a Redis outage that takes the whole shop down.
+
+It answers the interview questions students most often get wrong:
+
+- "How does `@Cacheable` work? What is stored in Redis, under which key?"
+- "You update a row and users still see the old value. Why, and how do you fix it?"
+- "`@CacheEvict` or `@CachePut`?"
+- "Why does `@Cacheable` do nothing when I call the method from the same class?"
+- "What is a cache stampede, and does `sync = true` fix it?"
+- "Redis goes down. Does your application go down with it?"
+
+## Tech Stack
+
+- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate), Spring Data Redis (Lettuce)
+- **PostgreSQL 17** and **Redis 8** in Docker
+- JUnit 5, AssertJ, Testcontainers
+
+## What you need
+
+- JDK 25
+- Docker, running
+
+You do not need `redis-cli` or `psql`: the tools below talk to Redis and Postgres from Java.
+
+## Getting Started
+
+Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see
+`./demo` (same for `inspect` and `check`).
+
+```bash
+cd start
+docker compose up -d # Postgres on port 5451, Redis on port 6390
+./demo # 20 requests for the same product: how many reach the slow source?
+./check # 13 of 28 pass: that is your starting point
+```
+
+The first run downloads Maven and the dependencies, so it takes a minute or two.
+
+When you are finished: `docker compose down`.
+
+## The three tools
+
+### `./demo` — see what happens
+
+Starts the real application, sends requests at it over HTTP and counts how many of them had to call
+the slow source. Every run starts from a clean state: prices reset, Redis emptied. Ends with a
+`RESULT` line.
+
+```
+./demo 20 requests for product 1, one after the other
+./demo --scenario update read a product, change its price, read it again
+./demo --scenario basket the basket page, which shows products 1, 2 and 3
+./demo --scenario stampede a cached product expires and 20 requests arrive at once
+./demo --scenario redis-down the application cannot reach Redis
+./demo --requests 50 --delay-ms 500 more requests, a slower source
+./demo --requests 1 --ttl 15 cache with a 15 second TTL (watch it with ./inspect --watch)
+./demo --help
+```
+
+### `./inspect` — look inside Redis
+
+Lists every key in Redis with its TTL and its value, byte for byte, then puts each product row from
+Postgres next to its cached copy and says whether they agree (`same` or `STALE`). Also shows the
+last price changes. `./inspect --watch` refreshes every second for a minute.
+
+### `./check` — are the acceptance criteria met?
+
+`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything.
+`./mvnw verify` runs the same tests the usual Maven way.
+
+The tests are the acceptance criteria. **Never edit, delete or disable a test.** They start the
+application against a real Postgres and a real Redis (Testcontainers), call it over HTTP, and count
+how many times the slow source was called. Concurrency is forced with latches, never left to luck,
+and no test measures time.
+
+## The code
+
+```
+start/src/main/java/com/amigoscode/caching/
+├── cache/
+│ └── CacheConfig.java switching caching on and configuring Redis. Tasks 2, 6, 7 and 8
+├── product/
+│ ├── ProductController.java GET /api/products/{id}, GET /api/products?ids=..., PUT .../price
+│ ├── ProductService.java what gets cached and evicted. Tasks 2, 4, 5 and 7
+│ ├── SlowProductSource.java the slow part: 200 ms, then a read from Postgres. Nothing to change
+│ ├── ProductView.java what the API returns and what gets cached
+│ └── JdbcPriceHistory.java writes down every price change, in the same transaction
+└── demo/ the demo and inspect tools. Nothing to change here
+```
+
+The endpoints:
+
+| Endpoint | What it is |
+|---|---|
+| `GET /api/products/{id}` | The product page |
+| `GET /api/products?ids=1,2,3` | The basket page: several products, in the order asked for |
+| `PUT /api/products/{id}/price` with `{"price": 79.00}` | A price change from the back office |
+
+## Two ways to work
+
+- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and
+ hints for each task. Use this if you want to work it out yourself.
+- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same nine tasks, step by step, with the output you
+ should see and an explanation of why. Use this to learn the concept, or when you are stuck.
+
+Both files use the same task numbers.
+
+| Task | What you do | Checked by |
+|---|---|---|
+| 1 | See every request pay for the slow source | you answer questions |
+| 2 | Cache products in Redis, as JSON | `./check 2` |
+| 3 | Inspect the cache, and watch it go stale | you answer questions |
+| 4 | Fix the stale price after an update | `./check 4` |
+| 5 | Fix the cache that the basket skips (self-invocation) | `./check 5` |
+| 6 | Give cached products a TTL | `./check 6` |
+| 7 | Fix the cache stampede | `./check 7` |
+| 8 | Keep the shop up when Redis is down | `./check 8` |
+| 9 | Compare, and decide what to cache | you answer questions |
+
+## Solution
+
+`solution/` is the same project with every task done: `cd solution && ./check` prints 28 of 28.
+
+To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`).
+
+
+Spoiler: the problems and the fixes
+
+**Caching (Task 2).** `@EnableCaching`, then `@Cacheable(cacheNames = "products", key = "#productId")`
+on `findById`. Spring Boot sees Redis and builds a `RedisCacheManager`. Its default stores values
+with Java serialization: `ProductView` must be `Serializable`, and Redis holds 447 unreadable bytes.
+A `RedisCacheManagerBuilderCustomizer` gives the `products` cache a JSON serializer instead: 51
+bytes, `{"id":1,"name":"Mechanical keyboard","price":89.00}`, under the key `products::1`.
+
+**Stale data (Task 4).** `PUT` changes the database and nothing tells the cache. `@CacheEvict` on
+`changePrice` removes the entry, and the cache advice runs outside the transaction, so it happens
+after the commit. Evicting before the commit (`beforeInvocation = true`) lets a reader put the old
+price straight back. `@CachePut` also works, with its own race between two writers.
+
+**Self-invocation (Task 5).** The basket calls `this.findById(...)`. The call never leaves the
+object, so it never goes through the Spring proxy, so `@Cacheable` does not run. The same trap as
+`@Transactional` (see [`../01-transactional`](../01-transactional)). Fix: call `findById` from
+another bean.
+
+**TTL (Task 6).** Entries live for ever by default. `.entryTtl(...)` in the cache configuration,
+from `catalogue.cache.products-ttl`. The TTL is also the safety net for every change that does not
+go through your `PUT`.
+
+**Stampede (Task 7).** `sync = true` is only a request to the cache. Spring Data Redis's default
+cache writer does not lock, so all 20 requests still load. A locking cache writer takes a lock key
+in Redis (`products~lock`), which works across instances, but it locks the whole cache, not one
+key, and it must have a timeout.
+
+**Redis down (Task 8).** Every cache read fails, so every request is a 500. A `CacheErrorHandler`
+(`LoggingCacheErrorHandler`) logs the failure and treats it as a miss. The shop is slower, not down.
+
+| | `@CacheEvict` | `@CachePut` |
+|---|---|---|
+| After an update | Removes the entry; the next read loads it | Writes the new value straight away |
+| Next read | One slow load | Fast |
+| Risk | A slow reader can put an old value back | Two concurrent writers can leave the older value |
+| Use it when | Almost always: it is the safe default | The method returns exactly what a read would return, and reads right after a write matter |
+
+
diff --git a/java/concepts/junior-mid/12-caching-with-redis/TASKS_GUIDED.md b/java/concepts/junior-mid/12-caching-with-redis/TASKS_GUIDED.md
new file mode 100644
index 0000000..2454c43
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/TASKS_GUIDED.md
@@ -0,0 +1,898 @@
+# Guided Tasks — Caching with Redis
+
+The same nine tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to
+run, the output you should see, why it happens, and the change to make.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+Timings will differ on your machine, and so will the TTLs you see in `./inspect`. The number of
+calls to the slow source and the `RESULT` line should match.
+
+**Before you start**
+
+```bash
+cd start
+docker compose up -d
+```
+
+---
+
+## Task 1: See Every Request Pay for the Slow Source
+
+No code in this task. You are collecting evidence.
+
+### Run it
+
+```bash
+./demo
+```
+
+```
+Scenario: repeat | requests: 20 | slow source: 200 ms
+The same product page is opened 20 times, one request after the other.
+
+ Request 1 GET /api/products/1 <- 200 price 89.00 331 ms slow source called
+ Request 2 GET /api/products/1 <- 200 price 89.00 210 ms slow source called
+ Request 3 GET /api/products/1 <- 200 price 89.00 211 ms slow source called
+ Request 4 GET /api/products/1 <- 200 price 89.00 224 ms slow source called
+ Request 5 GET /api/products/1 <- 200 price 89.00 207 ms slow source called
+ ...
+ Request 20 GET /api/products/1 <- 200 price 89.00 211 ms slow source called
+
+Requests: 20
+Calls to the slow source: 20
+Time taken: 4328 ms (216 ms per request)
+
+RESULT: NO CACHE. 20 requests, 20 calls to the slow source: every request paid the full 200 ms.
+```
+
+Twenty requests for the same product, with the same answer every time, and every one of them paid
+the full 200 ms. `SlowProductSource` stands for an expensive query (a product joined with prices,
+stock and reviews) or a call to another service. `ProductService.findById` calls it every time.
+
+### Look at Redis
+
+```bash
+./inspect
+```
+
+```
+REDIS localhost:6390 (0 keys)
+ empty. Nothing has been cached.
+
+POSTGRES NEXT TO THE CACHE
+ id name price_in_db cached_as price_in_cache verdict
+ -- ------------------- ----------- --------- -------------- ----------
+ 1 Mechanical keyboard 89.00 not cached
+ 2 4K monitor 329.00 not cached
+ 3 USB-C dock 149.00 not cached
+```
+
+Redis is running and Spring Data Redis is on the classpath, and nothing uses them. Having Redis
+available caches nothing.
+
+### The basket
+
+```bash
+./demo --scenario basket
+```
+
+```
+ Basket 1 GET /api/products?ids=1,2,3 <- 200 price 89.00, 329.00, 149.00 636 ms slow source called 3 times
+ ...
+Calls to the slow source, basket (5 requests x 3 products): 15
+
+RESULT: NOT CACHED. Nothing is cached yet: the product page and the basket call the slow source for every product, every time.
+```
+
+Three products, three slow calls, 600 ms per basket. Keep this number: it comes back in Task 5.
+
+### Is this data safe to cache?
+
+A product's name and price change a few times a day and are read thousands of times an hour. The
+same answer, computed again and again: that is what a cache is for. What a cache costs you is that
+for a while the answer can be **out of date**. The rest of this project is about that cost.
+
+---
+
+## Task 2: Cache Products in Redis, as JSON
+
+### Step 1: switch caching on
+
+In `CacheConfig`, add `@EnableCaching`:
+
+```java
+@Configuration
+@EnableCaching
+public class CacheConfig {
+```
+
+Import `org.springframework.cache.annotation.EnableCaching`. Without it, every cache annotation in
+the project is ignored, silently.
+
+In `ProductService`, annotate `findById`:
+
+```java
+@Cacheable(cacheNames = CacheConfig.PRODUCTS, key = "#productId")
+public ProductView findById(long productId) {
+ return source.load(productId);
+}
+```
+
+Imports: `org.springframework.cache.annotation.Cacheable` and `com.amigoscode.caching.cache.CacheConfig`.
+`key = "#productId"` is what Spring would
+pick by itself for a method with one argument; writing it down makes the key obvious.
+
+You did not configure Redis anywhere. Spring Boot sees `@EnableCaching` and a
+`RedisConnectionFactory`, and builds a `RedisCacheManager`.
+
+### Look before you go on
+
+```bash
+./demo --requests 3
+```
+
+```
+ Request 1 GET /api/products/1 <- 500 Cannot serialize 281 ms slow source called
+ Request 2 GET /api/products/1 <- 500 Cannot serialize 208 ms slow source called
+ Request 3 GET /api/products/1 <- 500 Cannot serialize 213 ms slow source called
+
+RESULT: ERROR. 3 of 3 requests failed: 500 Cannot serialize
+ Cause: IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.amigoscode.caching.product.ProductView]
+```
+
+Worse than before: the slow source still runs, and then the request fails. The method worked; it
+is storing the result that failed. Spring Boot's `RedisCacheManager` stores values with **Java
+serialization** by default (`JdkSerializationRedisSerializer`), and Java serialization only
+accepts classes that implement `Serializable`.
+
+### Step 2: the quick fix
+
+Make `ProductView` serializable (import `java.io.Serializable`):
+
+```java
+public record ProductView(long id, String name, BigDecimal price) implements Serializable {
+```
+
+`./demo` now says `RESULT: OK. 20 requests, 1 call to the slow source.` Run `./inspect` to see
+what got stored:
+
+```
+REDIS localhost:6390 (1 key)
+ key ttl bytes value
+ ----------- ------------------ ----- ---------------------------------------------------------------------------
+ products::1 -1 (never expires) 447 \xac\xed\x00\x05sr\x00*com.amigoscode.caching.product.ProductView\x00\x0...
+
+POSTGRES NEXT TO THE CACHE
+ id name price_in_db cached_as price_in_cache verdict
+ -- ------------------- ----------- ----------- -------------- -------------------------------
+ 1 Mechanical keyboard 89.00 products::1 (not JSON) cannot tell: Java serialization
+```
+
+- **The key** is `products::1`: the cache name, two colons, the key. Readable.
+- **The value** is 447 bytes of Java serialization: `\xac\xed` is its magic number, followed by the
+ full class name. Nobody can read it during an incident, no other language can use it, and if you
+ rename `ProductView` or change its fields, every entry already in Redis fails to deserialize.
+- **The TTL** is `-1`: this entry never expires. Remember that for Task 6.
+
+```bash
+./check 2
+```
+
+```
+ [FAIL] Cache: the value in Redis is readable JSON with the name and price, not Java serialization bytes
+ products::1 should be JSON like {"id":1,"name":"Mechanical keyboard","price":89.00}
+ but Redis holds 447 bytes: \xac\xed\x00\x05sr\x00*com.amigoscode.caching.product.ProductView\x00\x00\x00\x00\x00\x00\...
+ 5 of 6 pass
+```
+
+### Step 3: JSON
+
+Remove `implements Serializable` again: it is not needed any more. Then give the `products` cache
+its own configuration in `CacheConfig`:
+
+```java
+@Configuration
+@EnableCaching
+public class CacheConfig {
+
+ public static final String PRODUCTS = "products";
+
+ @Bean
+ RedisCacheManagerBuilderCustomizer productsCache() {
+ return builder -> builder.withCacheConfiguration(PRODUCTS, RedisCacheConfiguration.defaultCacheConfig()
+ .serializeValuesWith(SerializationPair.fromSerializer(new JacksonJsonRedisSerializer<>(ProductView.class))));
+ }
+}
+```
+
+Imports: `RedisCacheManagerBuilderCustomizer` (from `org.springframework.boot.cache.autoconfigure`),
+`Bean`, `RedisCacheConfiguration`, `JacksonJsonRedisSerializer`,
+`RedisSerializationContext.SerializationPair` and `ProductView`. Your IDE finds them.
+
+- Spring Boot still builds the `RedisCacheManager`. The customizer bean changes the builder before
+ it does, and `withCacheConfiguration` gives one cache its own settings.
+- `JacksonJsonRedisSerializer` (Spring Data Redis 4, Jackson 3) reads and writes one known type.
+ `GenericJacksonJsonRedisSerializer` stores the class name inside the JSON so one cache can hold
+ any type; typed is simpler and does not let the JSON decide which class gets created.
+
+### After
+
+`./demo`, then `./inspect`:
+
+```
+RESULT: OK. 20 requests, 1 call to the slow source. The other 19 were answered from Redis.
+
+REDIS localhost:6390 (1 key)
+ key ttl bytes value
+ ----------- ------------------ ----- ---------------------------------------------------
+ products::1 -1 (never expires) 51 {"id":1,"name":"Mechanical keyboard","price":89.00}
+```
+
+51 readable bytes instead of 447. Request 1 still took the full 200 ms and more: a cache never
+makes the first request faster. Requests 2 to 20 took about 5 ms.
+
+### Check, and see what you broke
+
+```bash
+./check
+```
+
+```
+Task 2: Cache products in Redis, as JSON
+ 6 of 6 pass
+Task 4: Fix the stale price after an update
+ ...
+ [FAIL] Update: after PUT a new price, GET returns the new price
+ Assertion condition defined as a Lambda expression in com.amigoscode.caching.StaleDataIT [price returned by GET]
+ expected: 79.00
+ but was: 89.00 within 3 seconds.
+ ...
+ 1 of 4 pass
+...
+Task 8: Keep the shop up when Redis is down
+ [FAIL] Redis down: GET still returns the product, loaded from the slow source, instead of a 500
+ [status (body: {"timestamp":"2026-11-27T14:48:29.374Z","status":500,"error":"Internal Server Error","path":"/api/products/1"})]
+ expected: 200
+ but was: 500
+ 1 of 2 pass
+```
+
+Before your change those checks were green. Nothing was cached, so nothing could be stale, and
+nothing depended on Redis. **Adding a cache added two new ways to be wrong.** Task 3 looks at the
+first one.
+
+### What about a product that does not exist?
+
+`GET /api/products/999` is a 404 every time, and each time it calls the slow source:
+`CacheIT.anUnknownProductIsNotCached` checks exactly that. The source throws
+`ProductNotFoundException`, and **exceptions are never cached**.
+
+If a method *returned* `null` instead, `defaultCacheConfig()` caches it: tried here, Redis held a
+64-byte Java-serialized `org.springframework.cache.support.NullValue` under `products::999`, even
+with the JSON serializer. That keeps requests for ids that do not exist away from the database, and
+a product created a minute later stays "not found" until the entry expires.
+`.disableCachingNullValues()` turns it off; a `null` result then fails with `Cache 'products' does
+not allow 'null' values; Avoid storing null via '@Cacheable(unless="#result == null")'`.
+
+---
+
+## Task 3: Inspect the Cache, and Watch It Go Stale
+
+### Step 1: change a price
+
+```bash
+./demo --scenario update
+```
+
+```
+ Step 1 GET /api/products/1 <- 200 price 89.00 327 ms slow source called
+ Step 2 GET /api/products/1 <- 200 price 89.00 22 ms slow source not called
+ Step 3 PUT /api/products/1/price 79.00 <- 200 price 79.00 31 ms slow source not called
+ Step 4 GET /api/products/1 <- 200 price 89.00 3 ms slow source not called
+
+Price in the database: 79.00
+Price GET returned: 89.00
+
+RESULT: STALE. The price was changed to 79.00, but GET still returns 89.00 from the cache.
+```
+
+The `PUT` worked: it answered 79.00, and the database says 79.00. The next `GET` answered 89.00,
+in 3 ms, without asking anybody.
+
+### Step 2: both copies, side by side
+
+```bash
+./inspect
+```
+
+```
+REDIS localhost:6390 (1 key)
+ key ttl bytes value
+ ----------- ------------------ ----- ---------------------------------------------------
+ products::1 -1 (never expires) 51 {"id":1,"name":"Mechanical keyboard","price":89.00}
+
+POSTGRES NEXT TO THE CACHE
+ id name price_in_db cached_as price_in_cache verdict
+ -- ------------------- ----------- ----------- -------------- ----------
+ 1 Mechanical keyboard 79.00 products::1 89.00 STALE
+
+PRICE CHANGES (newest first)
+ product_id old_price new_price changed_at
+ ---------- --------- --------- ------------
+ 1 89.00 79.00 14:49:47.460
+```
+
+### Steps 3 and 4: why
+
+A cache is a **copy**. `changePrice` updates the original, in Postgres, and writes the change into
+`price_change`. Nothing tells the copy. `@Cacheable` only decides what happens on a read; it has no
+idea that some other method changes the same data.
+
+And the copy has `ttl -1`. Without a code change, this shop shows 89.00 **for ever**, or until
+somebody restarts Redis.
+
+### Step 5: the change you cannot see
+
+`update product set price = 70.00 where id = 2`, run by hand or by a nightly import, never goes
+through `changePrice`. No annotation on any method can react to it. That is why Task 4 alone is not
+enough, and Task 6 (a TTL) is not optional: the TTL is the upper bound on how long *any* change,
+including the ones your code never sees, can stay invisible.
+
+---
+
+## Task 4: Fix the Stale Price After an Update
+
+**The idea:** when the price changes, remove the cached copy. The next read loads the new price.
+
+### The trap first
+
+In `ProductService`, add an eviction to `changePrice`, removing the entry *before* the method runs:
+
+```java
+@Transactional
+@CacheEvict(cacheNames = CacheConfig.PRODUCTS, key = "#productId", beforeInvocation = true)
+public ProductView changePrice(long productId, BigDecimal newPrice) {
+```
+
+Import `org.springframework.cache.annotation.CacheEvict`. Run the demo: it says
+`RESULT: OK. GET returns the new price, 79.00.` Now run the check:
+
+```bash
+./check 4
+```
+
+```
+ [FAIL] Update: the entry is removed after the new price is committed, so a GET in between cannot put the old price back
+ Assertion condition defined as a Lambda expression in com.amigoscode.caching.StaleDataIT [price returned by GET after the PUT has finished]
+ expected: 79.00
+ but was: 89.00 within 3 seconds.
+ 3 of 4 pass
+```
+
+That test stops the `PUT` transaction just before it commits (`ControllablePriceHistory`) and sends
+a `GET` in that moment:
+
+| Time | PUT (changePrice) | GET in between | Redis | Postgres (committed) |
+|---|---|---|---|---|
+| 1 | evicts `products::1` | | empty | 89.00 |
+| 2 | changes the price, not committed yet | | empty | 89.00 |
+| 3 | | misses the cache, loads, reads **89.00** | | 89.00 |
+| 4 | | stores 89.00 | **89.00** | 89.00 |
+| 5 | commits | | 89.00 | 79.00 |
+
+The old price is back in the cache, and nothing will remove it. The demo cannot show this because
+nothing else is reading at that moment. In production something always is.
+
+### The fix
+
+Remove `beforeInvocation = true`:
+
+```java
+@Transactional
+@CacheEvict(cacheNames = CacheConfig.PRODUCTS, key = "#productId")
+public ProductView changePrice(long productId, BigDecimal newPrice) {
+```
+
+The proxy now runs two pieces of advice around this method, the cache's and the transaction's. The
+cache advice is the outer one here, so the order is: transaction starts, method runs,
+**transaction commits**, then the entry is evicted. You can see it with
+`--logging.level.org.springframework.cache=TRACE` and the `JpaTransactionManager` at `DEBUG`:
+`Committing JPA transaction` is logged before `Invalidating cache key [1]`. That order is what
+`StaleDataIT.evictionHappensAfterTheCommit` pins down, so it will tell you if it ever changes.
+
+Do not use `allEntries = true`: it empties the whole cache for one price change.
+`StaleDataIT.otherProductsStayCached` fails with `[Redis still has products::2]`.
+
+### After
+
+```bash
+./demo --scenario update
+./inspect
+```
+
+```
+ Step 3 PUT /api/products/1/price 79.00 <- 200 price 79.00 36 ms slow source not called
+ Step 4 GET /api/products/1 <- 200 price 79.00 211 ms slow source called
+
+RESULT: OK. GET returns the new price, 79.00.
+
+ products::1 -1 (never expires) 51 {"id":1,"name":"Mechanical keyboard","price":79.00}
+ 1 Mechanical keyboard 79.00 products::1 79.00 same
+```
+
+Step 4 is slow again: the first read after an eviction pays for the load. That is the price of
+evicting.
+
+```bash
+./check 4
+```
+
+4 of 4 pass.
+
+### Evict or put?
+
+`@CachePut(cacheNames = CacheConfig.PRODUCTS, key = "#productId")` on `changePrice` also passes
+every check: it stores the `ProductView` the method returns, so step 4 would be fast. Two costs:
+
+- The method's return value must be exactly what `findById` would return. Here it is. When the
+ update returns a slimmer object, or the read adds data from elsewhere, the cache is now wrong.
+- Two concurrent updates can commit in one order and write to the cache in the other. The database
+ ends with the second price and the cache with the first, until the TTL.
+
+Eviction has a smaller version of that second problem, and this project explains it rather than
+demonstrates it: a reader that loaded the old row *just before* your commit, and stores it *just
+after* your eviction, puts the old price back. It needs a slow reader and bad timing, and the TTL
+caps how long it lasts. Evict is the safe default. Use put when reads right after a write matter
+and you control both methods.
+
+Why do the tests wait up to 3 seconds for the new price? Spring Data Redis 4 sends evictions to
+Redis in the background by default. In 300 PUT-then-GET round trips no GET here saw the old price,
+but a test should not bet on it. `writer.immediateWrites()` on the cache writer (Task 7) makes them
+synchronous.
+
+---
+
+## Task 5: Fix the Cache That the Basket Skips
+
+### See it
+
+```bash
+./demo --scenario basket
+```
+
+```
+ Product page GET /api/products/1 <- 200 price 89.00 326 ms slow source called
+ Product page GET /api/products/1 <- 200 price 89.00 25 ms slow source not called
+ Basket 1 GET /api/products?ids=1,2,3 <- 200 price 89.00, 329.00, 149.00 619 ms slow source called 3 times
+ Basket 2 GET /api/products?ids=1,2,3 <- 200 price 89.00, 329.00, 149.00 620 ms slow source called 3 times
+ ...
+Calls to the slow source, product page (2 requests): 1
+Calls to the slow source, basket (5 requests x 3 products): 15
+
+RESULT: NOT CACHED. The basket called the slow source 15 times for 3 products. Product 1 was already in the cache, and the basket did not even look.
+```
+
+The product page is cached. The basket asks for the same products through the same method, and
+every call reaches the slow source.
+
+### Why
+
+```java
+public List findAll(List productIds) {
+ return productIds.stream().map(this::findById).toList();
+}
+```
+
+The annotation does nothing inside `findById` itself. Spring creates a **proxy**, a generated
+subclass of `ProductService`, and gives it to every bean that asks for a `ProductService`. The
+proxy's `findById` checks the cache, then calls the real one.
+
+```
+ProductController --> [proxy: cache check] --> ProductService.findAll --> this.findById
+ (plain Java call:
+ no proxy, no cache)
+```
+
+The controller calls `findAll` through the proxy, but `findAll` has no annotation. Inside it,
+`this` is the real object, not the proxy, so `this.findById` is a plain method call. No cache.
+This is the same bug as `@Transactional` on a method called from its own class: see
+[`../01-transactional`](../01-transactional).
+
+### The fix
+
+Make the call come from outside the bean. The controller is the natural caller: let it call
+`findById` for each id, through the proxy it was given. In `ProductController`:
+
+```java
+@GetMapping(params = "ids")
+public List basket(@RequestParam List ids) {
+ if (ids.isEmpty() || ids.size() > 50) {
+ throw new InvalidRequestException("ids must list 1 to 50 product ids");
+ }
+ return ids.stream().map(productService::findById).toList();
+}
+```
+
+Then delete `findAll` from `ProductService` (and its `java.util.List` import), so nobody calls it
+by mistake.
+
+Other fixes that work: a separate `BasketService` bean (the better home once the basket has its
+own logic; here it would change the controller's constructor, which the baseline tests build), or
+keeping `findAll` and injecting the proxy into `ProductService` itself: a field
+`@Autowired @Lazy private ProductService self;` and `self::findById` in the loop. That passes every
+check too, and it reads as a workaround, because it is one. What does **not** work is
+`@Cacheable` on `findAll`: that caches the list under the key `[1, 2, 3]`, a basket of `[1, 2]`
+misses it, and a price change on product 1 has to evict every basket that contains it.
+
+### After
+
+```bash
+./demo --scenario basket
+```
+
+```
+ Basket 1 GET /api/products?ids=1,2,3 <- 200 price 89.00, 329.00, 149.00 428 ms slow source called 2 times
+ Basket 2 GET /api/products?ids=1,2,3 <- 200 price 89.00, 329.00, 149.00 4 ms slow source not called
+ ...
+RESULT: OK. The basket called the slow source 2 times: only for the products that were not cached yet.
+```
+
+Basket 1 loaded products 2 and 3 only: product 1 came from the product page's entry. `./check 5`:
+3 of 3 pass. Run `./check` too: the baseline must still be green.
+
+---
+
+## Task 6: Give Cached Products a TTL
+
+### The fix
+
+In `CacheConfig`, read the TTL from the configuration and give it to the `products` cache:
+
+```java
+@Bean
+RedisCacheManagerBuilderCustomizer productsCache(@Value("${catalogue.cache.products-ttl}") Duration ttl) {
+ return builder -> builder.withCacheConfiguration(PRODUCTS, RedisCacheConfiguration.defaultCacheConfig()
+ .serializeValuesWith(SerializationPair.fromSerializer(new JacksonJsonRedisSerializer<>(ProductView.class)))
+ .entryTtl(ttl));
+}
+```
+
+Imports: `java.time.Duration` and `org.springframework.beans.factory.annotation.Value`.
+`application.properties` already has `catalogue.cache.products-ttl=10m`; Spring turns `10m` into a
+`Duration`. (You can now delete "Nothing reads this yet." from the comment above it.)
+
+### Why not `spring.cache.redis.time-to-live`?
+
+It only applies to the configuration Spring Boot builds by default. Your `products` cache starts
+from `RedisCacheConfiguration.defaultCacheConfig()`, so no `spring.cache.redis.*` property reaches
+it. Tried here with the property at 30 seconds: `./inspect` still showed `-1 (never expires)`, and
+without your customizer the same property did apply.
+
+### After
+
+`./demo --requests 2`, then `./inspect`:
+
+```
+ key ttl bytes value
+ ----------- ----- ----- ---------------------------------------------------
+ products::1 597 s 51 {"id":1,"name":"Mechanical keyboard","price":89.00}
+```
+
+`./check 6`: 3 of 3 pass. `ShortTtlIT` starts the application with a 2 second TTL, changes the
+price straight in the database, waits until Redis has dropped the key (no fixed sleep), and checks
+that the next `GET` sees the new price.
+
+### Watch it expire
+
+```bash
+./demo --requests 1 --ttl 15
+./inspect --watch
+```
+
+The `ttl` column counts down, and when it reaches 0 the key disappears. Redis removed it; nothing in
+the application did. The next request pays for the slow source again.
+
+How long should it be? As long as you can live with the answer being wrong: a business decision,
+not a technical one. It also sets the load: one slow call per product per TTL, plus one per
+eviction.
+
+---
+
+## Task 7: Fix the Cache Stampede
+
+### See it
+
+```bash
+./demo --scenario stampede
+```
+
+```
+Products 1 and 2 are read once, to fill the cache. Then the entry for product 1 expires, and 20 requests for it arrive at the same moment.
+
+ products::1 removed from Redis, as if its TTL had just run out.
+
+Requests for product 1: 20, all at the same moment
+Slow source calls for product 1: 20
+Failed requests: 0
+Time taken: 233 ms
+Meanwhile, GET /api/products/2: 23 ms
+
+RESULT: STAMPEDE. 20 requests missed the cache together and 20 of them called the slow source for the same product.
+```
+
+Every request looked in Redis before any of them had finished loading, so all 20 missed, and all 20
+ran the same expensive query. With a real hot product it is hundreds, all hitting the database at
+the moment traffic is highest.
+
+### Step 1: the textbook answer
+
+```java
+@Cacheable(cacheNames = CacheConfig.PRODUCTS, key = "#productId", sync = true)
+public ProductView findById(long productId) {
+```
+
+```bash
+./demo --scenario stampede
+```
+
+```
+Slow source calls for product 1: 20
+
+RESULT: STAMPEDE. 20 requests missed the cache together and 20 of them called the slow source for the same product.
+```
+
+Nothing changed. `sync = true` does not lock anything itself: it makes Spring call
+`Cache.get(key, valueLoader)` instead of "get, and on a miss run the method and put". Whether only
+one caller runs the loader is up to the cache. Spring Data Redis's `RedisCache` passes it to its
+`RedisCacheWriter`, and the writer Spring Boot uses by default is the **non-locking** one: it reads,
+misses, loads and stores, for every caller.
+
+`./check 7` still shows `expected: 1 but was: 10`.
+
+### Step 2: a locking cache writer
+
+Give the cache manager a writer that locks. In `CacheConfig`, the customizer also needs the
+connection factory:
+
+```java
+@Bean
+RedisCacheManagerBuilderCustomizer productsCache(RedisConnectionFactory connectionFactory,
+ @Value("${catalogue.cache.products-ttl}") Duration ttl) {
+ return builder -> builder
+ .cacheWriter(RedisCacheWriter.lockingRedisCacheWriter(connectionFactory))
+ .withCacheConfiguration(PRODUCTS, RedisCacheConfiguration.defaultCacheConfig()
+ .serializeValuesWith(SerializationPair.fromSerializer(new JacksonJsonRedisSerializer<>(ProductView.class)))
+ .entryTtl(ttl));
+}
+```
+
+Imports: `RedisCacheWriter` (`org.springframework.data.redis.cache`) and `RedisConnectionFactory`.
+Then `./check 7`:
+
+```
+ [PASS] Stampede: 10 requests for a product that is not in the cache call the slow source once
+ [PASS] Stampede: while product 1 loads, the lock is a key in Redis (products~lock), so other instances wait for it too
+ [PASS] Stampede: all 10 requests get the product, none of them fails
+ [FAIL] Stampede: the lock has a TTL, so an instance that dies while loading cannot block the cache for ever
+ [TTL of products~lock in seconds (-1 means never, -2 that there is no lock key)]
+ Expecting actual:
+ -1L
+ to be greater than:
+ 0L
+ 3 of 4 pass
+```
+
+The stampede is gone. But the lock is a key in Redis that never expires: if this instance is killed
+in the middle of a load, `products~lock` stays, and every instance waits for it for ever.
+
+### Step 3: a lock that expires
+
+```java
+.cacheWriter(RedisCacheWriter.create(connectionFactory, writer -> writer
+ .enableLocking(lock -> lock.lockTimeout(TtlFunction.just(Duration.ofSeconds(10))))))
+```
+
+Import `org.springframework.data.redis.cache.RedisCacheWriter.TtlFunction`. `./check 7`: 4 of 4
+pass.
+
+### After
+
+```bash
+./demo --scenario stampede
+```
+
+```
+Requests for product 1: 20, all at the same moment
+Slow source calls for product 1: 1
+Failed requests: 0
+Time taken: 420 ms
+Meanwhile, GET /api/products/2: 175 ms
+
+RESULT: OK. 20 requests missed the cache together, 1 called the slow source, the others waited and read the result from Redis.
+```
+
+### What the lock really is
+
+Look at the last line before `RESULT`. Product 2 was in the cache the whole time, and it still
+waited for most of product 1's load (before the fix it took 23 ms). Now a slow load, with a second
+terminal open:
+
+```bash
+./demo --scenario stampede --delay-ms 10000 # terminal 1: takes about 40 seconds
+./inspect --watch # terminal 2, while it runs
+```
+
+```
+REDIS localhost:6390 (2 keys)
+ key ttl bytes value
+ ------------- ----- ----- -------------------------------------------
+ products::2 598 s 43 {"id":2,"name":"4K monitor","price":329.00}
+ products~lock 8 s 0
+```
+
+- The lock is **one key per cache**, `products~lock`, not one per product. While any product of
+ this cache is loading, every operation on the cache waits for it: reads of other products too.
+ Waiters poll for it every 50 ms (the default): 420 ms in total above, for a 200 ms load.
+- It lives in Redis, so a second instance of the application waits for it too. An in-memory cache
+ does the opposite: Spring's `ConcurrentMapCache` implements `sync = true` with
+ `ConcurrentHashMap.computeIfAbsent`, which waits per key, and only inside one JVM.
+- It has a TTL, and the TTL must be longer than a load. This load took as long as the lock's
+ 10 seconds, and terminal 1 ended with `Slow source calls for product 1: 2` and
+ `Meanwhile, GET /api/products/2: 10033 ms`: the lock expired, a second request took it and
+ loaded again, and a cached product waited ten seconds.
+
+So the locking writer fixes the stampede at a real price. When that price is too high, the other
+tools are: refresh popular entries before they expire, add random jitter to TTLs so they do not all
+expire together, or put a small local cache with per-key loading in front of Redis.
+
+---
+
+## Task 8: Keep the Shop Up When Redis Is Down
+
+### See it
+
+```bash
+./demo --scenario redis-down
+```
+
+```
+ Request 1 GET /api/products/1 <- 500 Unable to connect to Redis 203 ms slow source not called
+ Request 2 GET /api/products/1 <- 500 Unable to connect to Redis 6 ms slow source not called
+ ...
+RESULT: DOWN. Redis is not reachable, so 5 of 5 requests failed: 500 Unable to connect to Redis
+ Cause: ConnectException: Connection refused
+```
+
+The database is up. The product is right there. The shop is down because the copy is unavailable.
+
+### The fix
+
+Spring's cache abstraction sends every exception from the cache itself (not from your method) to a
+`CacheErrorHandler`. The default one rethrows. Spring ships `LoggingCacheErrorHandler`, which logs
+and carries on, and the caching code then behaves as if the cache had missed. In `CacheConfig`:
+
+```java
+@Configuration
+@EnableCaching
+public class CacheConfig implements CachingConfigurer {
+
+ // ... PRODUCTS and productsCache stay as they are
+
+ @Override
+ public CacheErrorHandler errorHandler() {
+ return new LoggingCacheErrorHandler();
+ }
+}
+```
+
+Imports: `org.springframework.cache.annotation.CachingConfigurer`,
+`org.springframework.cache.interceptor.CacheErrorHandler` and
+`org.springframework.cache.interceptor.LoggingCacheErrorHandler`.
+
+### After
+
+```bash
+./demo --scenario redis-down
+```
+
+```
+2026-11-27T14:53:28.622Z WARN 70777 --- [caching-with-redis] [o-auto-1-exec-2] o.s.c.i.LoggingCacheErrorHandler : Cache 'products' failed to get entry with key '1'
+ Request 1 GET /api/products/1 <- 200 price 89.00 483 ms slow source called
+ ...
+Requests: 5
+Failed requests: 0
+Calls to the slow source: 5
+
+RESULT: OK. Redis is not reachable, and all 5 requests were answered from the slow source instead.
+```
+
+`./check`: 28 passes and no failures.
+
+### What you traded
+
+- **Every request now reaches the slow source.** The shop is slower instead of down, which is only
+ better if the database can carry the whole load without a cache. Find that out before Redis goes
+ down, not while.
+- **The `PUT` worked even before your change.** Evictions are sent to Redis in the background
+ (Task 4), so a failed eviction is never seen by anybody. If Redis was only unreachable for a
+ moment, it comes back still holding the old price, until the TTL. One more reason Task 6 is not
+ optional.
+- **One gap remains, verified on this version of Spring.** With `sync = true` and Redis down, an
+ unknown product comes back as a 500 `Unable to connect to Redis` instead of a 404. Without
+ `sync = true` it is a 404. On that path Spring Framework 7.0.3 (the version Spring Boot 4.0.2
+ uses) reports the cache's exception, not your method's.
+
+---
+
+## Task 9: Compare, and Decide What to Cache
+
+### Step 1 and 2: the numbers
+
+One run of each scenario on a laptop, with the default 200 ms source. Yours will differ, the shape
+will not.
+
+| Scenario | `start/` | `solution/` |
+|---|---|---|
+| `./demo` (20 requests) | 20 calls, 4328 ms, `NO CACHE` | 1 call, 451 ms, `OK` |
+| `--scenario update` | `OK` (nothing cached) | `OK` |
+| `--scenario basket` (5 baskets) | 15 calls, `NOT CACHED` | 2 calls, `OK` |
+| `--scenario stampede` (20 at once) | 20 calls, `STAMPEDE` | 1 call, `OK`, product 2 waits |
+| `--scenario stampede --requests 100` | 100 calls, `STAMPEDE` | 1 call, `OK` |
+| `--scenario redis-down` | `OK` (Redis not used) | `OK`, 5 calls, one warning each |
+
+`start/` was correct the whole time, just slow. Every row where `solution/` says OK cost you code
+and a new way to be wrong, and you only found the stale price because you went looking.
+
+### Step 3: what can be wrong, and for how long
+
+- A price changed through the API: until the eviction, a few milliseconds.
+- A price changed anywhere else: up to the TTL, 10 minutes.
+- A reader that raced an update (Task 4): up to the TTL.
+- Redis unreachable during an update: up to the TTL after it comes back.
+
+The TTL is the real promise you make: "never more than 10 minutes out of date".
+
+### Step 4: what to cache
+
+| Data | Cache it? | Why |
+|---|---|---|
+| Product name and price on the product page | Yes, minutes | Read constantly, changed rarely, a few minutes out of date is acceptable |
+| The list of categories | Yes, longer | Almost never changes |
+| Stock on the product page ("only 3 left") | Short TTL, maybe | Approximate is fine for display |
+| Stock checked when an order is placed | No | It must be exact: read it from the database, inside the transaction that reserves it (see [`../07-locking`](../07-locking)) |
+| A customer's basket or account balance | No | Per user, changes often, and a wrong value is a real bug |
+| Anything per user or per permission | Only with the user in the key | A key without the user shows one customer's data to another |
+
+### Step 5: two instances, and the pattern you built
+
+Both instances share Redis, so an eviction on one is seen by the other, and the lock works across
+them. A local in-memory cache would give you neither. What you built is **cache-aside**: read the
+cache, on a miss load from the database and fill the cache, write to the database and evict.
+**Write-through** writes every change to the cache and the database together: reads are always
+warm, and you pay to keep data nobody may read. `@CachePut` is the step towards it.
+
+### How to say it in an interview
+
+> "I'd cache read-heavy data that can be a little out of date, like a product page, with
+> `@Cacheable` and Redis, cache-aside. I'd configure a JSON serializer, because Spring Boot's
+> default is Java serialization, and give every cache a TTL, because entries live for ever by
+> default and the TTL is the upper bound on staleness for changes my code never sees. On updates I
+> evict, after the commit, because evicting before lets a concurrent reader put the old value back;
+> `@CachePut` is an option when the update returns exactly what a read would. I'd watch out for
+> self-invocation, because the annotation only works through the Spring proxy. For hot keys I'd
+> think about stampedes: on Redis, `sync = true` only helps with a locking cache writer, and that
+> lock covers the whole cache and needs a timeout. And I'd add a `CacheErrorHandler`, so Redis being
+> down makes the application slower, not broken, after checking the database can take that load. I
+> would not cache balances, stock at checkout, or anything per user unless the user is in the key."
+
+Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of
+[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md).
+
+---
+
+## Clean up
+
+```bash
+docker compose down
+```
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/.mvn/jvm.config b/java/concepts/junior-mid/12-caching-with-redis/solution/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/12-caching-with-redis/solution/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/.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.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/check b/java/concepts/junior-mid/12-caching-with-redis/solution/check
new file mode 100755
index 0000000..8d362c5
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.caching.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/check.cmd b/java/concepts/junior-mid/12-caching-with-redis/solution/check.cmd
new file mode 100644
index 0000000..48286b1
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.caching.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/compose.yaml b/java/concepts/junior-mid/12-caching-with-redis/solution/compose.yaml
new file mode 100644
index 0000000..24030b7
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/compose.yaml
@@ -0,0 +1,28 @@
+# The project name is set here because the folder is called "solution" (or "start") in every
+# project of this repository: without it, "docker compose down" in another project would stop this one.
+name: caching-with-redis
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: caching-with-redis-postgres
+ environment:
+ POSTGRES_DB: catalogue
+ POSTGRES_USER: catalogue
+ POSTGRES_PASSWORD: catalogue
+ ports:
+ - "5451:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U catalogue -d catalogue"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
+ redis:
+ image: redis:8-alpine
+ container_name: caching-with-redis-redis
+ ports:
+ - "6390:6379"
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/demo b/java/concepts/junior-mid/12-caching-with-redis/solution/demo
new file mode 100755
index 0000000..6499539
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.caching.demo.Demo -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/demo.cmd b/java/concepts/junior-mid/12-caching-with-redis/solution/demo.cmd
new file mode 100644
index 0000000..0dbf2f4
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.caching.demo.Demo" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/inspect b/java/concepts/junior-mid/12-caching-with-redis/solution/inspect
new file mode 100755
index 0000000..22e3eb7
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.caching.demo.Inspect -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/inspect.cmd b/java/concepts/junior-mid/12-caching-with-redis/solution/inspect.cmd
new file mode 100644
index 0000000..2938c9c
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.caching.demo.Inspect" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/mvnw b/java/concepts/junior-mid/12-caching-with-redis/solution/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/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/java/concepts/junior-mid/12-caching-with-redis/solution/mvnw.cmd b/java/concepts/junior-mid/12-caching-with-redis/solution/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/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/java/concepts/junior-mid/12-caching-with-redis/solution/pom.xml b/java/concepts/junior-mid/12-caching-with-redis/solution/pom.xml
new file mode 100644
index 0000000..0663fa6
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/pom.xml
@@ -0,0 +1,121 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ caching-with-redis
+ 0.0.1-SNAPSHOT
+ caching-with-redis
+ Caching with Redis: watch every request hit a slow source, cache it, then fix stale data, self-invocation, TTLs and the stampede
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ org.springframework.boot
+ spring-boot-starter-cache
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+
+ org.testcontainers
+ testcontainers
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java
new file mode 100644
index 0000000..9e030b2
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java
@@ -0,0 +1,30 @@
+package com.amigoscode.caching;
+
+import com.amigoscode.caching.product.InvalidRequestException;
+import com.amigoscode.caching.product.ProductNotFoundException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/** Anything not listed here, including "Redis is not reachable" or a value Redis cannot serialize, becomes a 500. */
+@RestControllerAdvice
+public class ApiExceptionHandler {
+
+ public record ApiError(String code, String message) {
+ }
+
+ @ExceptionHandler(ProductNotFoundException.class)
+ public ResponseEntity notFound(ProductNotFoundException e) {
+ return error(HttpStatus.NOT_FOUND, "PRODUCT_NOT_FOUND", e);
+ }
+
+ @ExceptionHandler(InvalidRequestException.class)
+ public ResponseEntity badRequest(InvalidRequestException e) {
+ return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", e);
+ }
+
+ private static ResponseEntity error(HttpStatus status, String code, RuntimeException e) {
+ return ResponseEntity.status(status).body(new ApiError(code, e.getMessage()));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/CachingApplication.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/CachingApplication.java
new file mode 100644
index 0000000..5fd7cce
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/CachingApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.caching;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CachingApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CachingApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/cache/CacheConfig.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/cache/CacheConfig.java
new file mode 100644
index 0000000..83a9b33
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/cache/CacheConfig.java
@@ -0,0 +1,48 @@
+package com.amigoscode.caching.cache;
+
+import com.amigoscode.caching.product.ProductView;
+import java.time.Duration;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.cache.autoconfigure.RedisCacheManagerBuilderCustomizer;
+import org.springframework.cache.annotation.CachingConfigurer;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.interceptor.CacheErrorHandler;
+import org.springframework.cache.interceptor.LoggingCacheErrorHandler;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheWriter;
+import org.springframework.data.redis.cache.RedisCacheWriter.TtlFunction;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
+
+/** Switches caching on and configures the products cache. Spring Boot builds the RedisCacheManager. */
+@Configuration
+@EnableCaching
+public class CacheConfig implements CachingConfigurer {
+
+ public static final String PRODUCTS = "products";
+
+ @Bean
+ RedisCacheManagerBuilderCustomizer productsCache(RedisConnectionFactory connectionFactory,
+ @Value("${catalogue.cache.products-ttl}") Duration ttl) {
+ return builder -> builder
+ // Task 7: a cache writer that takes a lock in Redis (the key products~lock) while it loads
+ // a missing entry. Without it, sync = true does nothing on Redis. The lock expires after
+ // 10 seconds, so an instance that dies while loading cannot block the cache for ever.
+ .cacheWriter(RedisCacheWriter.create(connectionFactory, writer -> writer
+ .enableLocking(lock -> lock.lockTimeout(TtlFunction.just(Duration.ofSeconds(10))))))
+ .withCacheConfiguration(PRODUCTS, RedisCacheConfiguration.defaultCacheConfig()
+ // Task 2: JSON instead of Java serialization.
+ .serializeValuesWith(SerializationPair.fromSerializer(new JacksonJsonRedisSerializer<>(ProductView.class)))
+ // Task 6: entries expire instead of living for ever.
+ .entryTtl(ttl));
+ }
+
+ /** Task 8: if Redis is down, log it and carry on as if the cache were empty, instead of answering 500. */
+ @Override
+ public CacheErrorHandler errorHandler() {
+ return new LoggingCacheErrorHandler();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Db.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Db.java
new file mode 100644
index 0000000..6ae725a
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Db.java
@@ -0,0 +1,35 @@
+package com.amigoscode.caching.demo;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/** Postgres connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5451/catalogue");
+ static final String USER = env("DB_USER", "catalogue");
+ static final String PASSWORD = env("DB_PASSWORD", "catalogue");
+
+ private Db() {
+ }
+
+ static Connection connect() throws SQLException {
+ return DriverManager.getConnection(URL, USER, PASSWORD);
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ Redis.printNotReachable("Postgres at " + URL, e.getMessage());
+ return false;
+ }
+ }
+
+ static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Demo.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Demo.java
new file mode 100644
index 0000000..540789b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Demo.java
@@ -0,0 +1,534 @@
+package com.amigoscode.caching.demo;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.turbo.TurboFilter;
+import ch.qos.logback.core.spi.FilterReply;
+import com.amigoscode.caching.CachingApplication;
+import com.amigoscode.caching.product.SlowProductSource;
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Marker;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Starts the real application, sends requests at it over HTTP, and counts how many of them had to
+ * call the slow source. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags.
+ */
+public final class Demo {
+
+ private static final List SCENARIOS = List.of("repeat", "update", "basket", "stampede", "redis-down");
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+ private static final Pattern CODE = Pattern.compile("\"code\"\\s*:\\s*\"([A-Z_]+)\"");
+ private static final Pattern MESSAGE = Pattern.compile("\"message\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
+ private static final String NEW_PRICE = "79.00";
+ private static final AtomicReference SERVER_ERROR = new AtomicReference<>();
+
+ private record Options(String scenario, int requests, long delayMillis, Integer ttlSeconds) {
+ }
+
+ private record Response(int status, String body, long millis, int sourceCalls) {
+
+ String price() {
+ return find(PRICE, body);
+ }
+
+ String describe() {
+ if (status == 200) {
+ List prices = new ArrayList<>();
+ Matcher matcher = PRICE.matcher(body);
+ while (matcher.find()) {
+ prices.add(matcher.group(1));
+ }
+ return "200 price " + String.join(", ", prices);
+ }
+ String code = find(CODE, body);
+ String message = find(MESSAGE, body);
+ String text = code != null ? code : message == null ? "" : message;
+ if (text.length() > 80) {
+ text = text.substring(0, 80) + "...";
+ }
+ return status + (text.isEmpty() ? "" : " " + text);
+ }
+ }
+
+ private final Options options;
+ private final ConfigurableApplicationContext context;
+ private final SlowProductSource source;
+ private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ private final String baseUrl;
+
+ private Demo(Options options, ConfigurableApplicationContext context) {
+ this.options = options;
+ this.context = context;
+ this.source = context.getBean(SlowProductSource.class);
+ this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ boolean redisDown = options.scenario().equals("redis-down");
+ if (!Db.isUp()) {
+ return;
+ }
+ if (!redisDown) {
+ Redis redis = Redis.connectOrExplain();
+ if (redis == null) {
+ return;
+ }
+ redis.close();
+ }
+
+ List springArgs = new ArrayList<>(List.of(
+ "--server.port=0",
+ "--logging.level.root=WARN",
+ "--logging.level.io.netty.resolver.dns=ERROR",
+ "--spring.web.error.include-message=always",
+ "--catalogue.source-delay-ms=" + options.delayMillis()));
+ if (options.ttlSeconds() != null) {
+ springArgs.add("--catalogue.cache.products-ttl=" + options.ttlSeconds() + "s");
+ }
+ if (redisDown) {
+ springArgs.add("--spring.data.redis.port=" + closedPort());
+ springArgs.add("--spring.data.redis.timeout=1s");
+ springArgs.add("--spring.data.redis.connect-timeout=1s");
+ }
+
+ SpringApplication app = new SpringApplication(CachingApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) {
+ captureServerErrors();
+ new Demo(options, context).run();
+ }
+ }
+
+ private void run() throws Exception {
+ resetDatabase();
+ if (!options.scenario().equals("redis-down")) {
+ redis(connection -> connection.serverCommands().flushDb());
+ }
+ // One throwaway request so the first real one is not slowed down by startup work.
+ http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding());
+
+ System.out.println();
+ switch (options.scenario()) {
+ case "repeat" -> repeat();
+ case "update" -> update();
+ case "basket" -> basket();
+ case "stampede" -> stampede();
+ default -> redisDown();
+ }
+ System.out.println();
+ }
+
+ // ---------------------------------------------------------------- scenarios
+
+ private void repeat() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: repeat | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The same product page is opened " + n + " times, one request after the other.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ long startedAt = System.nanoTime();
+ int failed = 0;
+ Response firstFailure = null;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products/1");
+ if (response.status() != 200) {
+ failed++;
+ firstFailure = firstFailure == null ? response : firstFailure;
+ }
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Request " + pad(i, n), "GET /api/products/1", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ long millis = millisSince(startedAt);
+ int calls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Requests: " + n);
+ System.out.println("Calls to the slow source: " + calls);
+ System.out.println("Time taken: " + millis + " ms (" + (millis / n) + " ms per request)");
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " requests failed: " + firstFailure.describe() + serverError());
+ } else if (n > 1 && calls >= n) {
+ System.out.println("RESULT: NO CACHE. " + n + " requests, " + calls
+ + " calls to the slow source: every request paid the full " + options.delayMillis() + " ms.");
+ } else if (n == 1) {
+ System.out.println("RESULT: OK. 1 request, " + calls + " " + plural(calls, "call")
+ + " to the slow source. The first request for a product always has to load it.");
+ } else {
+ System.out.println("RESULT: OK. " + n + " requests, " + calls + " " + plural(calls, "call")
+ + " to the slow source. " + (n - calls == 1 ? "The other request was" : "The other " + (n - calls) + " were")
+ + " answered from Redis.");
+ }
+ }
+
+ private void update() throws Exception {
+ System.out.println("Scenario: update | slow source: " + options.delayMillis() + " ms");
+ System.out.println("Read product 1, change its price to " + NEW_PRICE + ", read it again.");
+ System.out.println();
+
+ Response first = get("/api/products/1");
+ printStep("Step 1", "GET /api/products/1", first);
+ Response second = get("/api/products/1");
+ printStep("Step 2", "GET /api/products/1", second);
+ Response put = send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/products/1/price"))
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString("{\"price\":" + NEW_PRICE + "}")));
+ printStep("Step 3", "PUT /api/products/1/price " + NEW_PRICE, put);
+ Response after = get("/api/products/1");
+ printStep("Step 4", "GET /api/products/1", after);
+
+ String inDatabase = context.getBean(JdbcTemplate.class)
+ .queryForObject("select price::text from product where id = 1", String.class);
+ System.out.println();
+ System.out.println("Price in the database: " + inDatabase);
+ System.out.println("Price GET returned: " + after.price());
+ System.out.println();
+ if (first.status() != 200 || put.status() != 200 || after.status() != 200) {
+ System.out.println("RESULT: ERROR. A request failed: " + (put.status() != 200 ? put : after).describe() + serverError());
+ } else if (!inDatabase.equals(after.price())) {
+ System.out.println("RESULT: STALE. The price was changed to " + inDatabase + ", but GET still returns "
+ + after.price() + " from the cache.");
+ } else {
+ System.out.println("RESULT: OK. GET returns the new price, " + inDatabase + ".");
+ }
+ }
+
+ private void basket() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: basket | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The product page for product 1 is opened twice, then the basket page with products 1, 2 and 3 "
+ + n + " times.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ printStep("Product page", "GET /api/products/1", get("/api/products/1"));
+ printStep("Product page", "GET /api/products/1", get("/api/products/1"));
+ int productPageCalls = source.calls() - callsBefore;
+
+ callsBefore = source.calls();
+ int failed = 0;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products?ids=1,2,3");
+ failed += response.status() == 200 ? 0 : 1;
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Basket " + pad(i, n), "GET /api/products?ids=1,2,3", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ int basketCalls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Calls to the slow source, product page (2 requests): " + productPageCalls);
+ System.out.println("Calls to the slow source, basket (" + n + " requests x 3 products): " + basketCalls);
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " basket requests failed." + serverError());
+ } else if (productPageCalls == 2 && basketCalls >= n * 3) {
+ System.out.println("RESULT: NOT CACHED. Nothing is cached yet: the product page and the basket call the slow source"
+ + " for every product, every time.");
+ } else if (basketCalls >= n * 3) {
+ System.out.println("RESULT: NOT CACHED. The basket called the slow source " + basketCalls
+ + " times for 3 products. Product 1 was already in the cache, and the basket did not even look.");
+ } else {
+ System.out.println("RESULT: OK. The basket called the slow source " + basketCalls + " "
+ + plural(basketCalls, "time") + ": only for the products that were not cached yet.");
+ }
+ }
+
+ private void stampede() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: stampede | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("Products 1 and 2 are read once, to fill the cache. Then the entry for product 1 expires, and "
+ + n + " requests for it arrive at the same moment.");
+ System.out.println();
+
+ get("/api/products/1");
+ get("/api/products/2");
+ redis(connection -> connection.keyCommands().del("products::1".getBytes()));
+ System.out.println(" products::1 removed from Redis, as if its TTL had just run out.");
+ System.out.println();
+
+ int callsBefore = source.calls(1);
+ CountDownLatch go = new CountDownLatch(1);
+ List> futures = new ArrayList<>();
+ Future otherProduct;
+ long startedAt;
+ try (ExecutorService clients = Executors.newVirtualThreadPerTaskExecutor()) {
+ for (int i = 0; i < n; i++) {
+ futures.add(clients.submit(() -> {
+ go.await();
+ return get("/api/products/1");
+ }));
+ }
+ // A little later, somebody opens product 2, which is still in the cache.
+ otherProduct = clients.submit(() -> {
+ go.await();
+ Thread.sleep(Math.min(50, Math.max(1, options.delayMillis() / 4)));
+ return get("/api/products/2");
+ });
+ startedAt = System.nanoTime();
+ go.countDown();
+ }
+ long millis = millisSince(startedAt);
+ int calls = source.calls(1) - callsBefore;
+ int failed = 0;
+ for (Future future : futures) {
+ failed += future.get().status() == 200 ? 0 : 1;
+ }
+ Response other = otherProduct.get();
+
+ System.out.println("Requests for product 1: " + n + ", all at the same moment");
+ System.out.println("Slow source calls for product 1: " + calls);
+ System.out.println("Failed requests: " + failed);
+ System.out.println("Time taken: " + millis + " ms");
+ System.out.println("Meanwhile, GET /api/products/2: " + other.millis() + " ms");
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " requests failed." + serverError());
+ } else if (calls > 1) {
+ System.out.println("RESULT: STAMPEDE. " + n + " requests missed the cache together and " + calls
+ + " of them called the slow source for the same product.");
+ } else {
+ System.out.println("RESULT: OK. " + n + " requests missed the cache together, " + calls
+ + " called the slow source, the others waited and read the result from Redis.");
+ }
+ }
+
+ private void redisDown() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: redis-down | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The application is pointed at a Redis that is not there, then asked for product 1 "
+ + n + " times.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ int failed = 0;
+ Response firstFailure = null;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products/1");
+ if (response.status() != 200) {
+ failed++;
+ firstFailure = firstFailure == null ? response : firstFailure;
+ }
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Request " + pad(i, n), "GET /api/products/1", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ int calls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Requests: " + n);
+ System.out.println("Failed requests: " + failed);
+ System.out.println("Calls to the slow source: " + calls);
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: DOWN. Redis is not reachable, so " + failed + " of " + n
+ + " requests failed: " + firstFailure.describe() + serverError());
+ } else {
+ System.out.println("RESULT: OK. Redis is not reachable, and all " + n
+ + " requests were answered from the slow source instead.");
+ }
+ }
+
+ // ---------------------------------------------------------------- helpers
+
+ private Response get(String path) throws IOException, InterruptedException {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET());
+ }
+
+ private Response send(HttpRequest.Builder request) throws IOException, InterruptedException {
+ int callsBefore = source.calls();
+ long startedAt = System.nanoTime();
+ HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
+ return new Response(response.statusCode(), response.body(), millisSince(startedAt), source.calls() - callsBefore);
+ }
+
+ private static void printStep(String label, String request, Response response) {
+ String source = response.sourceCalls() == 0 ? "slow source not called"
+ : "slow source called" + (response.sourceCalls() > 1 ? " " + response.sourceCalls() + " times" : "");
+ System.out.printf(" %-14s %-34s <- %-26s %5d ms %s%n", label, request, response.describe(), response.millis(), source);
+ }
+
+ /**
+ * A 500 is logged by Tomcat with a long stack trace. Keep only the root cause, and print it in
+ * the RESULT line instead. Added after startup, because Spring Boot resets logging when it starts.
+ */
+ private static void captureServerErrors() {
+ LoggerContext logging = (LoggerContext) LoggerFactory.getILoggerFactory();
+ logging.addTurboFilter(new TurboFilter() {
+ @Override
+ public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
+ if (t == null || !logger.getName().startsWith("org.apache.catalina.core.ContainerBase")) {
+ return FilterReply.NEUTRAL;
+ }
+ Throwable root = t;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ SERVER_ERROR.compareAndSet(null, root.getClass().getSimpleName() + ": " + root.getMessage());
+ return FilterReply.DENY;
+ }
+ });
+ }
+
+ /** " Cause: ..." for the first 500 the server logged, or nothing. */
+ private static String serverError() {
+ String error = SERVER_ERROR.get();
+ return error == null ? "" : System.lineSeparator() + " Cause: " + error;
+ }
+
+ private void resetDatabase() {
+ JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
+ jdbc.execute("truncate table price_change restart identity");
+ jdbc.update("""
+ update product set price = v.price
+ from (values (1, 89.00), (2, 329.00), (3, 149.00)) as v(id, price)
+ where product.id = v.id
+ """);
+ }
+
+ private interface RedisWork {
+ void run(RedisConnection connection);
+ }
+
+ private void redis(RedisWork work) {
+ try (RedisConnection connection = context.getBean(RedisConnectionFactory.class).getConnection()) {
+ work.run(connection);
+ }
+ }
+
+ private static int closedPort() throws IOException {
+ try (ServerSocket socket = new ServerSocket(0)) {
+ return socket.getLocalPort();
+ }
+ }
+
+ private static long millisSince(long nanos) {
+ return (System.nanoTime() - nanos) / 1_000_000;
+ }
+
+ private static String pad(int i, int n) {
+ return String.format("%" + String.valueOf(n).length() + "d", i);
+ }
+
+ private static String plural(int count, String word) {
+ return count == 1 ? word : word + "s";
+ }
+
+ private static String find(Pattern pattern, String body) {
+ Matcher matcher = pattern.matcher(body == null ? "" : body);
+ return matcher.find() ? matcher.group(1) : null;
+ }
+
+ private static Options parse(String[] args) {
+ String scenario = "repeat";
+ Integer requests = null;
+ long delayMillis = 200;
+ Integer ttlSeconds = null;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--scenario" -> {
+ scenario = value(args, ++i, arg);
+ if (!SCENARIOS.contains(scenario)) {
+ throw new IllegalArgumentException("Unknown scenario: " + scenario + ". Use one of " + SCENARIOS);
+ }
+ }
+ case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 500);
+ case "--delay-ms" -> delayMillis = number(value(args, ++i, arg), arg, 0, 60_000);
+ case "--ttl" -> ttlSeconds = number(value(args, ++i, arg), arg, 1, 86_400);
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ int defaultRequests = switch (scenario) {
+ case "basket", "redis-down" -> 5;
+ default -> 20;
+ };
+ return new Options(scenario, requests == null ? defaultRequests : requests, delayMillis, ttlSeconds);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static int number(String value, String option, int min, int max) {
+ try {
+ int number = Integer.parseInt(value);
+ if (number < min || number > max) {
+ throw new NumberFormatException();
+ }
+ return number;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value);
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --scenario what to run (default: repeat)");
+ System.out.println(" repeat the same product page, many times in a row");
+ System.out.println(" update read a product, change its price, read it again");
+ System.out.println(" basket the basket page, which shows products 1, 2 and 3");
+ System.out.println(" stampede a cached product expires and many requests arrive at once");
+ System.out.println(" redis-down the application cannot reach Redis");
+ System.out.println(" --requests how many requests (default: 20; basket and redis-down: 5)");
+ System.out.println(" --delay-ms how long the slow source takes per product (default: 200)");
+ System.out.println(" --ttl how long a cached product lives, instead of catalogue.cache.products-ttl");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --scenario update");
+ System.out.println(" ./demo --scenario stampede --requests 50");
+ System.out.println(" ./demo --requests 1 --ttl 15 then ./inspect --watch, and see the entry expire");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Inspect.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Inspect.java
new file mode 100644
index 0000000..10cf400
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Inspect.java
@@ -0,0 +1,192 @@
+package com.amigoscode.caching.demo;
+
+import io.lettuce.core.KeyScanCursor;
+import io.lettuce.core.ScanArgs;
+import io.lettuce.core.ScanCursor;
+import io.lettuce.core.api.sync.RedisCommands;
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Shows what is in Redis right now (every key, its TTL and its value, byte for byte) and puts each
+ * product row from Postgres next to its cached copy, so a stale entry is easy to see. Run it with
+ * ./inspect (or .\inspect on Windows).
+ */
+public final class Inspect {
+
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+ private static final int VALUE_WIDTH = 72;
+
+ public static void main(String[] args) throws Exception {
+ boolean watch = false;
+ for (String arg : args) {
+ if (arg.equals("--watch")) {
+ watch = true;
+ } else {
+ System.out.println("Usage: ./inspect [--watch] (Windows: .\\inspect [--watch])");
+ System.out.println();
+ System.out.println(" --watch refresh every second for one minute (Ctrl+C to stop)");
+ return;
+ }
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Redis redis = Redis.connectOrExplain(); Connection db = redis == null ? null : Db.connect()) {
+ if (redis == null) {
+ return;
+ }
+ int rounds = watch ? 60 : 1;
+ for (int round = 0; round < rounds; round++) {
+ snapshot(redis.commands(), db);
+ if (round < rounds - 1) {
+ Thread.sleep(1000);
+ }
+ }
+ }
+ }
+
+ private static void snapshot(RedisCommands redis, Connection db) throws SQLException {
+ System.out.println();
+ System.out.println("==== " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) + " ====");
+ System.out.println();
+
+ List keys = keys(redis);
+ Map values = new HashMap<>();
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"key", "ttl", "bytes", "value"});
+ for (String key : keys) {
+ byte[] name = key.getBytes(StandardCharsets.UTF_8);
+ long ttl = redis.ttl(name);
+ byte[] value = "string".equals(redis.type(name)) ? redis.get(name) : null;
+ if (value != null) {
+ values.put(key, value);
+ }
+ rows.add(new String[] {
+ key,
+ ttl == -1 ? "-1 (never expires)" : ttl == -2 ? "gone" : ttl + " s",
+ value == null ? "" : String.valueOf(value.length),
+ value == null ? "(" + redis.type(name) + ")" : printable(value)});
+ }
+ System.out.println("REDIS " + Redis.HOST + ":" + Redis.PORT + " (" + keys.size() + " " + (keys.size() == 1 ? "key" : "keys") + ")");
+ if (keys.isEmpty()) {
+ System.out.println(" empty. Nothing has been cached.");
+ } else {
+ printTable(rows);
+ }
+
+ System.out.println();
+ System.out.println("POSTGRES NEXT TO THE CACHE");
+ List products = new ArrayList<>();
+ products.add(new String[] {"id", "name", "price_in_db", "cached_as", "price_in_cache", "verdict"});
+ try (Statement statement = db.createStatement();
+ ResultSet result = statement.executeQuery("select id, name, price::text from product order by id")) {
+ while (result.next()) {
+ String id = result.getString(1);
+ String price = result.getString(3);
+ String key = "products::" + id;
+ byte[] value = values.get(key);
+ String cachedPrice;
+ String verdict;
+ if (value == null) {
+ cachedPrice = "";
+ verdict = "not cached";
+ } else if (value.length > 0 && value[0] == '{') {
+ Matcher matcher = PRICE.matcher(new String(value, StandardCharsets.UTF_8));
+ cachedPrice = matcher.find() ? matcher.group(1) : "?";
+ verdict = cachedPrice.equals(price) ? "same" : "STALE";
+ } else {
+ cachedPrice = "(not JSON)";
+ verdict = "cannot tell: Java serialization";
+ }
+ products.add(new String[] {id, result.getString(2), price, value == null ? "" : key, cachedPrice, verdict});
+ }
+ }
+ printTable(products);
+
+ System.out.println();
+ System.out.println("PRICE CHANGES (newest first)");
+ List changes = new ArrayList<>();
+ changes.add(new String[] {"product_id", "old_price", "new_price", "changed_at"});
+ try (Statement statement = db.createStatement();
+ ResultSet result = statement.executeQuery("""
+ select product_id, old_price::text, new_price::text, to_char(changed_at, 'HH24:MI:SS.MS')
+ from price_change order by id desc limit 5
+ """)) {
+ while (result.next()) {
+ changes.add(new String[] {result.getString(1), result.getString(2), result.getString(3), result.getString(4)});
+ }
+ }
+ if (changes.size() == 1) {
+ System.out.println(" none");
+ } else {
+ printTable(changes);
+ }
+ }
+
+ private static List keys(RedisCommands redis) {
+ List keys = new ArrayList<>();
+ ScanCursor cursor = ScanCursor.INITIAL;
+ do {
+ KeyScanCursor page = redis.scan(cursor, ScanArgs.Builder.limit(100));
+ page.getKeys().forEach(key -> keys.add(new String(key, StandardCharsets.UTF_8)));
+ cursor = page;
+ } while (!cursor.isFinished());
+ keys.sort(null);
+ return keys;
+ }
+
+ /** The value as text, with every byte that is not printable ASCII shown as \xNN. */
+ private static String printable(byte[] value) {
+ StringBuilder text = new StringBuilder();
+ for (byte b : value) {
+ int c = b & 0xff;
+ if (c >= 0x20 && c < 0x7f) {
+ text.append((char) c);
+ } else {
+ text.append(String.format("\\x%02x", c));
+ }
+ if (text.length() >= VALUE_WIDTH) {
+ return text.substring(0, VALUE_WIDTH) + "...";
+ }
+ }
+ return text.toString();
+ }
+
+ private static void printTable(List rows) {
+ int[] widths = new int[rows.get(0).length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Redis.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Redis.java
new file mode 100644
index 0000000..890b82d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/demo/Redis.java
@@ -0,0 +1,79 @@
+package com.amigoscode.caching.demo;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.LoggerContext;
+import io.lettuce.core.RedisClient;
+import io.lettuce.core.RedisURI;
+import io.lettuce.core.api.StatefulRedisConnection;
+import io.lettuce.core.codec.ByteArrayCodec;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Talks to Redis straight from Java with Lettuce, the client Spring uses, so nobody needs redis-cli.
+ * Same defaults as application.properties.
+ */
+final class Redis implements AutoCloseable {
+
+ static final String HOST = Db.env("REDIS_HOST", "localhost");
+ static final int PORT = Integer.parseInt(Db.env("REDIS_PORT", "6390"));
+
+ private final RedisClient client;
+ private final StatefulRedisConnection connection;
+
+ private Redis() {
+ quietLogging();
+ RedisURI uri = RedisURI.builder().withHost(HOST).withPort(PORT).withTimeout(Duration.ofSeconds(2)).build();
+ client = RedisClient.create(uri);
+ try {
+ connection = client.connect(ByteArrayCodec.INSTANCE);
+ } catch (RuntimeException e) {
+ client.shutdown(Duration.ZERO, Duration.ofSeconds(1));
+ throw e;
+ }
+ }
+
+ /** Connects, or prints what to do and returns null when Redis is not reachable. */
+ static Redis connectOrExplain() {
+ try {
+ return new Redis();
+ } catch (RuntimeException e) {
+ printNotReachable("Redis at " + HOST + ":" + PORT, e.getMessage());
+ return null;
+ }
+ }
+
+ io.lettuce.core.api.sync.RedisCommands commands() {
+ return connection.sync();
+ }
+
+ @Override
+ public void close() {
+ connection.close();
+ client.shutdown(Duration.ZERO, Duration.ofSeconds(1));
+ }
+
+ static byte[] bytes(String text) {
+ return text.getBytes(StandardCharsets.UTF_8);
+ }
+
+ static void printNotReachable(String what, String error) {
+ System.out.println();
+ System.out.println("Cannot reach " + what);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + (error == null ? "" : error.lines().findFirst().orElse("")) + ")");
+ }
+
+ /** Netty and Lettuce log at DEBUG when nothing else configures logging. Keep the output readable. */
+ static void quietLogging() {
+ if (LoggerFactory.getILoggerFactory() instanceof LoggerContext context) {
+ context.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.WARN);
+ context.getLogger("io.netty.resolver.dns").setLevel(Level.ERROR);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java
new file mode 100644
index 0000000..9572e64
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java
@@ -0,0 +1,9 @@
+package com.amigoscode.caching.product;
+
+/** The client sent something the API cannot accept. Becomes a 400. */
+public class InvalidRequestException extends RuntimeException {
+
+ public InvalidRequestException(String message) {
+ super(message);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java
new file mode 100644
index 0000000..48a24a8
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java
@@ -0,0 +1,21 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+
+@Component
+public class JdbcPriceHistory implements PriceHistory {
+
+ private final JdbcTemplate jdbc;
+
+ public JdbcPriceHistory(JdbcTemplate jdbc) {
+ this.jdbc = jdbc;
+ }
+
+ @Override
+ public void record(long productId, BigDecimal oldPrice, BigDecimal newPrice) {
+ jdbc.update("insert into price_change (product_id, old_price, new_price) values (?, ?, ?)",
+ productId, oldPrice, newPrice);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/PriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/PriceHistory.java
new file mode 100644
index 0000000..d123fd3
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/PriceHistory.java
@@ -0,0 +1,9 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+
+/** Writes down every price change. Called inside the transaction that changes the price. */
+public interface PriceHistory {
+
+ void record(long productId, BigDecimal oldPrice, BigDecimal newPrice);
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/Product.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/Product.java
new file mode 100644
index 0000000..26ff34c
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/Product.java
@@ -0,0 +1,35 @@
+package com.amigoscode.caching.product;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import java.math.BigDecimal;
+
+@Entity
+public class Product {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ private BigDecimal price;
+
+ protected Product() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void changePrice(BigDecimal newPrice) {
+ this.price = newPrice;
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductController.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductController.java
new file mode 100644
index 0000000..3213ddc
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductController.java
@@ -0,0 +1,48 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+import java.util.List;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/products")
+public class ProductController {
+
+ public record PriceChange(BigDecimal price) {
+ }
+
+ private final ProductService productService;
+
+ public ProductController(ProductService productService) {
+ this.productService = productService;
+ }
+
+ @GetMapping("/{id}")
+ public ProductView product(@PathVariable long id) {
+ return productService.findById(id);
+ }
+
+ /** The basket page: GET /api/products?ids=1,2,3 returns the products in the order asked for. */
+ @GetMapping(params = "ids")
+ public List basket(@RequestParam List ids) {
+ if (ids.isEmpty() || ids.size() > 50) {
+ throw new InvalidRequestException("ids must list 1 to 50 product ids");
+ }
+ // Each call goes through the Spring proxy of ProductService, so each one can hit the cache.
+ return ids.stream().map(productService::findById).toList();
+ }
+
+ @PutMapping("/{id}/price")
+ public ProductView changePrice(@PathVariable long id, @RequestBody PriceChange change) {
+ if (change == null || change.price() == null || change.price().signum() <= 0) {
+ throw new InvalidRequestException("price must be greater than 0");
+ }
+ return productService.changePrice(id, change.price());
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java
new file mode 100644
index 0000000..fd35269
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.caching.product;
+
+public class ProductNotFoundException extends RuntimeException {
+
+ public ProductNotFoundException(long productId) {
+ super("Product " + productId + " does not exist");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductRepository.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductRepository.java
new file mode 100644
index 0000000..cfdc3ea
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductRepository.java
@@ -0,0 +1,6 @@
+package com.amigoscode.caching.product;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface ProductRepository extends JpaRepository {
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductService.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductService.java
new file mode 100644
index 0000000..c37b0d0
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductService.java
@@ -0,0 +1,45 @@
+package com.amigoscode.caching.product;
+
+import com.amigoscode.caching.cache.CacheConfig;
+import java.math.BigDecimal;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class ProductService {
+
+ private final ProductSource source;
+ private final ProductRepository products;
+ private final PriceHistory priceHistory;
+
+ public ProductService(ProductSource source, ProductRepository products, PriceHistory priceHistory) {
+ this.source = source;
+ this.products = products;
+ this.priceHistory = priceHistory;
+ }
+
+ /**
+ * Cached in Redis under products::{id}. sync = true asks the cache to let only one caller load a
+ * missing entry; with the locking cache writer in CacheConfig the others wait for it.
+ */
+ @Cacheable(cacheNames = CacheConfig.PRODUCTS, key = "#productId", sync = true)
+ public ProductView findById(long productId) {
+ return source.load(productId);
+ }
+
+ /**
+ * The cache advice wraps the transaction, so the entry is removed after the new price is
+ * committed. Evicting before the commit would let a reader put the old price straight back.
+ */
+ @Transactional
+ @CacheEvict(cacheNames = CacheConfig.PRODUCTS, key = "#productId")
+ public ProductView changePrice(long productId, BigDecimal newPrice) {
+ Product product = products.findById(productId).orElseThrow(() -> new ProductNotFoundException(productId));
+ BigDecimal oldPrice = product.getPrice();
+ product.changePrice(newPrice);
+ priceHistory.record(productId, oldPrice, newPrice);
+ return ProductView.of(product);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductSource.java
new file mode 100644
index 0000000..4872622
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductSource.java
@@ -0,0 +1,11 @@
+package com.amigoscode.caching.product;
+
+/**
+ * Where product data really comes from. Loading one product is slow: in a real shop this is a query
+ * that joins prices, stock and reviews, or a call to another service. This is what a cache protects.
+ */
+public interface ProductSource {
+
+ /** Loads the product with its current price, or throws {@link ProductNotFoundException}. */
+ ProductView load(long productId);
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductView.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductView.java
new file mode 100644
index 0000000..3a76b81
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/ProductView.java
@@ -0,0 +1,11 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+
+/** What GET /api/products/{id} returns, and what gets cached. */
+public record ProductView(long id, String name, BigDecimal price) {
+
+ static ProductView of(Product product) {
+ return new ProductView(product.getId(), product.getName(), product.getPrice());
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/SlowProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/SlowProductSource.java
new file mode 100644
index 0000000..8fdf753
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/java/com/amigoscode/caching/product/SlowProductSource.java
@@ -0,0 +1,52 @@
+package com.amigoscode.caching.product;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * Reads the product from Postgres, after waiting catalogue.source-delay-ms (200 ms by default) to
+ * stand in for the expensive part. Counts every call, so the demo can show how often it was asked.
+ */
+@Component
+public class SlowProductSource implements ProductSource {
+
+ private final ProductRepository products;
+ private final long delayMillis;
+ private final AtomicInteger calls = new AtomicInteger();
+ private final Map callsPerProduct = new ConcurrentHashMap<>();
+
+ public SlowProductSource(ProductRepository products, @Value("${catalogue.source-delay-ms}") long delayMillis) {
+ this.products = products;
+ this.delayMillis = delayMillis;
+ }
+
+ @Override
+ public ProductView load(long productId) {
+ calls.incrementAndGet();
+ callsPerProduct.computeIfAbsent(productId, id -> new AtomicInteger()).incrementAndGet();
+ if (delayMillis > 0) {
+ try {
+ Thread.sleep(delayMillis);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+ return products.findById(productId).map(ProductView::of)
+ .orElseThrow(() -> new ProductNotFoundException(productId));
+ }
+
+ /** How many times load was called since the application started. */
+ public int calls() {
+ return calls.get();
+ }
+
+ /** How many times product {@code productId} was loaded since the application started. */
+ public int calls(long productId) {
+ AtomicInteger count = callsPerProduct.get(productId);
+ return count == null ? 0 : count.get();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/application.properties b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/application.properties
new file mode 100644
index 0000000..3c0b5b0
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/application.properties
@@ -0,0 +1,19 @@
+spring.application.name=caching-with-redis
+
+# Postgres and Redis from compose.yaml. Ports 5451 and 6390 so they do not clash with ones you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5451/catalogue}
+spring.datasource.username=${DB_USER:catalogue}
+spring.datasource.password=${DB_PASSWORD:catalogue}
+spring.data.redis.host=${REDIS_HOST:localhost}
+spring.data.redis.port=${REDIS_PORT:6390}
+
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+spring.sql.init.mode=always
+
+# How long the slow source takes to load one product, in milliseconds. It stands for an expensive
+# query or a call to another service.
+catalogue.source-delay-ms=200
+
+# How long a cached product lives in Redis.
+catalogue.cache.products-ttl=10m
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/schema.sql
new file mode 100644
index 0000000..45e4545
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/main/resources/schema.sql
@@ -0,0 +1,20 @@
+create table if not exists product (
+ id bigint primary key,
+ name text not null,
+ price numeric(10, 2) not null check (price > 0)
+);
+
+-- Every price change is written down, in the same transaction as the change itself.
+create table if not exists price_change (
+ id bigserial primary key,
+ product_id bigint not null references product (id),
+ old_price numeric(10, 2) not null,
+ new_price numeric(10, 2) not null,
+ changed_at timestamptz not null default now()
+);
+
+insert into product (id, name, price)
+values (1, 'Mechanical keyboard', 89.00),
+ (2, '4K monitor', 329.00),
+ (3, 'USB-C dock', 149.00)
+on conflict (id) do nothing;
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/CacheIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/CacheIT.java
new file mode 100644
index 0000000..3d99588
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/CacheIT.java
@@ -0,0 +1,87 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.CacheManager;
+import org.springframework.context.ApplicationContext;
+import org.springframework.data.redis.cache.RedisCacheManager;
+
+@Tag("task2")
+class CacheIT extends IntegrationTest {
+
+ @Autowired
+ private ApplicationContext context;
+
+ @Test
+ @DisplayName("Cache: caching is switched on, and the cache manager is Redis (RedisCacheManager)")
+ void theCacheIsRedis() {
+ CacheManager cacheManager = context.getBeanProvider(CacheManager.class).getIfAvailable();
+
+ assertThat(cacheManager).as("the CacheManager bean (none means caching is not switched on)").isNotNull();
+ assertThat(cacheManager).as("the CacheManager").isInstanceOf(RedisCacheManager.class);
+ }
+
+ @Test
+ @DisplayName("Cache: 5 GETs for product 1 call the slow source once")
+ void repeatedReadsHitTheCache() {
+ for (int i = 0; i < 5; i++) {
+ assertThat(api.get("/api/products/1").status()).as("status").isEqualTo(200);
+ }
+
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Cache: every product has its own entry: products 1 and 2, read twice each, are loaded once each")
+ void eachProductIsCachedSeparately() {
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Cache: product 1 is stored in Redis under the key products::1")
+ void theKeyIsTheCacheNameAndTheId() {
+ api.get("/api/products/1");
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(redisHasKey("products::1")).as("Redis has the key products::1").isTrue());
+ }
+
+ @Test
+ @DisplayName("Cache: the value in Redis is readable JSON with the name and price, not Java serialization bytes")
+ void theValueIsJson() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisHasKey("products::1"));
+
+ byte[] value = redisValue("products::1");
+ String text = value == null ? "" : new String(value, StandardCharsets.UTF_8);
+ if (value == null || value[0] != '{' || !text.contains("\"name\":\"Mechanical keyboard\"") || !text.contains("\"price\":89.00")) {
+ fail("products::1 should be JSON like {\"id\":1,\"name\":\"Mechanical keyboard\",\"price\":89.00}%nbut Redis holds %d bytes: %s",
+ value == null ? 0 : value.length, printable(value));
+ }
+ }
+
+ @Test
+ @DisplayName("Cache: an unknown product is a 404 every time, and nothing is written to Redis (exceptions are not cached)")
+ void anUnknownProductIsNotCached() {
+ assertThat(api.get("/api/products/999").status()).as("first request").isEqualTo(404);
+ assertThat(api.get("/api/products/999").status()).as("second request").isEqualTo(404);
+
+ assertThat(source.calls(999)).as("calls to the slow source for product 999").isEqualTo(2);
+ assertThat(redisKeyCount()).as("keys in Redis").isZero();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/Check.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/Check.java
new file mode 100644
index 0000000..39a507b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/Check.java
@@ -0,0 +1,115 @@
+package com.amigoscode.caching;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Tasks 1, 3 and 9 are inspection tasks: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the HTTP contract and the slow source (passes from the start, must stay green)");
+ TASKS.put("2", "Task 2: Cache products in Redis, as JSON");
+ TASKS.put("4", "Task 4: Fix the stale price after an update");
+ TASKS.put("5", "Task 5: Fix the cache that the basket skips (self-invocation)");
+ TASKS.put("6", "Task 6: Give cached products a TTL");
+ TASKS.put("7", "Task 7: Fix the cache stampede");
+ TASKS.put("8", "Task 8: Keep the shop up when Redis is down");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-9]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 9. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductControllerTest.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductControllerTest.java
new file mode 100644
index 0000000..bb7e1ed
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductControllerTest.java
@@ -0,0 +1,111 @@
+package com.amigoscode.caching;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.amigoscode.caching.product.ProductController;
+import com.amigoscode.caching.product.ProductNotFoundException;
+import com.amigoscode.caching.product.ProductService;
+import com.amigoscode.caching.product.ProductView;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+/**
+ * Unit tests for the HTTP contract: no Spring context, no database, no Redis. ProductService is a
+ * stub. They pass from the start and must keep passing, so keep the constructors of ProductController
+ * and ProductService as they are.
+ */
+@Tag("baseline")
+class ProductControllerTest {
+
+ private static final Map PRODUCTS = Map.of(
+ 1L, new ProductView(1, "Mechanical keyboard", new BigDecimal("89.00")),
+ 2L, new ProductView(2, "4K monitor", new BigDecimal("329.00")),
+ 3L, new ProductView(3, "USB-C dock", new BigDecimal("149.00")));
+
+ private final MockMvc api = MockMvcBuilders.standaloneSetup(new ProductController(new StubProductService()))
+ .setControllerAdvice(new ApiExceptionHandler())
+ .build();
+
+ @Test
+ @DisplayName("HTTP: GET /api/products/1 returns 200 with the product's id, name and price")
+ void productReturnsOk() throws Exception {
+ api.perform(get("/api/products/1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.id").value(1))
+ .andExpect(jsonPath("$.name").value("Mechanical keyboard"))
+ .andExpect(jsonPath("$.price").value(89.00));
+ }
+
+ @Test
+ @DisplayName("HTTP: an unknown product returns 404 PRODUCT_NOT_FOUND")
+ void unknownProductReturnsNotFound() throws Exception {
+ api.perform(get("/api/products/999"))
+ .andExpect(status().isNotFound())
+ .andExpect(jsonPath("$.code").value("PRODUCT_NOT_FOUND"));
+ }
+
+ @Test
+ @DisplayName("HTTP: PUT /api/products/1/price returns 200 with the new price")
+ void changePriceReturnsTheNewPrice() throws Exception {
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":79.00}"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.price").value(79.00));
+ }
+
+ @Test
+ @DisplayName("HTTP: a price of zero or less returns 400")
+ void nonPositivePriceIsRejected() throws Exception {
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":0}"))
+ .andExpect(status().isBadRequest());
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":-5}"))
+ .andExpect(status().isBadRequest());
+ }
+
+ @Test
+ @DisplayName("HTTP: GET /api/products?ids=3,1 (the basket) returns the products in the order asked for")
+ void basketKeepsTheOrder() throws Exception {
+ api.perform(get("/api/products?ids=3,1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.length()").value(2))
+ .andExpect(jsonPath("$[0].id").value(3))
+ .andExpect(jsonPath("$[1].id").value(1));
+ }
+
+ /** Answers from a map, without Spring, Postgres or Redis. */
+ private static final class StubProductService extends ProductService {
+
+ StubProductService() {
+ super(null, null, null);
+ }
+
+ @Override
+ public ProductView findById(long productId) {
+ ProductView product = PRODUCTS.get(productId);
+ if (product == null) {
+ throw new ProductNotFoundException(productId);
+ }
+ return product;
+ }
+
+ /** No @Override on purpose: the basket is answered the same way, whichever method the controller calls. */
+ public List findAll(List productIds) {
+ return productIds.stream().map(this::findById).toList();
+ }
+
+ @Override
+ public ProductView changePrice(long productId, BigDecimal newPrice) {
+ ProductView product = findById(productId);
+ return new ProductView(product.id(), product.name(), newPrice);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductSourceIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductSourceIT.java
new file mode 100644
index 0000000..920ba60
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ProductSourceIT.java
@@ -0,0 +1,27 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.product.SlowProductSource;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("baseline")
+class ProductSourceIT extends IntegrationTest {
+
+ @Autowired
+ private SlowProductSource slowSource;
+
+ @Test
+ @DisplayName("Source: the slow source reads the product from Postgres, with the price it has right now")
+ void readsTheCurrentRow() {
+ jdbc.update("update product set price = 55.50 where id = 2");
+
+ assertThat(slowSource.load(2).price()).isEqualByComparingTo(new BigDecimal("55.50"));
+ assertThat(slowSource.load(2).name()).isEqualTo("4K monitor");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/RedisDownIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/RedisDownIT.java
new file mode 100644
index 0000000..fef8fc4
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/RedisDownIT.java
@@ -0,0 +1,87 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.Containers;
+import com.amigoscode.caching.support.ControllableProductSource;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.math.BigDecimal;
+import java.net.ServerSocket;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.Import;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+
+/** The application with a real Postgres and a Redis port where nothing is listening. */
+@Tag("task8")
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ properties = {"spring.main.banner-mode=off", "catalogue.source-delay-ms=0",
+ "spring.data.redis.connect-timeout=1s", "spring.data.redis.timeout=1s"})
+@Import(IntegrationTest.TestBeans.class)
+class RedisDownIT {
+
+ private static final int CLOSED_PORT = closedPort();
+
+ @DynamicPropertySource
+ static void redisIsDown(DynamicPropertyRegistry registry) {
+ Containers.database(registry);
+ registry.add("spring.data.redis.host", () -> "localhost");
+ registry.add("spring.data.redis.port", () -> CLOSED_PORT);
+ }
+
+ @Autowired
+ private ControllableProductSource source;
+
+ @Autowired
+ private JdbcTemplate jdbc;
+
+ @Value("${local.server.port}")
+ private int port;
+
+ private Api api;
+
+ @BeforeEach
+ void freshShop() {
+ api = new Api(port);
+ source.reset();
+ IntegrationTest.resetPrices(jdbc);
+ }
+
+ @Test
+ @DisplayName("Redis down: GET still returns the product, loaded from the slow source, instead of a 500")
+ void readsStillWork() {
+ Api.Response response = api.get("/api/products/1");
+
+ assertThat(response.status()).as("status (body: " + response.body() + ")").isEqualTo(200);
+ assertThat(response.price()).as("price").isEqualByComparingTo(new BigDecimal("89.00"));
+ assertThat(source.calls(1)).as("calls to the slow source").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Redis down: PUT still changes the price instead of a 500")
+ void writesStillWork() {
+ Api.Response response = api.changePrice(1, "79.00");
+
+ assertThat(response.status()).as("status (body: " + response.body() + ")").isEqualTo(200);
+ assertThat(jdbc.queryForObject("select price from product where id = 1", BigDecimal.class))
+ .as("price in the database").isEqualByComparingTo(new BigDecimal("79.00"));
+ }
+
+ private static int closedPort() {
+ try (ServerSocket socket = new ServerSocket(0)) {
+ return socket.getLocalPort();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/SelfInvocationIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/SelfInvocationIT.java
new file mode 100644
index 0000000..03c3a4d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/SelfInvocationIT.java
@@ -0,0 +1,43 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task5")
+class SelfInvocationIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Basket: asking for products 1, 2 and 3 twice loads each product only once")
+ void theBasketIsCached() {
+ assertThat(api.get("/api/products?ids=1,2,3").status()).as("status").isEqualTo(200);
+ assertThat(api.get("/api/products?ids=1,2,3").status()).as("status").isEqualTo(200);
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ assertThat(source.calls(3)).as("calls for product 3").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Basket: a product already cached by GET /api/products/{id} is not loaded again by the basket")
+ void theBasketUsesWhatTheProductPageCached() {
+ api.get("/api/products/1");
+
+ api.get("/api/products?ids=1,2,3");
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Basket: what the basket loaded is cached for GET /api/products/{id} too")
+ void theProductPageUsesWhatTheBasketCached() {
+ api.get("/api/products?ids=1,2,3");
+
+ api.get("/api/products/2");
+
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ShortTtlIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ShortTtlIT.java
new file mode 100644
index 0000000..49db081
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/ShortTtlIT.java
@@ -0,0 +1,43 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.context.TestPropertySource;
+
+/** The same application with catalogue.cache.products-ttl=2s, so an entry expires while the test watches. */
+@Tag("task6")
+@TestPropertySource(properties = "catalogue.cache.products-ttl=2s")
+class ShortTtlIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("TTL: the TTL comes from catalogue.cache.products-ttl (set to 2 seconds in this test)")
+ void theTtlIsConfigured() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ assertThat(redisTtl("products::1"))
+ .as("TTL of products::1 in seconds (-1 means it never expires, -2 that the key is missing)")
+ .isBetween(1L, 2L);
+ }
+
+ @Test
+ @DisplayName("TTL: once the entry expires, the next GET loads the product again and sees a price changed behind the cache's back")
+ void anExpiredEntryIsLoadedAgain() {
+ api.get("/api/products/1");
+ // Somebody fixes the price straight in the database. No PUT, so nothing evicts the entry.
+ jdbc.update("update product set price = 75.00 where id = 1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ await("products::1 to expire").atMost(Duration.ofSeconds(8)).until(() -> !redisHasKey("products::1"));
+
+ assertThat(api.get("/api/products/1").price()).as("price after the entry expired").isEqualByComparingTo(new BigDecimal("75.00"));
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(2);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StaleDataIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StaleDataIT.java
new file mode 100644
index 0000000..4cd545d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StaleDataIT.java
@@ -0,0 +1,83 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * These pass in start/, where nothing is cached, and turn red the moment Task 2 adds the cache.
+ * Task 4 turns them green again.
+ */
+@Tag("task4")
+class StaleDataIT extends IntegrationTest {
+
+ private static final BigDecimal NEW_PRICE = new BigDecimal("79.00");
+
+ @Test
+ @DisplayName("Update: after PUT a new price, GET returns the new price")
+ void getReturnsTheNewPrice() {
+ api.get("/api/products/1");
+
+ assertThat(api.changePrice(1, "79.00").status()).as("PUT status").isEqualTo(200);
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(api.get("/api/products/1").price()).as("price returned by GET").isEqualByComparingTo(NEW_PRICE));
+ }
+
+ @Test
+ @DisplayName("Update: after the PUT, Redis no longer holds the old price for product 1")
+ void redisDoesNotKeepTheOldPrice() {
+ api.get("/api/products/1");
+ api.changePrice(1, "79.00");
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
+ byte[] value = redisValue("products::1");
+ String cached = value == null ? null : new String(value, StandardCharsets.UTF_8);
+ assertThat(cached == null || cached.contains("79.00"))
+ .as("products::1 is gone or holds 79.00, but it holds: " + printable(value)).isTrue();
+ });
+ }
+
+ @Test
+ @DisplayName("Update: the other products stay cached: changing product 1 does not empty the whole cache")
+ void otherProductsStayCached() {
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+
+ api.changePrice(1, "79.00");
+ api.get("/api/products/2");
+
+ assertThat(source.calls(2)).as("calls to the slow source for product 2").isEqualTo(1);
+ assertThat(redisHasKey("products::2")).as("Redis still has products::2").isTrue();
+ }
+
+ @Test
+ @DisplayName("Update: the entry is removed after the new price is committed, so a GET in between cannot put the old price back")
+ void evictionHappensAfterTheCommit() throws Exception {
+ api.get("/api/products/1");
+
+ priceHistory.holdTheNextCommit();
+ CompletableFuture put = CompletableFuture.supplyAsync(() -> api.changePrice(1, "79.00"));
+ priceHistory.awaitTheCommit();
+
+ // The new price is written but not committed. Anyone who reads the database now sees 89.00.
+ Api.Response inBetween = api.get("/api/products/1");
+ assertThat(inBetween.status()).as("status of the GET in between").isEqualTo(200);
+
+ priceHistory.releaseTheCommit();
+ assertThat(put.get().status()).as("PUT status").isEqualTo(200);
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(api.get("/api/products/1").price())
+ .as("price returned by GET after the PUT has finished").isEqualByComparingTo(NEW_PRICE));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StampedeIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StampedeIT.java
new file mode 100644
index 0000000..d6a9730
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/StampedeIT.java
@@ -0,0 +1,71 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task7")
+class StampedeIT extends IntegrationTest {
+
+ private static final String LOCK_KEY = "products~lock";
+
+ @Test
+ @DisplayName("Stampede: 10 requests for a product that is not in the cache call the slow source once")
+ void onlyOneRequestLoads() throws Exception {
+ source.everyoneMissesBeforeAnyoneLoads(10);
+
+ api.getAtTheSameMoment("/api/products/1", 10);
+
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Stampede: all 10 requests get the product, none of them fails")
+ void everybodyGetsTheProduct() throws Exception {
+ source.everyoneMissesBeforeAnyoneLoads(10);
+
+ List responses = api.getAtTheSameMoment("/api/products/1", 10);
+
+ assertThat(responses).extracting(Api.Response::status).as("statuses").containsOnly(200);
+ assertThat(responses).extracting(Api.Response::price).as("prices")
+ .allSatisfy(price -> assertThat(price).isEqualByComparingTo(new BigDecimal("89.00")));
+ }
+
+ @Test
+ @DisplayName("Stampede: while product 1 loads, the lock is a key in Redis (products~lock), so other instances wait for it too")
+ void theLockLivesInRedis() {
+ source.holdUntilReleased();
+ CompletableFuture loading = CompletableFuture.supplyAsync(() -> api.get("/api/products/1"));
+ await().atMost(Duration.ofSeconds(10)).until(() -> source.arrivals() >= 1);
+
+ boolean locked = redisHasKey(LOCK_KEY);
+ source.release();
+
+ assertThat(locked).as("Redis has the key " + LOCK_KEY + " while the product is loading").isTrue();
+ assertThat(loading.join().status()).as("status").isEqualTo(200);
+ }
+
+ @Test
+ @DisplayName("Stampede: the lock has a TTL, so an instance that dies while loading cannot block the cache for ever")
+ void theLockExpires() {
+ source.holdUntilReleased();
+ CompletableFuture loading = CompletableFuture.supplyAsync(() -> api.get("/api/products/1"));
+ await().atMost(Duration.ofSeconds(10)).until(() -> source.arrivals() >= 1);
+
+ long ttl = redisTtl(LOCK_KEY);
+ source.release();
+
+ assertThat(ttl).as("TTL of " + LOCK_KEY + " in seconds (-1 means never, -2 that there is no lock key)")
+ .isPositive();
+ assertThat(loading.join().status()).as("status").isEqualTo(200);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/TtlIT.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/TtlIT.java
new file mode 100644
index 0000000..d2bcc38
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/TtlIT.java
@@ -0,0 +1,25 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task6")
+class TtlIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("TTL: products::1 expires: Redis reports a TTL of more than 0 and at most 10 minutes")
+ void entriesHaveATtl() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ assertThat(redisTtl("products::1"))
+ .as("TTL of products::1 in seconds (-1 means it never expires, -2 that the key is missing)")
+ .isBetween(1L, 600L);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Api.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Api.java
new file mode 100644
index 0000000..8cdde7b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Api.java
@@ -0,0 +1,91 @@
+package com.amigoscode.caching.support;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** Talks to the running application over real HTTP, the way a browser would. */
+public final class Api {
+
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+
+ public record Response(int status, String body) {
+
+ /** The first price in the body. */
+ public BigDecimal price() {
+ List prices = prices();
+ return prices.isEmpty() ? null : prices.getFirst();
+ }
+
+ public List prices() {
+ List prices = new ArrayList<>();
+ Matcher matcher = PRICE.matcher(body);
+ while (matcher.find()) {
+ prices.add(new BigDecimal(matcher.group(1)));
+ }
+ return prices;
+ }
+ }
+
+ private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ private final String baseUrl;
+
+ public Api(int port) {
+ this.baseUrl = "http://localhost:" + port;
+ }
+
+ public Response get(String path) {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET());
+ }
+
+ public Response changePrice(long productId, String price) {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/products/" + productId + "/price"))
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString("{\"price\":" + price + "}")));
+ }
+
+ /** Sends {@code count} GETs for {@code path} at the same moment and waits for all of them. */
+ public List getAtTheSameMoment(String path, int count) throws Exception {
+ CountDownLatch go = new CountDownLatch(1);
+ List> futures = new ArrayList<>();
+ try (ExecutorService clients = Executors.newFixedThreadPool(count)) {
+ for (int i = 0; i < count; i++) {
+ futures.add(clients.submit(() -> {
+ go.await();
+ return get(path);
+ }));
+ }
+ go.countDown();
+ List responses = new ArrayList<>();
+ for (Future future : futures) {
+ responses.add(future.get(60, TimeUnit.SECONDS));
+ }
+ return responses;
+ }
+ }
+
+ private Response send(HttpRequest.Builder request) {
+ try {
+ HttpResponse response = http.send(request.timeout(java.time.Duration.ofSeconds(60)).build(),
+ HttpResponse.BodyHandlers.ofString());
+ return new Response(response.statusCode(), response.body());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Containers.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Containers.java
new file mode 100644
index 0000000..a7b8324
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/Containers.java
@@ -0,0 +1,36 @@
+package com.amigoscode.caching.support;
+
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.lifecycle.Startables;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+import org.testcontainers.utility.DockerImageName;
+
+/**
+ * One Postgres and one Redis for the whole test run, started by Testcontainers (Docker must be
+ * running). Real Redis, because serialization, TTLs and locks are exactly what a fake would get wrong.
+ */
+public final class Containers {
+
+ private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
+ private static final GenericContainer> REDIS =
+ new GenericContainer<>(DockerImageName.parse("redis:8-alpine")).withExposedPorts(6379);
+
+ static {
+ Startables.deepStart(POSTGRES, REDIS).join();
+ }
+
+ private Containers() {
+ }
+
+ public static void database(DynamicPropertyRegistry registry) {
+ registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
+ registry.add("spring.datasource.username", POSTGRES::getUsername);
+ registry.add("spring.datasource.password", POSTGRES::getPassword);
+ }
+
+ public static void redis(DynamicPropertyRegistry registry) {
+ registry.add("spring.data.redis.host", REDIS::getHost);
+ registry.add("spring.data.redis.port", () -> REDIS.getMappedPort(6379));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java
new file mode 100644
index 0000000..c0c08ac
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java
@@ -0,0 +1,65 @@
+package com.amigoscode.caching.support;
+
+import com.amigoscode.caching.product.PriceHistory;
+import java.math.BigDecimal;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Replaces the price history in integration tests. It is called inside the transaction that changes
+ * the price, which makes it the place to stop that transaction just before it commits: the new price
+ * is written but nobody else can see it yet.
+ */
+public class ControllablePriceHistory implements PriceHistory {
+
+ private volatile CountDownLatch commitGate;
+ private volatile CountDownLatch aboutToCommit;
+
+ public void reset() {
+ releaseTheCommit();
+ commitGate = null;
+ aboutToCommit = null;
+ }
+
+ /** The next price change stops right before its commit, until {@link #releaseTheCommit()}. */
+ public void holdTheNextCommit() {
+ aboutToCommit = new CountDownLatch(1);
+ commitGate = new CountDownLatch(1);
+ }
+
+ /** Waits until the held price change has reached its commit. */
+ public void awaitTheCommit() throws InterruptedException {
+ if (!aboutToCommit.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("The price change never reached its commit");
+ }
+ }
+
+ public void releaseTheCommit() {
+ CountDownLatch gate = commitGate;
+ if (gate != null) {
+ gate.countDown();
+ }
+ }
+
+ @Override
+ public void record(long productId, BigDecimal oldPrice, BigDecimal newPrice) {
+ CountDownLatch gate = commitGate;
+ CountDownLatch reached = aboutToCommit;
+ if (gate == null || !TransactionSynchronizationManager.isSynchronizationActive()) {
+ return;
+ }
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+ @Override
+ public void beforeCommit(boolean readOnly) {
+ reached.countDown();
+ try {
+ gate.await(20, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ });
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java
new file mode 100644
index 0000000..dbaec07
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java
@@ -0,0 +1,103 @@
+package com.amigoscode.caching.support;
+
+import com.amigoscode.caching.product.ProductNotFoundException;
+import com.amigoscode.caching.product.ProductSource;
+import com.amigoscode.caching.product.ProductView;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Replaces the slow source in integration tests. It reads the same row from Postgres, counts every
+ * call per product, and can hold callers back, so a test can force "everybody misses the cache at
+ * the same moment" on purpose instead of hoping that threads happen to overlap.
+ */
+public class ControllableProductSource implements ProductSource {
+
+ private static final long MEETING_TIMEOUT_MILLIS = 1500;
+
+ private final JdbcTemplate jdbc;
+ private final Map calls = new ConcurrentHashMap<>();
+ private final AtomicInteger arrivals = new AtomicInteger();
+ private volatile int meetingSize;
+ private volatile CountDownLatch meeting;
+ private volatile CountDownLatch gate;
+
+ public ControllableProductSource(JdbcTemplate jdbc) {
+ this.jdbc = jdbc;
+ }
+
+ public void reset() {
+ release();
+ calls.clear();
+ arrivals.set(0);
+ meetingSize = 0;
+ meeting = null;
+ gate = null;
+ }
+
+ /**
+ * The first {@code callers} wait here until all of them have arrived, so all of them have missed
+ * the cache before any of them can fill it. If the others never arrive (because something made
+ * them wait for the first one) the wait ends after 1.5 seconds.
+ */
+ public void everyoneMissesBeforeAnyoneLoads(int callers) {
+ meetingSize = callers;
+ meeting = new CountDownLatch(callers);
+ }
+
+ /** Every caller stops here until {@link #release()}. */
+ public void holdUntilReleased() {
+ gate = new CountDownLatch(1);
+ }
+
+ public void release() {
+ CountDownLatch current = gate;
+ if (current != null) {
+ current.countDown();
+ }
+ }
+
+ /** How many calls have started, for any product. */
+ public int arrivals() {
+ return arrivals.get();
+ }
+
+ /** How many times product {@code productId} was loaded. */
+ public int calls(long productId) {
+ AtomicInteger count = calls.get(productId);
+ return count == null ? 0 : count.get();
+ }
+
+ @Override
+ public ProductView load(long productId) {
+ calls.computeIfAbsent(productId, id -> new AtomicInteger()).incrementAndGet();
+ int arrival = arrivals.incrementAndGet();
+ try {
+ CountDownLatch currentMeeting = meeting;
+ if (currentMeeting != null && arrival <= meetingSize) {
+ currentMeeting.countDown();
+ currentMeeting.await(MEETING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+ }
+ CountDownLatch currentGate = gate;
+ if (currentGate != null) {
+ currentGate.await(20, TimeUnit.SECONDS);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ List found = jdbc.query("select id, name, price from product where id = ?",
+ (row, i) -> new ProductView(row.getLong("id"), row.getString("name"), row.getObject("price", BigDecimal.class)),
+ productId);
+ if (found.isEmpty()) {
+ throw new ProductNotFoundException(productId);
+ }
+ return found.getFirst();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/IntegrationTest.java b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/IntegrationTest.java
new file mode 100644
index 0000000..cc760c2
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/java/com/amigoscode/caching/support/IntegrationTest.java
@@ -0,0 +1,137 @@
+package com.amigoscode.caching.support;
+
+import java.nio.charset.StandardCharsets;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+
+/**
+ * Base class for the *IT tests. They start the real application on a random port and call it over
+ * HTTP, against a real Postgres and a real Redis. The slow source is replaced by one that counts its
+ * calls and takes no time unless a test holds it back.
+ */
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ properties = {"spring.main.banner-mode=off", "catalogue.source-delay-ms=0"})
+@Import(IntegrationTest.TestBeans.class)
+public abstract class IntegrationTest {
+
+ @DynamicPropertySource
+ static void containers(DynamicPropertyRegistry registry) {
+ Containers.database(registry);
+ Containers.redis(registry);
+ }
+
+ @TestConfiguration
+ public static class TestBeans {
+
+ @Bean
+ @Primary
+ ControllableProductSource controllableProductSource(JdbcTemplate jdbc) {
+ return new ControllableProductSource(jdbc);
+ }
+
+ @Bean
+ @Primary
+ ControllablePriceHistory controllablePriceHistory() {
+ return new ControllablePriceHistory();
+ }
+ }
+
+ @Autowired
+ protected ControllableProductSource source;
+
+ @Autowired
+ protected ControllablePriceHistory priceHistory;
+
+ @Autowired
+ protected JdbcTemplate jdbc;
+
+ @Autowired
+ private RedisConnectionFactory redisConnectionFactory;
+
+ @Value("${local.server.port}")
+ private int port;
+
+ protected Api api;
+
+ @BeforeEach
+ void freshShop() {
+ api = new Api(port);
+ source.reset();
+ priceHistory.reset();
+ resetPrices(jdbc);
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ connection.serverCommands().flushDb();
+ }
+ }
+
+ @AfterEach
+ void letEveryoneGo() {
+ source.release();
+ priceHistory.releaseTheCommit();
+ }
+
+ public static void resetPrices(JdbcTemplate jdbc) {
+ jdbc.update("""
+ update product set price = v.price
+ from (values (1, 89.00), (2, 329.00), (3, 149.00)) as v(id, price)
+ where product.id = v.id
+ """);
+ }
+
+ /** The raw bytes stored under {@code key}, or null. */
+ protected byte[] redisValue(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ return connection.stringCommands().get(key.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+
+ protected boolean redisHasKey(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ return Boolean.TRUE.equals(connection.keyCommands().exists(key.getBytes(StandardCharsets.UTF_8)));
+ }
+ }
+
+ /** Seconds until {@code key} expires: -1 means never, -2 means there is no such key. */
+ protected long redisTtl(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ Long ttl = connection.keyCommands().ttl(key.getBytes(StandardCharsets.UTF_8));
+ return ttl == null ? -2 : ttl;
+ }
+ }
+
+ protected int redisKeyCount() {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ Long size = connection.serverCommands().dbSize();
+ return size == null ? 0 : size.intValue();
+ }
+ }
+
+ protected String priceInDatabase(long productId) {
+ return jdbc.queryForObject("select price::text from product where id = ?", String.class, productId);
+ }
+
+ /** Bytes as text, with anything that is not printable ASCII shown as \xNN. */
+ protected static String printable(byte[] value) {
+ if (value == null) {
+ return "(no value)";
+ }
+ StringBuilder text = new StringBuilder();
+ for (byte b : value) {
+ int c = b & 0xff;
+ text.append(c >= 0x20 && c < 0x7f ? String.valueOf((char) c) : String.format("\\x%02x", c));
+ }
+ return text.length() > 90 ? text.substring(0, 90) + "..." : text.toString();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/resources/logback-test.xml
new file mode 100644
index 0000000..4db5b14
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/solution/src/test/resources/logback-test.xml
@@ -0,0 +1,13 @@
+
+
+
+ %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n
+
+
+
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/.mvn/jvm.config b/java/concepts/junior-mid/12-caching-with-redis/start/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/12-caching-with-redis/start/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/.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.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/check b/java/concepts/junior-mid/12-caching-with-redis/start/check
new file mode 100755
index 0000000..8d362c5
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.caching.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/check.cmd b/java/concepts/junior-mid/12-caching-with-redis/start/check.cmd
new file mode 100644
index 0000000..48286b1
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.caching.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/compose.yaml b/java/concepts/junior-mid/12-caching-with-redis/start/compose.yaml
new file mode 100644
index 0000000..24030b7
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/compose.yaml
@@ -0,0 +1,28 @@
+# The project name is set here because the folder is called "solution" (or "start") in every
+# project of this repository: without it, "docker compose down" in another project would stop this one.
+name: caching-with-redis
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: caching-with-redis-postgres
+ environment:
+ POSTGRES_DB: catalogue
+ POSTGRES_USER: catalogue
+ POSTGRES_PASSWORD: catalogue
+ ports:
+ - "5451:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U catalogue -d catalogue"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
+ redis:
+ image: redis:8-alpine
+ container_name: caching-with-redis-redis
+ ports:
+ - "6390:6379"
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/demo b/java/concepts/junior-mid/12-caching-with-redis/start/demo
new file mode 100755
index 0000000..6499539
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.caching.demo.Demo -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/demo.cmd b/java/concepts/junior-mid/12-caching-with-redis/start/demo.cmd
new file mode 100644
index 0000000..0dbf2f4
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.caching.demo.Demo" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/inspect b/java/concepts/junior-mid/12-caching-with-redis/start/inspect
new file mode 100755
index 0000000..22e3eb7
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.caching.demo.Inspect -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/inspect.cmd b/java/concepts/junior-mid/12-caching-with-redis/start/inspect.cmd
new file mode 100644
index 0000000..2938c9c
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.caching.demo.Inspect" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/mvnw b/java/concepts/junior-mid/12-caching-with-redis/start/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/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/java/concepts/junior-mid/12-caching-with-redis/start/mvnw.cmd b/java/concepts/junior-mid/12-caching-with-redis/start/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/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/java/concepts/junior-mid/12-caching-with-redis/start/pom.xml b/java/concepts/junior-mid/12-caching-with-redis/start/pom.xml
new file mode 100644
index 0000000..0663fa6
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/pom.xml
@@ -0,0 +1,121 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ caching-with-redis
+ 0.0.1-SNAPSHOT
+ caching-with-redis
+ Caching with Redis: watch every request hit a slow source, cache it, then fix stale data, self-invocation, TTLs and the stampede
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ org.springframework.boot
+ spring-boot-starter-cache
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+
+ org.testcontainers
+ testcontainers
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java
new file mode 100644
index 0000000..9e030b2
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/ApiExceptionHandler.java
@@ -0,0 +1,30 @@
+package com.amigoscode.caching;
+
+import com.amigoscode.caching.product.InvalidRequestException;
+import com.amigoscode.caching.product.ProductNotFoundException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/** Anything not listed here, including "Redis is not reachable" or a value Redis cannot serialize, becomes a 500. */
+@RestControllerAdvice
+public class ApiExceptionHandler {
+
+ public record ApiError(String code, String message) {
+ }
+
+ @ExceptionHandler(ProductNotFoundException.class)
+ public ResponseEntity notFound(ProductNotFoundException e) {
+ return error(HttpStatus.NOT_FOUND, "PRODUCT_NOT_FOUND", e);
+ }
+
+ @ExceptionHandler(InvalidRequestException.class)
+ public ResponseEntity badRequest(InvalidRequestException e) {
+ return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", e);
+ }
+
+ private static ResponseEntity error(HttpStatus status, String code, RuntimeException e) {
+ return ResponseEntity.status(status).body(new ApiError(code, e.getMessage()));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/CachingApplication.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/CachingApplication.java
new file mode 100644
index 0000000..5fd7cce
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/CachingApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.caching;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CachingApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CachingApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/cache/CacheConfig.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/cache/CacheConfig.java
new file mode 100644
index 0000000..72419af
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/cache/CacheConfig.java
@@ -0,0 +1,11 @@
+package com.amigoscode.caching.cache;
+
+import org.springframework.context.annotation.Configuration;
+
+/** Caching configuration. Empty for now: nothing is cached yet. */
+@Configuration
+public class CacheConfig {
+
+ /** The name of the cache for products. Its keys in Redis will start with "products::". */
+ public static final String PRODUCTS = "products";
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Db.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Db.java
new file mode 100644
index 0000000..6ae725a
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Db.java
@@ -0,0 +1,35 @@
+package com.amigoscode.caching.demo;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/** Postgres connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5451/catalogue");
+ static final String USER = env("DB_USER", "catalogue");
+ static final String PASSWORD = env("DB_PASSWORD", "catalogue");
+
+ private Db() {
+ }
+
+ static Connection connect() throws SQLException {
+ return DriverManager.getConnection(URL, USER, PASSWORD);
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ Redis.printNotReachable("Postgres at " + URL, e.getMessage());
+ return false;
+ }
+ }
+
+ static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Demo.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Demo.java
new file mode 100644
index 0000000..540789b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Demo.java
@@ -0,0 +1,534 @@
+package com.amigoscode.caching.demo;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.turbo.TurboFilter;
+import ch.qos.logback.core.spi.FilterReply;
+import com.amigoscode.caching.CachingApplication;
+import com.amigoscode.caching.product.SlowProductSource;
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Marker;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Starts the real application, sends requests at it over HTTP, and counts how many of them had to
+ * call the slow source. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags.
+ */
+public final class Demo {
+
+ private static final List SCENARIOS = List.of("repeat", "update", "basket", "stampede", "redis-down");
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+ private static final Pattern CODE = Pattern.compile("\"code\"\\s*:\\s*\"([A-Z_]+)\"");
+ private static final Pattern MESSAGE = Pattern.compile("\"message\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
+ private static final String NEW_PRICE = "79.00";
+ private static final AtomicReference SERVER_ERROR = new AtomicReference<>();
+
+ private record Options(String scenario, int requests, long delayMillis, Integer ttlSeconds) {
+ }
+
+ private record Response(int status, String body, long millis, int sourceCalls) {
+
+ String price() {
+ return find(PRICE, body);
+ }
+
+ String describe() {
+ if (status == 200) {
+ List prices = new ArrayList<>();
+ Matcher matcher = PRICE.matcher(body);
+ while (matcher.find()) {
+ prices.add(matcher.group(1));
+ }
+ return "200 price " + String.join(", ", prices);
+ }
+ String code = find(CODE, body);
+ String message = find(MESSAGE, body);
+ String text = code != null ? code : message == null ? "" : message;
+ if (text.length() > 80) {
+ text = text.substring(0, 80) + "...";
+ }
+ return status + (text.isEmpty() ? "" : " " + text);
+ }
+ }
+
+ private final Options options;
+ private final ConfigurableApplicationContext context;
+ private final SlowProductSource source;
+ private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ private final String baseUrl;
+
+ private Demo(Options options, ConfigurableApplicationContext context) {
+ this.options = options;
+ this.context = context;
+ this.source = context.getBean(SlowProductSource.class);
+ this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ boolean redisDown = options.scenario().equals("redis-down");
+ if (!Db.isUp()) {
+ return;
+ }
+ if (!redisDown) {
+ Redis redis = Redis.connectOrExplain();
+ if (redis == null) {
+ return;
+ }
+ redis.close();
+ }
+
+ List springArgs = new ArrayList<>(List.of(
+ "--server.port=0",
+ "--logging.level.root=WARN",
+ "--logging.level.io.netty.resolver.dns=ERROR",
+ "--spring.web.error.include-message=always",
+ "--catalogue.source-delay-ms=" + options.delayMillis()));
+ if (options.ttlSeconds() != null) {
+ springArgs.add("--catalogue.cache.products-ttl=" + options.ttlSeconds() + "s");
+ }
+ if (redisDown) {
+ springArgs.add("--spring.data.redis.port=" + closedPort());
+ springArgs.add("--spring.data.redis.timeout=1s");
+ springArgs.add("--spring.data.redis.connect-timeout=1s");
+ }
+
+ SpringApplication app = new SpringApplication(CachingApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) {
+ captureServerErrors();
+ new Demo(options, context).run();
+ }
+ }
+
+ private void run() throws Exception {
+ resetDatabase();
+ if (!options.scenario().equals("redis-down")) {
+ redis(connection -> connection.serverCommands().flushDb());
+ }
+ // One throwaway request so the first real one is not slowed down by startup work.
+ http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding());
+
+ System.out.println();
+ switch (options.scenario()) {
+ case "repeat" -> repeat();
+ case "update" -> update();
+ case "basket" -> basket();
+ case "stampede" -> stampede();
+ default -> redisDown();
+ }
+ System.out.println();
+ }
+
+ // ---------------------------------------------------------------- scenarios
+
+ private void repeat() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: repeat | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The same product page is opened " + n + " times, one request after the other.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ long startedAt = System.nanoTime();
+ int failed = 0;
+ Response firstFailure = null;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products/1");
+ if (response.status() != 200) {
+ failed++;
+ firstFailure = firstFailure == null ? response : firstFailure;
+ }
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Request " + pad(i, n), "GET /api/products/1", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ long millis = millisSince(startedAt);
+ int calls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Requests: " + n);
+ System.out.println("Calls to the slow source: " + calls);
+ System.out.println("Time taken: " + millis + " ms (" + (millis / n) + " ms per request)");
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " requests failed: " + firstFailure.describe() + serverError());
+ } else if (n > 1 && calls >= n) {
+ System.out.println("RESULT: NO CACHE. " + n + " requests, " + calls
+ + " calls to the slow source: every request paid the full " + options.delayMillis() + " ms.");
+ } else if (n == 1) {
+ System.out.println("RESULT: OK. 1 request, " + calls + " " + plural(calls, "call")
+ + " to the slow source. The first request for a product always has to load it.");
+ } else {
+ System.out.println("RESULT: OK. " + n + " requests, " + calls + " " + plural(calls, "call")
+ + " to the slow source. " + (n - calls == 1 ? "The other request was" : "The other " + (n - calls) + " were")
+ + " answered from Redis.");
+ }
+ }
+
+ private void update() throws Exception {
+ System.out.println("Scenario: update | slow source: " + options.delayMillis() + " ms");
+ System.out.println("Read product 1, change its price to " + NEW_PRICE + ", read it again.");
+ System.out.println();
+
+ Response first = get("/api/products/1");
+ printStep("Step 1", "GET /api/products/1", first);
+ Response second = get("/api/products/1");
+ printStep("Step 2", "GET /api/products/1", second);
+ Response put = send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/products/1/price"))
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString("{\"price\":" + NEW_PRICE + "}")));
+ printStep("Step 3", "PUT /api/products/1/price " + NEW_PRICE, put);
+ Response after = get("/api/products/1");
+ printStep("Step 4", "GET /api/products/1", after);
+
+ String inDatabase = context.getBean(JdbcTemplate.class)
+ .queryForObject("select price::text from product where id = 1", String.class);
+ System.out.println();
+ System.out.println("Price in the database: " + inDatabase);
+ System.out.println("Price GET returned: " + after.price());
+ System.out.println();
+ if (first.status() != 200 || put.status() != 200 || after.status() != 200) {
+ System.out.println("RESULT: ERROR. A request failed: " + (put.status() != 200 ? put : after).describe() + serverError());
+ } else if (!inDatabase.equals(after.price())) {
+ System.out.println("RESULT: STALE. The price was changed to " + inDatabase + ", but GET still returns "
+ + after.price() + " from the cache.");
+ } else {
+ System.out.println("RESULT: OK. GET returns the new price, " + inDatabase + ".");
+ }
+ }
+
+ private void basket() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: basket | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The product page for product 1 is opened twice, then the basket page with products 1, 2 and 3 "
+ + n + " times.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ printStep("Product page", "GET /api/products/1", get("/api/products/1"));
+ printStep("Product page", "GET /api/products/1", get("/api/products/1"));
+ int productPageCalls = source.calls() - callsBefore;
+
+ callsBefore = source.calls();
+ int failed = 0;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products?ids=1,2,3");
+ failed += response.status() == 200 ? 0 : 1;
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Basket " + pad(i, n), "GET /api/products?ids=1,2,3", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ int basketCalls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Calls to the slow source, product page (2 requests): " + productPageCalls);
+ System.out.println("Calls to the slow source, basket (" + n + " requests x 3 products): " + basketCalls);
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " basket requests failed." + serverError());
+ } else if (productPageCalls == 2 && basketCalls >= n * 3) {
+ System.out.println("RESULT: NOT CACHED. Nothing is cached yet: the product page and the basket call the slow source"
+ + " for every product, every time.");
+ } else if (basketCalls >= n * 3) {
+ System.out.println("RESULT: NOT CACHED. The basket called the slow source " + basketCalls
+ + " times for 3 products. Product 1 was already in the cache, and the basket did not even look.");
+ } else {
+ System.out.println("RESULT: OK. The basket called the slow source " + basketCalls + " "
+ + plural(basketCalls, "time") + ": only for the products that were not cached yet.");
+ }
+ }
+
+ private void stampede() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: stampede | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("Products 1 and 2 are read once, to fill the cache. Then the entry for product 1 expires, and "
+ + n + " requests for it arrive at the same moment.");
+ System.out.println();
+
+ get("/api/products/1");
+ get("/api/products/2");
+ redis(connection -> connection.keyCommands().del("products::1".getBytes()));
+ System.out.println(" products::1 removed from Redis, as if its TTL had just run out.");
+ System.out.println();
+
+ int callsBefore = source.calls(1);
+ CountDownLatch go = new CountDownLatch(1);
+ List> futures = new ArrayList<>();
+ Future otherProduct;
+ long startedAt;
+ try (ExecutorService clients = Executors.newVirtualThreadPerTaskExecutor()) {
+ for (int i = 0; i < n; i++) {
+ futures.add(clients.submit(() -> {
+ go.await();
+ return get("/api/products/1");
+ }));
+ }
+ // A little later, somebody opens product 2, which is still in the cache.
+ otherProduct = clients.submit(() -> {
+ go.await();
+ Thread.sleep(Math.min(50, Math.max(1, options.delayMillis() / 4)));
+ return get("/api/products/2");
+ });
+ startedAt = System.nanoTime();
+ go.countDown();
+ }
+ long millis = millisSince(startedAt);
+ int calls = source.calls(1) - callsBefore;
+ int failed = 0;
+ for (Future future : futures) {
+ failed += future.get().status() == 200 ? 0 : 1;
+ }
+ Response other = otherProduct.get();
+
+ System.out.println("Requests for product 1: " + n + ", all at the same moment");
+ System.out.println("Slow source calls for product 1: " + calls);
+ System.out.println("Failed requests: " + failed);
+ System.out.println("Time taken: " + millis + " ms");
+ System.out.println("Meanwhile, GET /api/products/2: " + other.millis() + " ms");
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: ERROR. " + failed + " of " + n + " requests failed." + serverError());
+ } else if (calls > 1) {
+ System.out.println("RESULT: STAMPEDE. " + n + " requests missed the cache together and " + calls
+ + " of them called the slow source for the same product.");
+ } else {
+ System.out.println("RESULT: OK. " + n + " requests missed the cache together, " + calls
+ + " called the slow source, the others waited and read the result from Redis.");
+ }
+ }
+
+ private void redisDown() throws Exception {
+ int n = options.requests();
+ System.out.println("Scenario: redis-down | requests: " + n + " | slow source: " + options.delayMillis() + " ms");
+ System.out.println("The application is pointed at a Redis that is not there, then asked for product 1 "
+ + n + " times.");
+ System.out.println();
+
+ int callsBefore = source.calls();
+ int failed = 0;
+ Response firstFailure = null;
+ for (int i = 1; i <= n; i++) {
+ Response response = get("/api/products/1");
+ if (response.status() != 200) {
+ failed++;
+ firstFailure = firstFailure == null ? response : firstFailure;
+ }
+ if (n <= 10 || i <= 5 || i == n) {
+ printStep("Request " + pad(i, n), "GET /api/products/1", response);
+ } else if (i == 6) {
+ System.out.println(" ...");
+ }
+ }
+ int calls = source.calls() - callsBefore;
+
+ System.out.println();
+ System.out.println("Requests: " + n);
+ System.out.println("Failed requests: " + failed);
+ System.out.println("Calls to the slow source: " + calls);
+ System.out.println();
+ if (failed > 0) {
+ System.out.println("RESULT: DOWN. Redis is not reachable, so " + failed + " of " + n
+ + " requests failed: " + firstFailure.describe() + serverError());
+ } else {
+ System.out.println("RESULT: OK. Redis is not reachable, and all " + n
+ + " requests were answered from the slow source instead.");
+ }
+ }
+
+ // ---------------------------------------------------------------- helpers
+
+ private Response get(String path) throws IOException, InterruptedException {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET());
+ }
+
+ private Response send(HttpRequest.Builder request) throws IOException, InterruptedException {
+ int callsBefore = source.calls();
+ long startedAt = System.nanoTime();
+ HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
+ return new Response(response.statusCode(), response.body(), millisSince(startedAt), source.calls() - callsBefore);
+ }
+
+ private static void printStep(String label, String request, Response response) {
+ String source = response.sourceCalls() == 0 ? "slow source not called"
+ : "slow source called" + (response.sourceCalls() > 1 ? " " + response.sourceCalls() + " times" : "");
+ System.out.printf(" %-14s %-34s <- %-26s %5d ms %s%n", label, request, response.describe(), response.millis(), source);
+ }
+
+ /**
+ * A 500 is logged by Tomcat with a long stack trace. Keep only the root cause, and print it in
+ * the RESULT line instead. Added after startup, because Spring Boot resets logging when it starts.
+ */
+ private static void captureServerErrors() {
+ LoggerContext logging = (LoggerContext) LoggerFactory.getILoggerFactory();
+ logging.addTurboFilter(new TurboFilter() {
+ @Override
+ public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
+ if (t == null || !logger.getName().startsWith("org.apache.catalina.core.ContainerBase")) {
+ return FilterReply.NEUTRAL;
+ }
+ Throwable root = t;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ SERVER_ERROR.compareAndSet(null, root.getClass().getSimpleName() + ": " + root.getMessage());
+ return FilterReply.DENY;
+ }
+ });
+ }
+
+ /** " Cause: ..." for the first 500 the server logged, or nothing. */
+ private static String serverError() {
+ String error = SERVER_ERROR.get();
+ return error == null ? "" : System.lineSeparator() + " Cause: " + error;
+ }
+
+ private void resetDatabase() {
+ JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
+ jdbc.execute("truncate table price_change restart identity");
+ jdbc.update("""
+ update product set price = v.price
+ from (values (1, 89.00), (2, 329.00), (3, 149.00)) as v(id, price)
+ where product.id = v.id
+ """);
+ }
+
+ private interface RedisWork {
+ void run(RedisConnection connection);
+ }
+
+ private void redis(RedisWork work) {
+ try (RedisConnection connection = context.getBean(RedisConnectionFactory.class).getConnection()) {
+ work.run(connection);
+ }
+ }
+
+ private static int closedPort() throws IOException {
+ try (ServerSocket socket = new ServerSocket(0)) {
+ return socket.getLocalPort();
+ }
+ }
+
+ private static long millisSince(long nanos) {
+ return (System.nanoTime() - nanos) / 1_000_000;
+ }
+
+ private static String pad(int i, int n) {
+ return String.format("%" + String.valueOf(n).length() + "d", i);
+ }
+
+ private static String plural(int count, String word) {
+ return count == 1 ? word : word + "s";
+ }
+
+ private static String find(Pattern pattern, String body) {
+ Matcher matcher = pattern.matcher(body == null ? "" : body);
+ return matcher.find() ? matcher.group(1) : null;
+ }
+
+ private static Options parse(String[] args) {
+ String scenario = "repeat";
+ Integer requests = null;
+ long delayMillis = 200;
+ Integer ttlSeconds = null;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--scenario" -> {
+ scenario = value(args, ++i, arg);
+ if (!SCENARIOS.contains(scenario)) {
+ throw new IllegalArgumentException("Unknown scenario: " + scenario + ". Use one of " + SCENARIOS);
+ }
+ }
+ case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 500);
+ case "--delay-ms" -> delayMillis = number(value(args, ++i, arg), arg, 0, 60_000);
+ case "--ttl" -> ttlSeconds = number(value(args, ++i, arg), arg, 1, 86_400);
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ int defaultRequests = switch (scenario) {
+ case "basket", "redis-down" -> 5;
+ default -> 20;
+ };
+ return new Options(scenario, requests == null ? defaultRequests : requests, delayMillis, ttlSeconds);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static int number(String value, String option, int min, int max) {
+ try {
+ int number = Integer.parseInt(value);
+ if (number < min || number > max) {
+ throw new NumberFormatException();
+ }
+ return number;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value);
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --scenario what to run (default: repeat)");
+ System.out.println(" repeat the same product page, many times in a row");
+ System.out.println(" update read a product, change its price, read it again");
+ System.out.println(" basket the basket page, which shows products 1, 2 and 3");
+ System.out.println(" stampede a cached product expires and many requests arrive at once");
+ System.out.println(" redis-down the application cannot reach Redis");
+ System.out.println(" --requests how many requests (default: 20; basket and redis-down: 5)");
+ System.out.println(" --delay-ms how long the slow source takes per product (default: 200)");
+ System.out.println(" --ttl how long a cached product lives, instead of catalogue.cache.products-ttl");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --scenario update");
+ System.out.println(" ./demo --scenario stampede --requests 50");
+ System.out.println(" ./demo --requests 1 --ttl 15 then ./inspect --watch, and see the entry expire");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Inspect.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Inspect.java
new file mode 100644
index 0000000..10cf400
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Inspect.java
@@ -0,0 +1,192 @@
+package com.amigoscode.caching.demo;
+
+import io.lettuce.core.KeyScanCursor;
+import io.lettuce.core.ScanArgs;
+import io.lettuce.core.ScanCursor;
+import io.lettuce.core.api.sync.RedisCommands;
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Shows what is in Redis right now (every key, its TTL and its value, byte for byte) and puts each
+ * product row from Postgres next to its cached copy, so a stale entry is easy to see. Run it with
+ * ./inspect (or .\inspect on Windows).
+ */
+public final class Inspect {
+
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+ private static final int VALUE_WIDTH = 72;
+
+ public static void main(String[] args) throws Exception {
+ boolean watch = false;
+ for (String arg : args) {
+ if (arg.equals("--watch")) {
+ watch = true;
+ } else {
+ System.out.println("Usage: ./inspect [--watch] (Windows: .\\inspect [--watch])");
+ System.out.println();
+ System.out.println(" --watch refresh every second for one minute (Ctrl+C to stop)");
+ return;
+ }
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Redis redis = Redis.connectOrExplain(); Connection db = redis == null ? null : Db.connect()) {
+ if (redis == null) {
+ return;
+ }
+ int rounds = watch ? 60 : 1;
+ for (int round = 0; round < rounds; round++) {
+ snapshot(redis.commands(), db);
+ if (round < rounds - 1) {
+ Thread.sleep(1000);
+ }
+ }
+ }
+ }
+
+ private static void snapshot(RedisCommands redis, Connection db) throws SQLException {
+ System.out.println();
+ System.out.println("==== " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) + " ====");
+ System.out.println();
+
+ List keys = keys(redis);
+ Map values = new HashMap<>();
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"key", "ttl", "bytes", "value"});
+ for (String key : keys) {
+ byte[] name = key.getBytes(StandardCharsets.UTF_8);
+ long ttl = redis.ttl(name);
+ byte[] value = "string".equals(redis.type(name)) ? redis.get(name) : null;
+ if (value != null) {
+ values.put(key, value);
+ }
+ rows.add(new String[] {
+ key,
+ ttl == -1 ? "-1 (never expires)" : ttl == -2 ? "gone" : ttl + " s",
+ value == null ? "" : String.valueOf(value.length),
+ value == null ? "(" + redis.type(name) + ")" : printable(value)});
+ }
+ System.out.println("REDIS " + Redis.HOST + ":" + Redis.PORT + " (" + keys.size() + " " + (keys.size() == 1 ? "key" : "keys") + ")");
+ if (keys.isEmpty()) {
+ System.out.println(" empty. Nothing has been cached.");
+ } else {
+ printTable(rows);
+ }
+
+ System.out.println();
+ System.out.println("POSTGRES NEXT TO THE CACHE");
+ List products = new ArrayList<>();
+ products.add(new String[] {"id", "name", "price_in_db", "cached_as", "price_in_cache", "verdict"});
+ try (Statement statement = db.createStatement();
+ ResultSet result = statement.executeQuery("select id, name, price::text from product order by id")) {
+ while (result.next()) {
+ String id = result.getString(1);
+ String price = result.getString(3);
+ String key = "products::" + id;
+ byte[] value = values.get(key);
+ String cachedPrice;
+ String verdict;
+ if (value == null) {
+ cachedPrice = "";
+ verdict = "not cached";
+ } else if (value.length > 0 && value[0] == '{') {
+ Matcher matcher = PRICE.matcher(new String(value, StandardCharsets.UTF_8));
+ cachedPrice = matcher.find() ? matcher.group(1) : "?";
+ verdict = cachedPrice.equals(price) ? "same" : "STALE";
+ } else {
+ cachedPrice = "(not JSON)";
+ verdict = "cannot tell: Java serialization";
+ }
+ products.add(new String[] {id, result.getString(2), price, value == null ? "" : key, cachedPrice, verdict});
+ }
+ }
+ printTable(products);
+
+ System.out.println();
+ System.out.println("PRICE CHANGES (newest first)");
+ List changes = new ArrayList<>();
+ changes.add(new String[] {"product_id", "old_price", "new_price", "changed_at"});
+ try (Statement statement = db.createStatement();
+ ResultSet result = statement.executeQuery("""
+ select product_id, old_price::text, new_price::text, to_char(changed_at, 'HH24:MI:SS.MS')
+ from price_change order by id desc limit 5
+ """)) {
+ while (result.next()) {
+ changes.add(new String[] {result.getString(1), result.getString(2), result.getString(3), result.getString(4)});
+ }
+ }
+ if (changes.size() == 1) {
+ System.out.println(" none");
+ } else {
+ printTable(changes);
+ }
+ }
+
+ private static List keys(RedisCommands redis) {
+ List keys = new ArrayList<>();
+ ScanCursor cursor = ScanCursor.INITIAL;
+ do {
+ KeyScanCursor page = redis.scan(cursor, ScanArgs.Builder.limit(100));
+ page.getKeys().forEach(key -> keys.add(new String(key, StandardCharsets.UTF_8)));
+ cursor = page;
+ } while (!cursor.isFinished());
+ keys.sort(null);
+ return keys;
+ }
+
+ /** The value as text, with every byte that is not printable ASCII shown as \xNN. */
+ private static String printable(byte[] value) {
+ StringBuilder text = new StringBuilder();
+ for (byte b : value) {
+ int c = b & 0xff;
+ if (c >= 0x20 && c < 0x7f) {
+ text.append((char) c);
+ } else {
+ text.append(String.format("\\x%02x", c));
+ }
+ if (text.length() >= VALUE_WIDTH) {
+ return text.substring(0, VALUE_WIDTH) + "...";
+ }
+ }
+ return text.toString();
+ }
+
+ private static void printTable(List rows) {
+ int[] widths = new int[rows.get(0).length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Redis.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Redis.java
new file mode 100644
index 0000000..890b82d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/demo/Redis.java
@@ -0,0 +1,79 @@
+package com.amigoscode.caching.demo;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.LoggerContext;
+import io.lettuce.core.RedisClient;
+import io.lettuce.core.RedisURI;
+import io.lettuce.core.api.StatefulRedisConnection;
+import io.lettuce.core.codec.ByteArrayCodec;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Talks to Redis straight from Java with Lettuce, the client Spring uses, so nobody needs redis-cli.
+ * Same defaults as application.properties.
+ */
+final class Redis implements AutoCloseable {
+
+ static final String HOST = Db.env("REDIS_HOST", "localhost");
+ static final int PORT = Integer.parseInt(Db.env("REDIS_PORT", "6390"));
+
+ private final RedisClient client;
+ private final StatefulRedisConnection connection;
+
+ private Redis() {
+ quietLogging();
+ RedisURI uri = RedisURI.builder().withHost(HOST).withPort(PORT).withTimeout(Duration.ofSeconds(2)).build();
+ client = RedisClient.create(uri);
+ try {
+ connection = client.connect(ByteArrayCodec.INSTANCE);
+ } catch (RuntimeException e) {
+ client.shutdown(Duration.ZERO, Duration.ofSeconds(1));
+ throw e;
+ }
+ }
+
+ /** Connects, or prints what to do and returns null when Redis is not reachable. */
+ static Redis connectOrExplain() {
+ try {
+ return new Redis();
+ } catch (RuntimeException e) {
+ printNotReachable("Redis at " + HOST + ":" + PORT, e.getMessage());
+ return null;
+ }
+ }
+
+ io.lettuce.core.api.sync.RedisCommands commands() {
+ return connection.sync();
+ }
+
+ @Override
+ public void close() {
+ connection.close();
+ client.shutdown(Duration.ZERO, Duration.ofSeconds(1));
+ }
+
+ static byte[] bytes(String text) {
+ return text.getBytes(StandardCharsets.UTF_8);
+ }
+
+ static void printNotReachable(String what, String error) {
+ System.out.println();
+ System.out.println("Cannot reach " + what);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + (error == null ? "" : error.lines().findFirst().orElse("")) + ")");
+ }
+
+ /** Netty and Lettuce log at DEBUG when nothing else configures logging. Keep the output readable. */
+ static void quietLogging() {
+ if (LoggerFactory.getILoggerFactory() instanceof LoggerContext context) {
+ context.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.WARN);
+ context.getLogger("io.netty.resolver.dns").setLevel(Level.ERROR);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java
new file mode 100644
index 0000000..9572e64
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/InvalidRequestException.java
@@ -0,0 +1,9 @@
+package com.amigoscode.caching.product;
+
+/** The client sent something the API cannot accept. Becomes a 400. */
+public class InvalidRequestException extends RuntimeException {
+
+ public InvalidRequestException(String message) {
+ super(message);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java
new file mode 100644
index 0000000..48a24a8
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/JdbcPriceHistory.java
@@ -0,0 +1,21 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+
+@Component
+public class JdbcPriceHistory implements PriceHistory {
+
+ private final JdbcTemplate jdbc;
+
+ public JdbcPriceHistory(JdbcTemplate jdbc) {
+ this.jdbc = jdbc;
+ }
+
+ @Override
+ public void record(long productId, BigDecimal oldPrice, BigDecimal newPrice) {
+ jdbc.update("insert into price_change (product_id, old_price, new_price) values (?, ?, ?)",
+ productId, oldPrice, newPrice);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/PriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/PriceHistory.java
new file mode 100644
index 0000000..d123fd3
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/PriceHistory.java
@@ -0,0 +1,9 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+
+/** Writes down every price change. Called inside the transaction that changes the price. */
+public interface PriceHistory {
+
+ void record(long productId, BigDecimal oldPrice, BigDecimal newPrice);
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/Product.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/Product.java
new file mode 100644
index 0000000..26ff34c
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/Product.java
@@ -0,0 +1,35 @@
+package com.amigoscode.caching.product;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import java.math.BigDecimal;
+
+@Entity
+public class Product {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ private BigDecimal price;
+
+ protected Product() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void changePrice(BigDecimal newPrice) {
+ this.price = newPrice;
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductController.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductController.java
new file mode 100644
index 0000000..ca9fa70
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductController.java
@@ -0,0 +1,47 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+import java.util.List;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/products")
+public class ProductController {
+
+ public record PriceChange(BigDecimal price) {
+ }
+
+ private final ProductService productService;
+
+ public ProductController(ProductService productService) {
+ this.productService = productService;
+ }
+
+ @GetMapping("/{id}")
+ public ProductView product(@PathVariable long id) {
+ return productService.findById(id);
+ }
+
+ /** The basket page: GET /api/products?ids=1,2,3 returns the products in the order asked for. */
+ @GetMapping(params = "ids")
+ public List basket(@RequestParam List ids) {
+ if (ids.isEmpty() || ids.size() > 50) {
+ throw new InvalidRequestException("ids must list 1 to 50 product ids");
+ }
+ return productService.findAll(ids);
+ }
+
+ @PutMapping("/{id}/price")
+ public ProductView changePrice(@PathVariable long id, @RequestBody PriceChange change) {
+ if (change == null || change.price() == null || change.price().signum() <= 0) {
+ throw new InvalidRequestException("price must be greater than 0");
+ }
+ return productService.changePrice(id, change.price());
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java
new file mode 100644
index 0000000..fd35269
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductNotFoundException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.caching.product;
+
+public class ProductNotFoundException extends RuntimeException {
+
+ public ProductNotFoundException(long productId) {
+ super("Product " + productId + " does not exist");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductRepository.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductRepository.java
new file mode 100644
index 0000000..cfdc3ea
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductRepository.java
@@ -0,0 +1,6 @@
+package com.amigoscode.caching.product;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface ProductRepository extends JpaRepository {
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductService.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductService.java
new file mode 100644
index 0000000..9792aad
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductService.java
@@ -0,0 +1,39 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+import java.util.List;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class ProductService {
+
+ private final ProductSource source;
+ private final ProductRepository products;
+ private final PriceHistory priceHistory;
+
+ public ProductService(ProductSource source, ProductRepository products, PriceHistory priceHistory) {
+ this.source = source;
+ this.products = products;
+ this.priceHistory = priceHistory;
+ }
+
+ /** The product page. Every call goes to the slow source. */
+ public ProductView findById(long productId) {
+ return source.load(productId);
+ }
+
+ /** The basket page: every product in the basket, in the order asked for. */
+ public List findAll(List productIds) {
+ return productIds.stream().map(this::findById).toList();
+ }
+
+ @Transactional
+ public ProductView changePrice(long productId, BigDecimal newPrice) {
+ Product product = products.findById(productId).orElseThrow(() -> new ProductNotFoundException(productId));
+ BigDecimal oldPrice = product.getPrice();
+ product.changePrice(newPrice);
+ priceHistory.record(productId, oldPrice, newPrice);
+ return ProductView.of(product);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductSource.java
new file mode 100644
index 0000000..4872622
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductSource.java
@@ -0,0 +1,11 @@
+package com.amigoscode.caching.product;
+
+/**
+ * Where product data really comes from. Loading one product is slow: in a real shop this is a query
+ * that joins prices, stock and reviews, or a call to another service. This is what a cache protects.
+ */
+public interface ProductSource {
+
+ /** Loads the product with its current price, or throws {@link ProductNotFoundException}. */
+ ProductView load(long productId);
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductView.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductView.java
new file mode 100644
index 0000000..3a76b81
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/ProductView.java
@@ -0,0 +1,11 @@
+package com.amigoscode.caching.product;
+
+import java.math.BigDecimal;
+
+/** What GET /api/products/{id} returns, and what gets cached. */
+public record ProductView(long id, String name, BigDecimal price) {
+
+ static ProductView of(Product product) {
+ return new ProductView(product.getId(), product.getName(), product.getPrice());
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/SlowProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/SlowProductSource.java
new file mode 100644
index 0000000..8fdf753
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/java/com/amigoscode/caching/product/SlowProductSource.java
@@ -0,0 +1,52 @@
+package com.amigoscode.caching.product;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * Reads the product from Postgres, after waiting catalogue.source-delay-ms (200 ms by default) to
+ * stand in for the expensive part. Counts every call, so the demo can show how often it was asked.
+ */
+@Component
+public class SlowProductSource implements ProductSource {
+
+ private final ProductRepository products;
+ private final long delayMillis;
+ private final AtomicInteger calls = new AtomicInteger();
+ private final Map callsPerProduct = new ConcurrentHashMap<>();
+
+ public SlowProductSource(ProductRepository products, @Value("${catalogue.source-delay-ms}") long delayMillis) {
+ this.products = products;
+ this.delayMillis = delayMillis;
+ }
+
+ @Override
+ public ProductView load(long productId) {
+ calls.incrementAndGet();
+ callsPerProduct.computeIfAbsent(productId, id -> new AtomicInteger()).incrementAndGet();
+ if (delayMillis > 0) {
+ try {
+ Thread.sleep(delayMillis);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+ return products.findById(productId).map(ProductView::of)
+ .orElseThrow(() -> new ProductNotFoundException(productId));
+ }
+
+ /** How many times load was called since the application started. */
+ public int calls() {
+ return calls.get();
+ }
+
+ /** How many times product {@code productId} was loaded since the application started. */
+ public int calls(long productId) {
+ AtomicInteger count = callsPerProduct.get(productId);
+ return count == null ? 0 : count.get();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/application.properties b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/application.properties
new file mode 100644
index 0000000..68df201
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/application.properties
@@ -0,0 +1,19 @@
+spring.application.name=caching-with-redis
+
+# Postgres and Redis from compose.yaml. Ports 5451 and 6390 so they do not clash with ones you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5451/catalogue}
+spring.datasource.username=${DB_USER:catalogue}
+spring.datasource.password=${DB_PASSWORD:catalogue}
+spring.data.redis.host=${REDIS_HOST:localhost}
+spring.data.redis.port=${REDIS_PORT:6390}
+
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+spring.sql.init.mode=always
+
+# How long the slow source takes to load one product, in milliseconds. It stands for an expensive
+# query or a call to another service.
+catalogue.source-delay-ms=200
+
+# How long a cached product lives in Redis. Nothing reads this yet.
+catalogue.cache.products-ttl=10m
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/schema.sql b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/schema.sql
new file mode 100644
index 0000000..45e4545
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/main/resources/schema.sql
@@ -0,0 +1,20 @@
+create table if not exists product (
+ id bigint primary key,
+ name text not null,
+ price numeric(10, 2) not null check (price > 0)
+);
+
+-- Every price change is written down, in the same transaction as the change itself.
+create table if not exists price_change (
+ id bigserial primary key,
+ product_id bigint not null references product (id),
+ old_price numeric(10, 2) not null,
+ new_price numeric(10, 2) not null,
+ changed_at timestamptz not null default now()
+);
+
+insert into product (id, name, price)
+values (1, 'Mechanical keyboard', 89.00),
+ (2, '4K monitor', 329.00),
+ (3, 'USB-C dock', 149.00)
+on conflict (id) do nothing;
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/CacheIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/CacheIT.java
new file mode 100644
index 0000000..3d99588
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/CacheIT.java
@@ -0,0 +1,87 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.CacheManager;
+import org.springframework.context.ApplicationContext;
+import org.springframework.data.redis.cache.RedisCacheManager;
+
+@Tag("task2")
+class CacheIT extends IntegrationTest {
+
+ @Autowired
+ private ApplicationContext context;
+
+ @Test
+ @DisplayName("Cache: caching is switched on, and the cache manager is Redis (RedisCacheManager)")
+ void theCacheIsRedis() {
+ CacheManager cacheManager = context.getBeanProvider(CacheManager.class).getIfAvailable();
+
+ assertThat(cacheManager).as("the CacheManager bean (none means caching is not switched on)").isNotNull();
+ assertThat(cacheManager).as("the CacheManager").isInstanceOf(RedisCacheManager.class);
+ }
+
+ @Test
+ @DisplayName("Cache: 5 GETs for product 1 call the slow source once")
+ void repeatedReadsHitTheCache() {
+ for (int i = 0; i < 5; i++) {
+ assertThat(api.get("/api/products/1").status()).as("status").isEqualTo(200);
+ }
+
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Cache: every product has its own entry: products 1 and 2, read twice each, are loaded once each")
+ void eachProductIsCachedSeparately() {
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Cache: product 1 is stored in Redis under the key products::1")
+ void theKeyIsTheCacheNameAndTheId() {
+ api.get("/api/products/1");
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(redisHasKey("products::1")).as("Redis has the key products::1").isTrue());
+ }
+
+ @Test
+ @DisplayName("Cache: the value in Redis is readable JSON with the name and price, not Java serialization bytes")
+ void theValueIsJson() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisHasKey("products::1"));
+
+ byte[] value = redisValue("products::1");
+ String text = value == null ? "" : new String(value, StandardCharsets.UTF_8);
+ if (value == null || value[0] != '{' || !text.contains("\"name\":\"Mechanical keyboard\"") || !text.contains("\"price\":89.00")) {
+ fail("products::1 should be JSON like {\"id\":1,\"name\":\"Mechanical keyboard\",\"price\":89.00}%nbut Redis holds %d bytes: %s",
+ value == null ? 0 : value.length, printable(value));
+ }
+ }
+
+ @Test
+ @DisplayName("Cache: an unknown product is a 404 every time, and nothing is written to Redis (exceptions are not cached)")
+ void anUnknownProductIsNotCached() {
+ assertThat(api.get("/api/products/999").status()).as("first request").isEqualTo(404);
+ assertThat(api.get("/api/products/999").status()).as("second request").isEqualTo(404);
+
+ assertThat(source.calls(999)).as("calls to the slow source for product 999").isEqualTo(2);
+ assertThat(redisKeyCount()).as("keys in Redis").isZero();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/Check.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/Check.java
new file mode 100644
index 0000000..39a507b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/Check.java
@@ -0,0 +1,115 @@
+package com.amigoscode.caching;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Tasks 1, 3 and 9 are inspection tasks: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the HTTP contract and the slow source (passes from the start, must stay green)");
+ TASKS.put("2", "Task 2: Cache products in Redis, as JSON");
+ TASKS.put("4", "Task 4: Fix the stale price after an update");
+ TASKS.put("5", "Task 5: Fix the cache that the basket skips (self-invocation)");
+ TASKS.put("6", "Task 6: Give cached products a TTL");
+ TASKS.put("7", "Task 7: Fix the cache stampede");
+ TASKS.put("8", "Task 8: Keep the shop up when Redis is down");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-9]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 9. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductControllerTest.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductControllerTest.java
new file mode 100644
index 0000000..bb7e1ed
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductControllerTest.java
@@ -0,0 +1,111 @@
+package com.amigoscode.caching;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.amigoscode.caching.product.ProductController;
+import com.amigoscode.caching.product.ProductNotFoundException;
+import com.amigoscode.caching.product.ProductService;
+import com.amigoscode.caching.product.ProductView;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+/**
+ * Unit tests for the HTTP contract: no Spring context, no database, no Redis. ProductService is a
+ * stub. They pass from the start and must keep passing, so keep the constructors of ProductController
+ * and ProductService as they are.
+ */
+@Tag("baseline")
+class ProductControllerTest {
+
+ private static final Map PRODUCTS = Map.of(
+ 1L, new ProductView(1, "Mechanical keyboard", new BigDecimal("89.00")),
+ 2L, new ProductView(2, "4K monitor", new BigDecimal("329.00")),
+ 3L, new ProductView(3, "USB-C dock", new BigDecimal("149.00")));
+
+ private final MockMvc api = MockMvcBuilders.standaloneSetup(new ProductController(new StubProductService()))
+ .setControllerAdvice(new ApiExceptionHandler())
+ .build();
+
+ @Test
+ @DisplayName("HTTP: GET /api/products/1 returns 200 with the product's id, name and price")
+ void productReturnsOk() throws Exception {
+ api.perform(get("/api/products/1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.id").value(1))
+ .andExpect(jsonPath("$.name").value("Mechanical keyboard"))
+ .andExpect(jsonPath("$.price").value(89.00));
+ }
+
+ @Test
+ @DisplayName("HTTP: an unknown product returns 404 PRODUCT_NOT_FOUND")
+ void unknownProductReturnsNotFound() throws Exception {
+ api.perform(get("/api/products/999"))
+ .andExpect(status().isNotFound())
+ .andExpect(jsonPath("$.code").value("PRODUCT_NOT_FOUND"));
+ }
+
+ @Test
+ @DisplayName("HTTP: PUT /api/products/1/price returns 200 with the new price")
+ void changePriceReturnsTheNewPrice() throws Exception {
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":79.00}"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.price").value(79.00));
+ }
+
+ @Test
+ @DisplayName("HTTP: a price of zero or less returns 400")
+ void nonPositivePriceIsRejected() throws Exception {
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":0}"))
+ .andExpect(status().isBadRequest());
+ api.perform(put("/api/products/1/price").contentType(MediaType.APPLICATION_JSON).content("{\"price\":-5}"))
+ .andExpect(status().isBadRequest());
+ }
+
+ @Test
+ @DisplayName("HTTP: GET /api/products?ids=3,1 (the basket) returns the products in the order asked for")
+ void basketKeepsTheOrder() throws Exception {
+ api.perform(get("/api/products?ids=3,1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.length()").value(2))
+ .andExpect(jsonPath("$[0].id").value(3))
+ .andExpect(jsonPath("$[1].id").value(1));
+ }
+
+ /** Answers from a map, without Spring, Postgres or Redis. */
+ private static final class StubProductService extends ProductService {
+
+ StubProductService() {
+ super(null, null, null);
+ }
+
+ @Override
+ public ProductView findById(long productId) {
+ ProductView product = PRODUCTS.get(productId);
+ if (product == null) {
+ throw new ProductNotFoundException(productId);
+ }
+ return product;
+ }
+
+ /** No @Override on purpose: the basket is answered the same way, whichever method the controller calls. */
+ public List findAll(List productIds) {
+ return productIds.stream().map(this::findById).toList();
+ }
+
+ @Override
+ public ProductView changePrice(long productId, BigDecimal newPrice) {
+ ProductView product = findById(productId);
+ return new ProductView(product.id(), product.name(), newPrice);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductSourceIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductSourceIT.java
new file mode 100644
index 0000000..920ba60
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ProductSourceIT.java
@@ -0,0 +1,27 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.product.SlowProductSource;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("baseline")
+class ProductSourceIT extends IntegrationTest {
+
+ @Autowired
+ private SlowProductSource slowSource;
+
+ @Test
+ @DisplayName("Source: the slow source reads the product from Postgres, with the price it has right now")
+ void readsTheCurrentRow() {
+ jdbc.update("update product set price = 55.50 where id = 2");
+
+ assertThat(slowSource.load(2).price()).isEqualByComparingTo(new BigDecimal("55.50"));
+ assertThat(slowSource.load(2).name()).isEqualTo("4K monitor");
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/RedisDownIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/RedisDownIT.java
new file mode 100644
index 0000000..fef8fc4
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/RedisDownIT.java
@@ -0,0 +1,87 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.Containers;
+import com.amigoscode.caching.support.ControllableProductSource;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.math.BigDecimal;
+import java.net.ServerSocket;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.Import;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+
+/** The application with a real Postgres and a Redis port where nothing is listening. */
+@Tag("task8")
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ properties = {"spring.main.banner-mode=off", "catalogue.source-delay-ms=0",
+ "spring.data.redis.connect-timeout=1s", "spring.data.redis.timeout=1s"})
+@Import(IntegrationTest.TestBeans.class)
+class RedisDownIT {
+
+ private static final int CLOSED_PORT = closedPort();
+
+ @DynamicPropertySource
+ static void redisIsDown(DynamicPropertyRegistry registry) {
+ Containers.database(registry);
+ registry.add("spring.data.redis.host", () -> "localhost");
+ registry.add("spring.data.redis.port", () -> CLOSED_PORT);
+ }
+
+ @Autowired
+ private ControllableProductSource source;
+
+ @Autowired
+ private JdbcTemplate jdbc;
+
+ @Value("${local.server.port}")
+ private int port;
+
+ private Api api;
+
+ @BeforeEach
+ void freshShop() {
+ api = new Api(port);
+ source.reset();
+ IntegrationTest.resetPrices(jdbc);
+ }
+
+ @Test
+ @DisplayName("Redis down: GET still returns the product, loaded from the slow source, instead of a 500")
+ void readsStillWork() {
+ Api.Response response = api.get("/api/products/1");
+
+ assertThat(response.status()).as("status (body: " + response.body() + ")").isEqualTo(200);
+ assertThat(response.price()).as("price").isEqualByComparingTo(new BigDecimal("89.00"));
+ assertThat(source.calls(1)).as("calls to the slow source").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Redis down: PUT still changes the price instead of a 500")
+ void writesStillWork() {
+ Api.Response response = api.changePrice(1, "79.00");
+
+ assertThat(response.status()).as("status (body: " + response.body() + ")").isEqualTo(200);
+ assertThat(jdbc.queryForObject("select price from product where id = 1", BigDecimal.class))
+ .as("price in the database").isEqualByComparingTo(new BigDecimal("79.00"));
+ }
+
+ private static int closedPort() {
+ try (ServerSocket socket = new ServerSocket(0)) {
+ return socket.getLocalPort();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/SelfInvocationIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/SelfInvocationIT.java
new file mode 100644
index 0000000..03c3a4d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/SelfInvocationIT.java
@@ -0,0 +1,43 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task5")
+class SelfInvocationIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Basket: asking for products 1, 2 and 3 twice loads each product only once")
+ void theBasketIsCached() {
+ assertThat(api.get("/api/products?ids=1,2,3").status()).as("status").isEqualTo(200);
+ assertThat(api.get("/api/products?ids=1,2,3").status()).as("status").isEqualTo(200);
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ assertThat(source.calls(3)).as("calls for product 3").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Basket: a product already cached by GET /api/products/{id} is not loaded again by the basket")
+ void theBasketUsesWhatTheProductPageCached() {
+ api.get("/api/products/1");
+
+ api.get("/api/products?ids=1,2,3");
+
+ assertThat(source.calls(1)).as("calls for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Basket: what the basket loaded is cached for GET /api/products/{id} too")
+ void theProductPageUsesWhatTheBasketCached() {
+ api.get("/api/products?ids=1,2,3");
+
+ api.get("/api/products/2");
+
+ assertThat(source.calls(2)).as("calls for product 2").isEqualTo(1);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ShortTtlIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ShortTtlIT.java
new file mode 100644
index 0000000..49db081
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/ShortTtlIT.java
@@ -0,0 +1,43 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.context.TestPropertySource;
+
+/** The same application with catalogue.cache.products-ttl=2s, so an entry expires while the test watches. */
+@Tag("task6")
+@TestPropertySource(properties = "catalogue.cache.products-ttl=2s")
+class ShortTtlIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("TTL: the TTL comes from catalogue.cache.products-ttl (set to 2 seconds in this test)")
+ void theTtlIsConfigured() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ assertThat(redisTtl("products::1"))
+ .as("TTL of products::1 in seconds (-1 means it never expires, -2 that the key is missing)")
+ .isBetween(1L, 2L);
+ }
+
+ @Test
+ @DisplayName("TTL: once the entry expires, the next GET loads the product again and sees a price changed behind the cache's back")
+ void anExpiredEntryIsLoadedAgain() {
+ api.get("/api/products/1");
+ // Somebody fixes the price straight in the database. No PUT, so nothing evicts the entry.
+ jdbc.update("update product set price = 75.00 where id = 1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ await("products::1 to expire").atMost(Duration.ofSeconds(8)).until(() -> !redisHasKey("products::1"));
+
+ assertThat(api.get("/api/products/1").price()).as("price after the entry expired").isEqualByComparingTo(new BigDecimal("75.00"));
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(2);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StaleDataIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StaleDataIT.java
new file mode 100644
index 0000000..4cd545d
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StaleDataIT.java
@@ -0,0 +1,83 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * These pass in start/, where nothing is cached, and turn red the moment Task 2 adds the cache.
+ * Task 4 turns them green again.
+ */
+@Tag("task4")
+class StaleDataIT extends IntegrationTest {
+
+ private static final BigDecimal NEW_PRICE = new BigDecimal("79.00");
+
+ @Test
+ @DisplayName("Update: after PUT a new price, GET returns the new price")
+ void getReturnsTheNewPrice() {
+ api.get("/api/products/1");
+
+ assertThat(api.changePrice(1, "79.00").status()).as("PUT status").isEqualTo(200);
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(api.get("/api/products/1").price()).as("price returned by GET").isEqualByComparingTo(NEW_PRICE));
+ }
+
+ @Test
+ @DisplayName("Update: after the PUT, Redis no longer holds the old price for product 1")
+ void redisDoesNotKeepTheOldPrice() {
+ api.get("/api/products/1");
+ api.changePrice(1, "79.00");
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
+ byte[] value = redisValue("products::1");
+ String cached = value == null ? null : new String(value, StandardCharsets.UTF_8);
+ assertThat(cached == null || cached.contains("79.00"))
+ .as("products::1 is gone or holds 79.00, but it holds: " + printable(value)).isTrue();
+ });
+ }
+
+ @Test
+ @DisplayName("Update: the other products stay cached: changing product 1 does not empty the whole cache")
+ void otherProductsStayCached() {
+ api.get("/api/products/1");
+ api.get("/api/products/2");
+
+ api.changePrice(1, "79.00");
+ api.get("/api/products/2");
+
+ assertThat(source.calls(2)).as("calls to the slow source for product 2").isEqualTo(1);
+ assertThat(redisHasKey("products::2")).as("Redis still has products::2").isTrue();
+ }
+
+ @Test
+ @DisplayName("Update: the entry is removed after the new price is committed, so a GET in between cannot put the old price back")
+ void evictionHappensAfterTheCommit() throws Exception {
+ api.get("/api/products/1");
+
+ priceHistory.holdTheNextCommit();
+ CompletableFuture put = CompletableFuture.supplyAsync(() -> api.changePrice(1, "79.00"));
+ priceHistory.awaitTheCommit();
+
+ // The new price is written but not committed. Anyone who reads the database now sees 89.00.
+ Api.Response inBetween = api.get("/api/products/1");
+ assertThat(inBetween.status()).as("status of the GET in between").isEqualTo(200);
+
+ priceHistory.releaseTheCommit();
+ assertThat(put.get().status()).as("PUT status").isEqualTo(200);
+
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
+ assertThat(api.get("/api/products/1").price())
+ .as("price returned by GET after the PUT has finished").isEqualByComparingTo(NEW_PRICE));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StampedeIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StampedeIT.java
new file mode 100644
index 0000000..d6a9730
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/StampedeIT.java
@@ -0,0 +1,71 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.Api;
+import com.amigoscode.caching.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task7")
+class StampedeIT extends IntegrationTest {
+
+ private static final String LOCK_KEY = "products~lock";
+
+ @Test
+ @DisplayName("Stampede: 10 requests for a product that is not in the cache call the slow source once")
+ void onlyOneRequestLoads() throws Exception {
+ source.everyoneMissesBeforeAnyoneLoads(10);
+
+ api.getAtTheSameMoment("/api/products/1", 10);
+
+ assertThat(source.calls(1)).as("calls to the slow source for product 1").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Stampede: all 10 requests get the product, none of them fails")
+ void everybodyGetsTheProduct() throws Exception {
+ source.everyoneMissesBeforeAnyoneLoads(10);
+
+ List responses = api.getAtTheSameMoment("/api/products/1", 10);
+
+ assertThat(responses).extracting(Api.Response::status).as("statuses").containsOnly(200);
+ assertThat(responses).extracting(Api.Response::price).as("prices")
+ .allSatisfy(price -> assertThat(price).isEqualByComparingTo(new BigDecimal("89.00")));
+ }
+
+ @Test
+ @DisplayName("Stampede: while product 1 loads, the lock is a key in Redis (products~lock), so other instances wait for it too")
+ void theLockLivesInRedis() {
+ source.holdUntilReleased();
+ CompletableFuture loading = CompletableFuture.supplyAsync(() -> api.get("/api/products/1"));
+ await().atMost(Duration.ofSeconds(10)).until(() -> source.arrivals() >= 1);
+
+ boolean locked = redisHasKey(LOCK_KEY);
+ source.release();
+
+ assertThat(locked).as("Redis has the key " + LOCK_KEY + " while the product is loading").isTrue();
+ assertThat(loading.join().status()).as("status").isEqualTo(200);
+ }
+
+ @Test
+ @DisplayName("Stampede: the lock has a TTL, so an instance that dies while loading cannot block the cache for ever")
+ void theLockExpires() {
+ source.holdUntilReleased();
+ CompletableFuture loading = CompletableFuture.supplyAsync(() -> api.get("/api/products/1"));
+ await().atMost(Duration.ofSeconds(10)).until(() -> source.arrivals() >= 1);
+
+ long ttl = redisTtl(LOCK_KEY);
+ source.release();
+
+ assertThat(ttl).as("TTL of " + LOCK_KEY + " in seconds (-1 means never, -2 that there is no lock key)")
+ .isPositive();
+ assertThat(loading.join().status()).as("status").isEqualTo(200);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/TtlIT.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/TtlIT.java
new file mode 100644
index 0000000..d2bcc38
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/TtlIT.java
@@ -0,0 +1,25 @@
+package com.amigoscode.caching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import com.amigoscode.caching.support.IntegrationTest;
+import java.time.Duration;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task6")
+class TtlIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("TTL: products::1 expires: Redis reports a TTL of more than 0 and at most 10 minutes")
+ void entriesHaveATtl() {
+ api.get("/api/products/1");
+ await("Redis to have the key products::1").atMost(Duration.ofSeconds(3)).until(() -> redisTtl("products::1") != -2);
+
+ assertThat(redisTtl("products::1"))
+ .as("TTL of products::1 in seconds (-1 means it never expires, -2 that the key is missing)")
+ .isBetween(1L, 600L);
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Api.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Api.java
new file mode 100644
index 0000000..8cdde7b
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Api.java
@@ -0,0 +1,91 @@
+package com.amigoscode.caching.support;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** Talks to the running application over real HTTP, the way a browser would. */
+public final class Api {
+
+ private static final Pattern PRICE = Pattern.compile("\"price\"\\s*:\\s*([0-9.]+)");
+
+ public record Response(int status, String body) {
+
+ /** The first price in the body. */
+ public BigDecimal price() {
+ List prices = prices();
+ return prices.isEmpty() ? null : prices.getFirst();
+ }
+
+ public List prices() {
+ List prices = new ArrayList<>();
+ Matcher matcher = PRICE.matcher(body);
+ while (matcher.find()) {
+ prices.add(new BigDecimal(matcher.group(1)));
+ }
+ return prices;
+ }
+ }
+
+ private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ private final String baseUrl;
+
+ public Api(int port) {
+ this.baseUrl = "http://localhost:" + port;
+ }
+
+ public Response get(String path) {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET());
+ }
+
+ public Response changePrice(long productId, String price) {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/products/" + productId + "/price"))
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString("{\"price\":" + price + "}")));
+ }
+
+ /** Sends {@code count} GETs for {@code path} at the same moment and waits for all of them. */
+ public List getAtTheSameMoment(String path, int count) throws Exception {
+ CountDownLatch go = new CountDownLatch(1);
+ List> futures = new ArrayList<>();
+ try (ExecutorService clients = Executors.newFixedThreadPool(count)) {
+ for (int i = 0; i < count; i++) {
+ futures.add(clients.submit(() -> {
+ go.await();
+ return get(path);
+ }));
+ }
+ go.countDown();
+ List responses = new ArrayList<>();
+ for (Future future : futures) {
+ responses.add(future.get(60, TimeUnit.SECONDS));
+ }
+ return responses;
+ }
+ }
+
+ private Response send(HttpRequest.Builder request) {
+ try {
+ HttpResponse response = http.send(request.timeout(java.time.Duration.ofSeconds(60)).build(),
+ HttpResponse.BodyHandlers.ofString());
+ return new Response(response.statusCode(), response.body());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Containers.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Containers.java
new file mode 100644
index 0000000..a7b8324
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/Containers.java
@@ -0,0 +1,36 @@
+package com.amigoscode.caching.support;
+
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.lifecycle.Startables;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+import org.testcontainers.utility.DockerImageName;
+
+/**
+ * One Postgres and one Redis for the whole test run, started by Testcontainers (Docker must be
+ * running). Real Redis, because serialization, TTLs and locks are exactly what a fake would get wrong.
+ */
+public final class Containers {
+
+ private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
+ private static final GenericContainer> REDIS =
+ new GenericContainer<>(DockerImageName.parse("redis:8-alpine")).withExposedPorts(6379);
+
+ static {
+ Startables.deepStart(POSTGRES, REDIS).join();
+ }
+
+ private Containers() {
+ }
+
+ public static void database(DynamicPropertyRegistry registry) {
+ registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
+ registry.add("spring.datasource.username", POSTGRES::getUsername);
+ registry.add("spring.datasource.password", POSTGRES::getPassword);
+ }
+
+ public static void redis(DynamicPropertyRegistry registry) {
+ registry.add("spring.data.redis.host", REDIS::getHost);
+ registry.add("spring.data.redis.port", () -> REDIS.getMappedPort(6379));
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java
new file mode 100644
index 0000000..c0c08ac
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllablePriceHistory.java
@@ -0,0 +1,65 @@
+package com.amigoscode.caching.support;
+
+import com.amigoscode.caching.product.PriceHistory;
+import java.math.BigDecimal;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Replaces the price history in integration tests. It is called inside the transaction that changes
+ * the price, which makes it the place to stop that transaction just before it commits: the new price
+ * is written but nobody else can see it yet.
+ */
+public class ControllablePriceHistory implements PriceHistory {
+
+ private volatile CountDownLatch commitGate;
+ private volatile CountDownLatch aboutToCommit;
+
+ public void reset() {
+ releaseTheCommit();
+ commitGate = null;
+ aboutToCommit = null;
+ }
+
+ /** The next price change stops right before its commit, until {@link #releaseTheCommit()}. */
+ public void holdTheNextCommit() {
+ aboutToCommit = new CountDownLatch(1);
+ commitGate = new CountDownLatch(1);
+ }
+
+ /** Waits until the held price change has reached its commit. */
+ public void awaitTheCommit() throws InterruptedException {
+ if (!aboutToCommit.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("The price change never reached its commit");
+ }
+ }
+
+ public void releaseTheCommit() {
+ CountDownLatch gate = commitGate;
+ if (gate != null) {
+ gate.countDown();
+ }
+ }
+
+ @Override
+ public void record(long productId, BigDecimal oldPrice, BigDecimal newPrice) {
+ CountDownLatch gate = commitGate;
+ CountDownLatch reached = aboutToCommit;
+ if (gate == null || !TransactionSynchronizationManager.isSynchronizationActive()) {
+ return;
+ }
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+ @Override
+ public void beforeCommit(boolean readOnly) {
+ reached.countDown();
+ try {
+ gate.await(20, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ });
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java
new file mode 100644
index 0000000..dbaec07
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/ControllableProductSource.java
@@ -0,0 +1,103 @@
+package com.amigoscode.caching.support;
+
+import com.amigoscode.caching.product.ProductNotFoundException;
+import com.amigoscode.caching.product.ProductSource;
+import com.amigoscode.caching.product.ProductView;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Replaces the slow source in integration tests. It reads the same row from Postgres, counts every
+ * call per product, and can hold callers back, so a test can force "everybody misses the cache at
+ * the same moment" on purpose instead of hoping that threads happen to overlap.
+ */
+public class ControllableProductSource implements ProductSource {
+
+ private static final long MEETING_TIMEOUT_MILLIS = 1500;
+
+ private final JdbcTemplate jdbc;
+ private final Map calls = new ConcurrentHashMap<>();
+ private final AtomicInteger arrivals = new AtomicInteger();
+ private volatile int meetingSize;
+ private volatile CountDownLatch meeting;
+ private volatile CountDownLatch gate;
+
+ public ControllableProductSource(JdbcTemplate jdbc) {
+ this.jdbc = jdbc;
+ }
+
+ public void reset() {
+ release();
+ calls.clear();
+ arrivals.set(0);
+ meetingSize = 0;
+ meeting = null;
+ gate = null;
+ }
+
+ /**
+ * The first {@code callers} wait here until all of them have arrived, so all of them have missed
+ * the cache before any of them can fill it. If the others never arrive (because something made
+ * them wait for the first one) the wait ends after 1.5 seconds.
+ */
+ public void everyoneMissesBeforeAnyoneLoads(int callers) {
+ meetingSize = callers;
+ meeting = new CountDownLatch(callers);
+ }
+
+ /** Every caller stops here until {@link #release()}. */
+ public void holdUntilReleased() {
+ gate = new CountDownLatch(1);
+ }
+
+ public void release() {
+ CountDownLatch current = gate;
+ if (current != null) {
+ current.countDown();
+ }
+ }
+
+ /** How many calls have started, for any product. */
+ public int arrivals() {
+ return arrivals.get();
+ }
+
+ /** How many times product {@code productId} was loaded. */
+ public int calls(long productId) {
+ AtomicInteger count = calls.get(productId);
+ return count == null ? 0 : count.get();
+ }
+
+ @Override
+ public ProductView load(long productId) {
+ calls.computeIfAbsent(productId, id -> new AtomicInteger()).incrementAndGet();
+ int arrival = arrivals.incrementAndGet();
+ try {
+ CountDownLatch currentMeeting = meeting;
+ if (currentMeeting != null && arrival <= meetingSize) {
+ currentMeeting.countDown();
+ currentMeeting.await(MEETING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+ }
+ CountDownLatch currentGate = gate;
+ if (currentGate != null) {
+ currentGate.await(20, TimeUnit.SECONDS);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ List found = jdbc.query("select id, name, price from product where id = ?",
+ (row, i) -> new ProductView(row.getLong("id"), row.getString("name"), row.getObject("price", BigDecimal.class)),
+ productId);
+ if (found.isEmpty()) {
+ throw new ProductNotFoundException(productId);
+ }
+ return found.getFirst();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/IntegrationTest.java b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/IntegrationTest.java
new file mode 100644
index 0000000..cc760c2
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/java/com/amigoscode/caching/support/IntegrationTest.java
@@ -0,0 +1,137 @@
+package com.amigoscode.caching.support;
+
+import java.nio.charset.StandardCharsets;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+
+/**
+ * Base class for the *IT tests. They start the real application on a random port and call it over
+ * HTTP, against a real Postgres and a real Redis. The slow source is replaced by one that counts its
+ * calls and takes no time unless a test holds it back.
+ */
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ properties = {"spring.main.banner-mode=off", "catalogue.source-delay-ms=0"})
+@Import(IntegrationTest.TestBeans.class)
+public abstract class IntegrationTest {
+
+ @DynamicPropertySource
+ static void containers(DynamicPropertyRegistry registry) {
+ Containers.database(registry);
+ Containers.redis(registry);
+ }
+
+ @TestConfiguration
+ public static class TestBeans {
+
+ @Bean
+ @Primary
+ ControllableProductSource controllableProductSource(JdbcTemplate jdbc) {
+ return new ControllableProductSource(jdbc);
+ }
+
+ @Bean
+ @Primary
+ ControllablePriceHistory controllablePriceHistory() {
+ return new ControllablePriceHistory();
+ }
+ }
+
+ @Autowired
+ protected ControllableProductSource source;
+
+ @Autowired
+ protected ControllablePriceHistory priceHistory;
+
+ @Autowired
+ protected JdbcTemplate jdbc;
+
+ @Autowired
+ private RedisConnectionFactory redisConnectionFactory;
+
+ @Value("${local.server.port}")
+ private int port;
+
+ protected Api api;
+
+ @BeforeEach
+ void freshShop() {
+ api = new Api(port);
+ source.reset();
+ priceHistory.reset();
+ resetPrices(jdbc);
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ connection.serverCommands().flushDb();
+ }
+ }
+
+ @AfterEach
+ void letEveryoneGo() {
+ source.release();
+ priceHistory.releaseTheCommit();
+ }
+
+ public static void resetPrices(JdbcTemplate jdbc) {
+ jdbc.update("""
+ update product set price = v.price
+ from (values (1, 89.00), (2, 329.00), (3, 149.00)) as v(id, price)
+ where product.id = v.id
+ """);
+ }
+
+ /** The raw bytes stored under {@code key}, or null. */
+ protected byte[] redisValue(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ return connection.stringCommands().get(key.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+
+ protected boolean redisHasKey(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ return Boolean.TRUE.equals(connection.keyCommands().exists(key.getBytes(StandardCharsets.UTF_8)));
+ }
+ }
+
+ /** Seconds until {@code key} expires: -1 means never, -2 means there is no such key. */
+ protected long redisTtl(String key) {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ Long ttl = connection.keyCommands().ttl(key.getBytes(StandardCharsets.UTF_8));
+ return ttl == null ? -2 : ttl;
+ }
+ }
+
+ protected int redisKeyCount() {
+ try (RedisConnection connection = redisConnectionFactory.getConnection()) {
+ Long size = connection.serverCommands().dbSize();
+ return size == null ? 0 : size.intValue();
+ }
+ }
+
+ protected String priceInDatabase(long productId) {
+ return jdbc.queryForObject("select price::text from product where id = ?", String.class, productId);
+ }
+
+ /** Bytes as text, with anything that is not printable ASCII shown as \xNN. */
+ protected static String printable(byte[] value) {
+ if (value == null) {
+ return "(no value)";
+ }
+ StringBuilder text = new StringBuilder();
+ for (byte b : value) {
+ int c = b & 0xff;
+ text.append(c >= 0x20 && c < 0x7f ? String.valueOf((char) c) : String.format("\\x%02x", c));
+ }
+ return text.length() > 90 ? text.substring(0, 90) + "..." : text.toString();
+ }
+}
diff --git a/java/concepts/junior-mid/12-caching-with-redis/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/resources/logback-test.xml
new file mode 100644
index 0000000..4db5b14
--- /dev/null
+++ b/java/concepts/junior-mid/12-caching-with-redis/start/src/test/resources/logback-test.xml
@@ -0,0 +1,13 @@
+
+
+
+ %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n
+
+
+
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/13-money-as-double/INTERVIEW_TASKS.md b/java/concepts/junior-mid/13-money-as-double/INTERVIEW_TASKS.md
new file mode 100644
index 0000000..407733f
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/INTERVIEW_TASKS.md
@@ -0,0 +1,326 @@
+# Interview Tasks — Money as double
+
+> **In `start/`, `./check` FAILS on purpose: 9 of 34 checks pass.** Tasks 2, 4, 5, 6 and 7 turn the
+> other 25 green. Tasks 1, 3 and 8 are inspection tasks: you run things, look, and answer questions.
+
+Do the tasks in order. Every fix is followed by an inspection: Tasks 3 and 8 are nothing else, and
+Tasks 4 to 7 each end with an **Inspect** part. A green test tells you the fix works, the inspection
+tells you **why**, and the why is what an interviewer asks for.
+
+Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks
+you through it with the expected output.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+**Rules:** work in `start/`. Never edit, delete or disable a test. Column types go into
+`src/main/resources/schema.sql`, which drops and creates the table on every start. Nothing in
+`demo/` needs to change.
+
+---
+
+## Task 1: See the Cent Go Missing (10 min)
+
+**Story:** *Finance says the payout for yesterday was one cent short: 1,000 payments of 0.10, and
+99.99 arrived at the bank. Support has a second ticket: a customer returned two items of a 19.99
+order, and the refund for the second one was refused. Before you change anything, reproduce both.*
+
+**Steps:**
+1. `docker compose up -d`, then `./demo`. Read the four totals. Which ones are wrong, and by how much?
+2. `./demo --count 10`, then `./demo --count 3`. Is the payout always wrong? Is the total?
+3. Open `PaymentService.dailyTotal`. Find the line that turns 99.9999999999986 into 9999 cents.
+4. `./demo --scenario refund`. Read the message of the 422. What does the app think 10.00 + 9.99 is?
+5. Open `Payment.refund`. Which two comparisons does it make, and which one fails here?
+6. `./inspect`. Postgres prints `0.1`. What is the exact value in the column?
+7. `./demo --scenario refund`, then `./inspect` again. How many cents does the app pay out for that
+ one payment of 19.99?
+8. `./demo --scenario traps`. Which of the first four lines surprises you?
+
+**Acceptance Criteria** (`./check 1`, already passing: these tests document the problem)
+- [ ] You can explain why `0.1 + 0.2` is not `0.3` in one sentence, without the word "bug"
+- [ ] You can say where the missing cent went: who turned `99.9999999999986` into 99.99
+- [ ] You can explain why Postgres gives the same wrong total as Java
+- [ ] You can explain why the refund was refused although the numbers add up on paper
+- [ ] The four Task 1 tests pass (`DoubleFactsTest`, `PostgresColumnTypesIT`)
+
+**Hints:**
+- A `double` stores a binary fraction. Which fractions can be written with a finite number of binary
+ digits?
+- A cast from `double` to `long` does not round
+
+---
+
+## Task 2: Fix the Payments: BigDecimal and numeric(19,2) (25 min)
+
+**Story:** *Make the payments exact, in Java and in the database. Change `schema.sql`, `Payment`,
+`PaymentService` and `PaymentController`.*
+
+**Acceptance Criteria** (`./check 2`)
+- [ ] The daily total of 1,000 payments of 0.10 is exactly 100.00
+ — `PaymentsIT.dailyTotalIsExact`
+- [ ] 1,000 payments of 0.10 pay out 10000 cents, not 9999 — `PaymentsIT.payoutIsExact`
+- [ ] 19.99 refunded as 10.00 then 9.99: both are accepted and the payment is `REFUNDED`
+ — `PaymentsIT.refundInTwoParts`
+- [ ] `amount` and `refunded` are `numeric(19,2)` columns — `PaymentsIT.columnsAreNumeric`
+- [ ] 12345678901234567.89 is stored to the cent — `PaymentsIT.largeAmountIsStoredExactly`
+- [ ] `./demo` and `./demo --scenario refund` print `RESULT: OK`
+- [ ] The baseline tests still pass (`./check`)
+
+**Hints:**
+- Change the column first and run `./demo` before you touch the Java. Read the message
+- `@Column(precision = 19, scale = 2)` says to Hibernate what `numeric(19,2)` says to Postgres
+- `BigDecimal` has no `+`, `>` or `==`. Which methods replace them, and which one must you never use
+ for "is this the same amount"?
+- Turning euros into cents: is there a way that cannot quietly lose a fraction?
+
+---
+
+## Task 3: Inspect the Storage (15 min)
+
+**Story:** *The tests are green. Now show what is in the database, and why it was wrong before.*
+
+**Steps:**
+1. `./demo`, then `./inspect`. Compare the first three sections with what `./inspect` showed in
+ Task 1.
+2. In Task 1 one payment of 19.99 paid out 1998 cents, and Postgres printed `19.99`. Explain both.
+ Run `./demo --scenario refund` and `./inspect` now.
+3. Read the four-column-type table. Which type is worse than `double precision`, and why does it
+ look fine at a glance?
+4. Read the last table. What does `numeric(19,2)` do with `0.105` and with `0.30000000000000004`?
+ Is that good or bad for an API?
+5. `./demo --scenario json`. For `0.30000000000000004`, which amount did the API answer with, and
+ which one did Postgres store?
+6. In `schema.sql`, why 19 and 2? What is the largest amount the column can hold?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can explain why Postgres printed `0.1` for a value that is not 0.1
+- [ ] You can name the column type for money, and say what each of its two numbers means
+- [ ] You can say what `numeric(19,2)` does with a third decimal, and why that is a problem
+- [ ] You can explain why `real` is even worse than `double precision`
+
+---
+
+## Task 4: Fix the BigDecimal Traps (20 min)
+
+**Story:** *The invoicing code already uses `BigDecimal`, and it is still wrong: a 15% discount on
+9.90 is one cent short, an invoice paid with "100" is not "paid in full", a double click is charged
+twice, and a bundle price crashes. Fix `InvoiceMath` and `ChargeKey`. The method signatures stay.*
+
+**Acceptance Criteria** (`./check 4`)
+- [ ] 15% of 9.90 is 1.49 — `InvoiceMathTest.fifteenPercentOfNineNinety`
+- [ ] 100 paid on 100.00 due is paid in full — `InvoiceMathTest.sameAmountWithAnotherScaleIsPaid`
+- [ ] 99.99 paid on 100.00 due is not — `InvoiceMathTest.lessIsNotPaid` (already passing: keep it
+ that way)
+- [ ] A bundle of 3 for 10.00 costs 3.33 each, no exception — `InvoiceMathTest.bundleOfThree`
+- [ ] `ChargeKey("INV-7", 10.0)` and `ChargeKey("INV-7", 10.00)` are the same key, also in a
+ `HashSet` — `InvoiceMathTest.sameChargeWithAnotherScale`
+- [ ] `./demo --scenario traps` prints `RESULT: OK`
+
+**Hints:**
+- `BigDecimal.valueOf(double)` and `new BigDecimal(double)` do not give the same number. And is
+ there a way to build 0.15 that never goes near a `double`?
+- A `BigDecimal` is a number and a scale. Which methods look at the scale?
+- A record's `equals` and `hashCode` are generated from its fields. A record can have a compact
+ constructor
+- `divide(divisor)` must return the exact answer or throw. Which overload lets you say how to round?
+
+**Inspect:**
+1. `./demo --scenario traps`. Which lines did not change after your fix, and why can no fix change
+ them?
+2. Would a `TreeSet` have the `HashSet` problem? Why not?
+3. Somebody "fixes" `ChargeKey` with `stripTrailingZeros()`. It passes. What does
+ `new BigDecimal("100.00").stripTrailingZeros()` print? Where would that hurt later?
+
+---
+
+## Task 5: Fix the VAT Rounding (20 min)
+
+**Story:** *An accountant sent back three invoices: the VAT on the lines does not add up to the VAT
+on the invoice, a 15% VAT on 6.70 is a cent short, and a credit note does not cancel its invoice.
+The calculator also ignores the configured rounding mode and the `PER_LINE` / `ON_TOTAL` rule. Fix
+`VatCalculator`.*
+
+**Acceptance Criteria** (`./check 5`)
+- [ ] 15% of 6.70 is 1.01 with `HALF_UP` — `VatCalculatorTest.halfACentIsRoundedUp`
+- [ ] 15% of -9.90 is -1.49, the mirror of 1.49 — `VatCalculatorTest.creditNoteMirrorsTheInvoice`
+- [ ] `PER_LINE`: 3 x 0.99 at 20% is 0.20 per line and 0.60 on the invoice
+ — `VatCalculatorTest.perLineAddsUp`
+- [ ] `ON_TOTAL`: the same lines are 0.59 on the invoice and the lines carry no VAT
+ — `VatCalculatorTest.onTotalRoundsOnce`
+- [ ] 0.125 rounds to 0.13 with `HALF_UP` and 0.12 with `HALF_EVEN`
+ — `VatCalculatorTest.theRoundingModeIsUsed`
+- [ ] `./demo --scenario vat` prints `RESULT: OK`, with and without `--rounding-mode HALF_EVEN`
+
+**Hints:**
+- `6.70 * 0.15` as a double is not 1.005. And what does `Math.round(-148.5)` return?
+- `setScale(2, roundingMode)`
+- One rule per invoice: if the lines are rounded, the invoice VAT is their sum
+
+**Inspect:**
+1. `./demo --scenario vat` and `./demo --scenario vat --rounding-mode HALF_EVEN`. Which numbers
+ change? Why does `PER_LINE` not change with the mode here?
+2. Which of the two places to round would you choose for a shop that shows VAT on every line of the
+ receipt? And for a monthly invoice with 2,000 lines?
+3. Why is `HALF_EVEN` called banker's rounding, and when does it matter?
+
+---
+
+## Task 6: Split a Bill Without Losing a Cent, in Any Currency (20 min)
+
+**Story:** *Three friends share a 100.00 bill: each is charged 33.33, and the restaurant is 0.01
+short. The same app is opening in Japan and Bahrain, where it splits 1000 yen into 333.33 yen
+parts. Fix `MinorUnits`, then `BillSplitter`.*
+
+**Acceptance Criteria** (`./check 6`)
+- [ ] 19.99 EUR is 1999 cents, 500 JPY is 500, 1.234 BHD is 1234 fils
+ — `MinorUnitsTest.toMinorUnits`
+- [ ] 12.345 EUR is an `ArithmeticException`, not a rounded number of cents
+ — `MinorUnitsTest.moreDecimalsThanTheCurrencyHasIsRefused`
+- [ ] 1999 cents is 19.99 EUR, 500 is 500 JPY, 1234 fils is 1.234 BHD
+ — `MinorUnitsTest.fromMinorUnits`
+- [ ] 100.00 EUR between 3 is 33.34 + 33.33 + 33.33 — `SplitTest.hundredBetweenThree`
+- [ ] 0.05 EUR between 3 is 0.02 + 0.02 + 0.01 — `SplitTest.fiveCentsBetweenThree`
+- [ ] 1000 JPY between 3 is 334 + 333 + 333 — `SplitTest.yenHasNoDecimals`
+- [ ] 10.000 BHD between 3 is 3.334 + 3.333 + 3.333 — `SplitTest.dinarHasThreeDecimals`
+- [ ] `./demo --scenario split` prints `RESULT: OK` for EUR, JPY and BHD
+
+**Hints:**
+- `java.util.Currency` knows how many decimals each currency has
+- `movePointRight` is exact. `longValueExact` throws when something would be lost
+- Integers divide with a remainder. Who gets the remainder?
+
+**Inspect:**
+1. `./demo --scenario split --amount 100.00 --people 7`. Which parts get the extra cent?
+2. `./demo --scenario split --amount 12.345`. What do you get, and is it the right answer? (Task 7
+ comes back to it.)
+3. A ledger stores `amount_minor bigint` and `currency char(3)`. What does it gain over
+ `numeric(19,2)`, and what does it give up?
+
+---
+
+## Task 7: Fix the JSON (25 min)
+
+**Story:** *The mobile team reports that a large refund shows a different amount in the app than in
+the back office, and that one invoice total arrived as `1E+2`. The web team computes amounts in
+JavaScript and sometimes sends `0.30000000000000004`, which the API accepts. Make money cross the
+HTTP boundary safely. Create `money/AmountFormat.java`, then change the three controllers.*
+
+**Acceptance Criteria** (`./check 7`)
+- [ ] Money in a response is a JSON string with the currency's decimals: `"0.10"`, `"0.00"`
+ — `MoneyJsonIT.moneyIsAStringWithTheCurrencyDecimals`
+- [ ] An invoice of 80.00 + 25% VAT has `"gross":"100.00"`, and no `E+` anywhere
+ — `MoneyJsonIT.noExponent`
+- [ ] 12345678901234567.89 comes back as `"12345678901234567.89"`
+ — `MoneyJsonIT.largeAmountComesBackExactly`
+- [ ] An amount may be sent as `"0.10"` or as `0.10` — `MoneyJsonIT.stringOrNumber` (already
+ passing: keep it that way)
+- [ ] `0.30000000000000004` is refused with a 400 and nothing is stored
+ — `MoneyJsonIT.tooManyDecimalsIsRefused`
+- [ ] `./demo --scenario json` prints `RESULT: OK`
+- [ ] `./demo --scenario split --amount 12.345` answers 400, not 500
+- [ ] `./check` prints 34 passes and no failures
+
+**Hints:**
+- Run `./demo --scenario json` before you start. Compare what the API answered with what Postgres
+ stored for `0.30000000000000004`
+- Two helpers: one that formats an amount for a currency, one that checks an amount a client sent
+- `setScale(decimals, RoundingMode.UNNECESSARY)` and `toPlainString()`
+- `IllegalArgumentException` is already a 400 in `ApiExceptionHandler`
+
+**Inspect:**
+1. `./demo --scenario json`. Read what a JavaScript client makes of each response, before and
+ after.
+2. Why a string and not a number with the right scale? What does `JSON.parse("100.00")` return?
+3. Name two other ways to send money that a JavaScript client cannot get wrong.
+
+---
+
+## Task 8: Compare and Choose (15 min)
+
+**Story:** *"How would you store and calculate money?" is the interview question. Collect the
+evidence, then answer it.*
+
+**Steps:**
+1. `./demo --scenario all` in `start/`, then in your `start/` after the fixes (or in `solution/`).
+ Read the two summaries side by side.
+2. For each `RESULT` line in the `start/` summary, name the line of code that caused it and the
+ task that fixed it.
+3. Rewrite the daily total in your head with `long` cents. What changes in `Payment`, `schema.sql`
+ and the JSON? What stays the same?
+4. A product owner asks for prices with 4 decimals for fuel (1.7999 per litre), paid in cents.
+ Where do you round, and with which mode?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can give two reasons not to use `double` for money, with an example of each
+- [ ] You can name the types for money in Java, in Postgres and in JSON, and say why
+- [ ] You can say when you would choose `long` minor units over `BigDecimal`
+- [ ] You can explain why "where do we round, and how?" is a business question, not a technical one
+
+---
+
+## Questions to Ask Afterwards
+
+Answer out loud, in full sentences, before reading the answer in brackets.
+
+- Why not `double` for money? (A `double` is a binary fraction. Most decimal amounts, 0.10 for
+ example, have no exact binary value, so every amount is slightly off and the errors add up: 1,000
+ payments of 0.10 make 99.9999999999986. It also only keeps about 15 to 17 significant digits. Use
+ `BigDecimal`, or a `long` count of cents.)
+- `new BigDecimal(0.1)` or `BigDecimal.valueOf(0.1)`? (Neither, ideally: `new BigDecimal("0.1")`.
+ `new BigDecimal(0.1)` gives the exact value of the double, 0.1000000000000000055511151231257827...
+ `BigDecimal.valueOf(0.1)` goes through `Double.toString` and gives 0.1, which is right here but
+ still started life as a double. Do not let a money amount be a double at any point.)
+- Why is `new BigDecimal("2.0").equals(new BigDecimal("2.00"))` false? (A `BigDecimal` is an unscaled
+ value and a scale. `equals` and `hashCode` compare both, `compareTo` compares the number. So use
+ `compareTo` for "the same amount", and be careful with `BigDecimal` keys in a `HashSet`, a
+ `HashMap` or a record: normalise the scale first. A `TreeSet` uses `compareTo` and treats them as
+ one.)
+- Why can `divide` throw? (Without a scale it must return the exact result, and 10/3 has no finite
+ decimal representation: `ArithmeticException: Non-terminating decimal expansion`. Always pass a
+ scale and a `RoundingMode`, or a `MathContext`.)
+- Which column type for money in Postgres? (`numeric(precision, scale)`, for example
+ `numeric(19,2)`: exact decimal digits, 17 before the point and 2 after. Not `real` or
+ `double precision`, which have the same problem as Java's float types. Not Postgres's `money`
+ type either: it follows the server's `lc_monetary` setting and does not store a currency. Or a
+ `bigint` of minor units with a currency column.)
+- What happens when you insert 0.105 into a `numeric(19,2)` column? (Postgres rounds it to 0.11,
+ half away from zero, without an error. So validate the scale before you store, or a client's
+ `0.30000000000000004` silently becomes 0.30.)
+- `HALF_UP` or `HALF_EVEN`? (`HALF_UP` rounds .5 away from zero; it is what most people and most
+ invoices expect. `HALF_EVEN`, banker's rounding, rounds .5 to the even neighbour, so over many
+ roundings the errors cancel instead of all going up. It is the rounding mode of IEEE 754 and
+ common in finance and interest calculations. Whichever you choose, choose it explicitly, and the
+ tax rules of the country may choose it for you.)
+- Round per line or on the total? (They give different answers: 3 x 0.99 at 20% is 0.60 per line
+ and 0.59 on the total. Both can be legal. What is never fine is rounding the lines one way and the
+ total another, because then the invoice does not add up. It is a business rule: write it down
+ and test it.)
+- How do you split 100.00 between three people? (Not 33.33 three times: that is 99.99. Work in
+ cents: 10000 / 3 is 3333 remainder 1, so one person pays 33.34 and two pay 33.33. The parts must
+ always add up to the total, and no two parts may differ by more than one cent.)
+- What is a minor unit? (The smallest unit of a currency: the cent for EUR, nothing for JPY (0
+ decimals), the fils for BHD (3 decimals). `Currency.getDefaultFractionDigits()` knows it. Never
+ hard-code 100.)
+- `BigDecimal` or `long` cents? (`long` is fast, a primitive, and what payment providers usually
+ want in their APIs, but you must carry the currency's decimals next to it and handle division
+ remainders yourself. `BigDecimal` is slower but handles any scale, for example a price of 1.7999
+ per litre. Many systems calculate in `BigDecimal` and store or send minor units. For a dedicated
+ money type, look at JSR 354, `javax.money`, and its reference implementation Moneta.)
+- How do you send money in JSON? (As a string with the currency's decimals, `"19.99"`, next to the
+ currency code, or as an integer of minor units, `1999`. Not as a JSON number with decimals: a
+ JavaScript client parses every number as a double, so `12345678901234567.89` arrives as
+ `12345678901234568`, and Jackson can write a `BigDecimal` as `1E+2`.)
+
+## Tips for Interviewers
+
+- The most common answer is "use `BigDecimal`" and nothing more. Ask how they build one from a
+ literal, how they compare two of them and how they divide. Each one is a trap from Task 4.
+- Ask the candidate to predict the payout of `./demo --count 10` before running it. A strong
+ candidate says "99 cents" and explains the cast.
+- Ask what `numeric(19,2)` does with `0.105`. Most candidates guess "an error". It is the most
+ useful surprise in Task 3.
+- In Task 5, watch whether they ask "per line or on the total?" before writing code. That question
+ is the senior answer.
+- In Task 6, a candidate who writes `divide(3, 2, HALF_UP)` and moves on has not checked that the
+ parts add up. Ask them to add them.
+- For senior candidates: ask them to design the `payment` table and the JSON for a multi-currency
+ ledger, and to defend minor units or decimals.
diff --git a/java/concepts/junior-mid/13-money-as-double/README.md b/java/concepts/junior-mid/13-money-as-double/README.md
new file mode 100644
index 0000000..f484411
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/README.md
@@ -0,0 +1,193 @@
+# Money as double — BigDecimal, numeric Columns, Rounding and Minor Units
+
+> **In `start/`, `./check` FAILS on purpose: 9 of 34 checks pass.** That is the exercise, not a
+> broken checkout. Tasks 2, 4, 5, 6 and 7 turn the other 25 green.
+
+A payments service takes 1,000 payments of 0.10 euros in a day. The daily report says
+`99.9999999999986`, and the shop's bank is paid **99.99**. Nothing crashed and nothing was logged.
+The amounts are `double`s and the column is `double precision`. This project lets you watch the cent
+go missing, then fix it all the way through: Java, the database, rounding, splitting, currencies
+and JSON.
+
+It answers the interview questions students most often get wrong:
+
+- "Why should you not use `double` for money? What do you use instead?"
+- "What is the difference between `new BigDecimal(0.1)` and `BigDecimal.valueOf(0.1)`?"
+- "Why is `new BigDecimal("2.0").equals(new BigDecimal("2.00"))` false?"
+- "Which column type do you use for money in Postgres?"
+- "How do you split 100.00 between three people?"
+- "How do you send money in a JSON API?"
+
+## Tech Stack
+
+- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate), Jackson 3
+- **PostgreSQL 17** in Docker
+- JUnit 5, AssertJ, Testcontainers
+
+## What you need
+
+- JDK 25
+- Docker, running
+
+## Getting Started
+
+Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see
+`./demo` (same for `inspect` and `check`).
+
+```bash
+cd start
+docker compose up -d # Postgres on port 5452
+./demo # watch 1,000 payments of 0.10 pay out 99.99
+./check # 9 of 34 pass: that is your starting point
+```
+
+The first run downloads Maven and the dependencies, so it takes a minute or two.
+
+When you are finished: `docker compose down`.
+
+## The three tools
+
+### `./demo` — see what happens
+
+Starts the real application, sends it real HTTP requests and prints what came back next to the right
+answer. Ends with one or more `RESULT` lines. Every run starts from an empty table.
+
+```
+./demo 1,000 payments of 0.10 and the daily total
+./demo --count 10 --amount 0.10 how many payments, and how much each
+./demo --scenario refund 19.99 captured, refunded as 10.00 + 9.99
+./demo --scenario traps new BigDecimal(double), equals, HashSet, divide
+./demo --scenario vat VAT rounded per line or on the total, and a credit note
+./demo --scenario vat --rounding-mode HALF_EVEN
+./demo --scenario split 100.00 between 3 people
+./demo --scenario split --amount 1000 --currency JPY --people 3
+./demo --scenario json what goes over the wire, and what JavaScript reads
+./demo --scenario all every scenario, then a summary
+./demo --help
+```
+
+### `./inspect` — look inside the database
+
+Run it after `./demo`. It shows the column types from `information_schema`, the stored values exactly
+as Postgres holds them (`new BigDecimal(double)` shows the real binary value), the day's total worked
+out by Postgres and by the application, and the same 1,000 payments in a `real`, a
+`double precision`, a `numeric(19,2)` and a `numeric` column side by side.
+
+### `./check` — are the acceptance criteria met?
+
+`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything.
+`./mvnw verify` runs the same tests the usual Maven way.
+
+The tests are the acceptance criteria. **Never edit, delete or disable a test.** The payment tests
+talk to the application the way a client does, JSON over HTTP, and read the table with plain SQL, so
+they do not care which Java types you choose: only what goes over the wire and what lands in the
+database counts.
+
+## The code
+
+```
+start/src/main/
+├── resources/
+│ ├── schema.sql the payment table, created again on every start. Task 2
+│ └── application.properties the VAT rounding mode and where VAT is rounded
+└── java/com/amigoscode/money/
+ ├── payment/
+ │ ├── Payment.java the entity: amount and refunded. Task 2
+ │ ├── PaymentService.java capture, refund, the daily total and the payout. Task 2
+ │ ├── PaymentController.java the payment endpoints. Tasks 2 and 7
+ │ └── ChargeKey.java the key of the duplicate-charge check. Task 4
+ ├── invoice/
+ │ ├── InvoiceMath.java percentOf, isPaidInFull, unitPrice. Task 4
+ │ ├── VatCalculator.java the net, VAT and gross of an invoice. Task 5
+ │ └── InvoiceController.java the quote endpoint. Task 7
+ ├── split/
+ │ ├── BillSplitter.java shares a bill between people. Task 6
+ │ └── SplitController.java the split endpoint. Task 7
+ ├── money/
+ │ └── MinorUnits.java amounts as whole cents, yen or fils. Task 6
+ └── demo/ the demo and inspect tools. Nothing to change here
+```
+
+| Endpoint | Body | What it does |
+|---|---|---|
+| `POST /api/payments` | `{"amount":"0.10"}` | Captures a payment in euros |
+| `POST /api/payments/{id}/refunds` | `{"amount":"10.00"}` | Refunds part or all of it |
+| `GET /api/payments/daily-total?date=` | | The day's total, and the payout to the bank in cents |
+| `POST /api/invoices/quote` | `vatRate`, `lines`, optional `vatRounding` and `discountPercent` | Net, VAT and gross of an invoice |
+| `POST /api/bills/split` | `{"amount":"100.00","currency":"EUR","people":3}` | The share of each person |
+
+## Two ways to work
+
+- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and
+ hints for each task. Use this if you want to work it out yourself.
+- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same eight tasks, step by step, with the output you
+ should see and an explanation of why. Use this to learn the concept, or when you are stuck.
+
+Both files use the same task numbers.
+
+| Task | What you do | Checked by |
+|---|---|---|
+| 1 | See the cent go missing | `./check 1` (passes: it documents the problem) |
+| 2 | Fix the payments: `BigDecimal` and `numeric(19,2)` | `./check 2` |
+| 3 | Inspect the storage | you answer questions |
+| 4 | Fix the `BigDecimal` traps | `./check 4` |
+| 5 | Fix the VAT rounding | `./check 5` |
+| 6 | Split a bill without losing a cent, in any currency | `./check 6` |
+| 7 | Fix the JSON | `./check 7` |
+| 8 | Compare `double`, `BigDecimal` and `long` minor units | you answer questions |
+
+## Solution
+
+`solution/` is the same project with every task done: `cd solution && ./check` prints 34 of 34.
+
+`start/` and `solution/` use the same database. Every start drops the `payment` table and creates it
+again from `schema.sql`, so switching between them is safe.
+
+To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`).
+
+
+Spoiler: the bugs and the fixes
+
+**double (Task 2).** `0.1` has no exact binary value: the `double` nearest to it is
+`0.1000000000000000055511151231257827021181583404541015625`. Add 1,000 of them and the error adds up
+to `99.9999999999986`. `(long) (total * 100)` cuts that to 9999 cents. `10.00 + 9.99` is
+`19.990000000000002`, so a refund of the rest is refused as "more than was captured". Fix:
+`BigDecimal` in Java, `numeric(19,2)` in Postgres (`@Column(precision = 19, scale = 2)`), `compareTo`
+for comparisons, and `movePointRight(2).longValueExact()` for the cents.
+
+**The traps (Task 4).** `new BigDecimal(15 / 100.0)` is
+`0.1499999999999999944488848768742172978818416595458984375`, so 15% of 9.90 rounds to 1.48: use
+`BigDecimal.valueOf(15, 2)` or a string. `equals` compares the scale, so 100 is not 100.00 and a
+record key with 10.0 is not the same key as 10.00: use `compareTo`, or give every key the same scale.
+`divide` without a scale throws `ArithmeticException` for 10.00 / 3: give it a scale and a
+`RoundingMode`.
+
+**Rounding (Task 5).** `Math.round(x * 100) / 100.0` rounds `1.005` to 1.00 (it is `1.00499...` as a
+double), and rounds `-148.5` to `-148`, so a credit note does not cancel its invoice. Round with
+`setScale(2, mode)` and choose the mode (`HALF_UP` or `HALF_EVEN`) and the place (per line or on the
+total) on purpose: 3 x 0.99 at 20% is 0.60 per line and 0.59 on the total. Both are legal. Mixing them
+on one invoice is not.
+
+**Splitting and currencies (Task 6).** 100.00 / 3 rounded is 33.33, and 3 x 33.33 is 99.99. Work in
+whole minor units, divide with a remainder, and give the remainder out one cent at a time: 33.34 +
+33.33 + 33.33. The number of decimals comes from the currency: 2 for EUR, 0 for JPY, 3 for BHD
+(`Currency.getDefaultFractionDigits()`).
+
+**JSON (Task 7).** Jackson writes a `BigDecimal` as a JSON number with its scale (`100.00`), or as
+`1E+2` after `stripTrailingZeros()`. A JavaScript client reads every JSON number as a double, so
+`12345678901234567.89` becomes `12345678901234568`. Send money as a string with the currency's
+decimals, and refuse an amount with more decimals than the currency has: `numeric(19,2)` would
+silently round `0.30000000000000004` to `0.30`.
+
+**When to use which.**
+
+| | `double` | `BigDecimal` | `long` minor units |
+|---|---|---|---|
+| Exact for 0.10 | No | Yes | Yes (10 cents) |
+| Rounding | Hidden, binary | Explicit: scale + `RoundingMode` | Integer division: you decide what to do with the remainder |
+| Speed and memory | Fastest | Slowest, an object per value | Fast, a primitive |
+| Range | About 15 to 17 significant digits | Unlimited | Up to 92,233,720,368,547,758.07 in cents |
+| Database | `double precision`: no | `numeric(19,2)` | `bigint` |
+| Use it for | Science, statistics. Never money | Money in business code: prices, tax, interest | Payment provider APIs, ledgers, high volume |
+
+
diff --git a/java/concepts/junior-mid/13-money-as-double/TASKS_GUIDED.md b/java/concepts/junior-mid/13-money-as-double/TASKS_GUIDED.md
new file mode 100644
index 0000000..ccf6458
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/TASKS_GUIDED.md
@@ -0,0 +1,899 @@
+# Guided Tasks — Money as double
+
+The same eight tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to
+run, the output you should see, why it happens, and the change to make.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+All output below was copied from real runs. Dates and ids will differ on your machine. The amounts
+and the `RESULT` lines should match exactly: nothing in this project depends on timing.
+
+**Before you start**
+
+```bash
+cd start
+docker compose up -d
+```
+
+---
+
+## Task 1: See the Cent Go Missing
+
+No code in this task. You are collecting evidence.
+
+### Run it
+
+```bash
+./demo
+```
+
+```
+Scenario: payments | 1000 payments of 0.10 EUR, captured today
+
+POST /api/payments {"amount":"0.10"} x 1000
+ first answer: 201 {"id":1,"amount":0.1,"refunded":0.0,"currency":"EUR","status":"CAPTURED"}
+GET /api/payments/daily-total
+ 200 {"date":"2026-11-27","payments":1000,"total":99.9999999999986,"currency":"EUR","payoutCents":9999}
+
+What the payments add up to: 100.00 (1000 x 0.10, worked out by the demo with BigDecimal)
+Total from the app: 99.9999999999986
+Total from Postgres, sum(amount): 99.9999999999986 (column type: double precision)
+Paid out to the shop's bank: 99.99 (payoutCents: 9999)
+
+RESULT: OFF BY 0.01. 1000 payments of 0.10 add up to 100.00, but 99.99 is paid out.
+RESULT: DRIFT. The app's total says 99.9999999999986, not 100.00.
+RESULT: DRIFT IN POSTGRES. sum(amount) over a double precision column says 99.9999999999986, not 100.00.
+```
+
+### What just happened
+
+A `double` is a **binary** fraction. 0.5 (`1/2`) and 0.25 (`1/4`) are exact. 0.1 is `1/10`, and in
+binary it goes on for ever (`0.000110011001100...`), like 1/3 in decimal. The `double` keeps 53
+binary digits and rounds the rest, so `0.1` in your code is really:
+
+```
+0.1000000000000000055511151231257827021181583404541015625
+```
+
+Every payment is a tiny bit off, every addition rounds again, and after 1,000 of them the total is
+`99.9999999999986`.
+
+Then the payout. Open `PaymentService.dailyTotal`:
+
+```java
+long payoutCents = (long) (total * 100);
+```
+
+`99.9999999999986 * 100` is `9999.99999999986`, and a cast to `long` does not round: it **cuts**.
+9999 cents: the missing cent. No test that compares "about 100" would notice.
+
+Try fewer payments:
+
+```bash
+./demo --count 10
+./demo --count 3
+```
+
+```
+Total from the app: 0.9999999999999999
+Paid out to the shop's bank: 0.99 (payoutCents: 99)
+RESULT: OFF BY 0.01. 10 payments of 0.10 add up to 1.00, but 0.99 is paid out.
+
+Total from the app: 0.30000000000000004
+Paid out to the shop's bank: 0.30 (payoutCents: 30)
+RESULT: DRIFT. The app's total says 0.30000000000000004, not 0.30.
+```
+
+With 3 payments the error is upwards and the cast hides it. With 10 it is downwards and costs a
+cent. The error is in every total; it only shows when it lands on the wrong side. Postgres agrees,
+because a `double precision` column is the same IEEE 754 double as Java's.
+
+### The refund
+
+Run `./demo --scenario refund`:
+
+```
+POST /api/payments/1/refunds {"amount":"10.00"}
+ 200 {"id":1,"amount":19.99,"refunded":10.0,"currency":"EUR","status":"PARTIALLY_REFUNDED"}
+POST /api/payments/1/refunds {"amount":"9.99"}
+ 422 {"code":"REFUND_EXCEEDS_CAPTURED","message":"Refunding 9.99 on payment 1 would make the total refunded 19.990000000000002, more than the 19.99 captured"}
+
+RESULT: REFUND REFUSED. 10.00 + 9.99 is exactly 19.99, but the app said the refunds add up to more than the 19.99 captured.
+```
+
+`Payment.refund` checks `refunded + refund > amount`. In doubles, `10.0 + 9.99` is
+`19.990000000000002`, which **is** greater than the double `19.99`. (And `refunded == amount`, on the
+next line, would have been false anyway.)
+
+### Look in the database
+
+Run `./inspect`:
+
+```
+PAYMENTS AS POSTGRES STORES THEM (the first 1 of 1)
+ id status amount exact value of amount refunded exact value of refunded
+ -- ------------------ ------ --------------------------------------------------- -------- -----------------------
+ 1 PARTIALLY_REFUNDED 19.99 19.989999999999998436805981327779591083526611328125 10 10
+
+THE DAY'S TOTAL, TWICE (every payment captured on 2026-11-27)
+ Postgres, select sum(amount) over 1 row: 19.99
+ The app, GET /api/payments/daily-total: 200 {"date":"2026-11-27","payments":1,"total":19.99,"currency":"EUR","payoutCents":1998}
+```
+
+Postgres prints the shortest text that reads back as the same double, `19.99`. The column holds
+`19.98999999...`, and **one** payment of 19.99 pays out 1998 cents.
+
+### Check
+
+`./check 1` prints 4 of 4. They pin down what a double does in Java and in Postgres, so no fix will
+ever change them.
+
+---
+
+## Task 2: Fix the Payments: BigDecimal and numeric(19,2)
+
+**The idea:** store and calculate amounts as decimal digits. In Java that is `BigDecimal`: an exact
+whole number (the unscaled value) and a scale. `19.99` is `1999` with scale 2. In Postgres: `numeric`.
+
+### Step 1: the column first
+
+In `schema.sql`, change both money columns:
+
+```sql
+ amount numeric(19,2) not null check (amount > 0),
+ refunded numeric(19,2) not null default 0 check (refunded >= 0 and refunded <= amount),
+```
+
+`schema.sql` drops and creates the table on every start (in a real project this would be a Flyway
+or Liquibase migration). `numeric(19,2)`: 19 digits in total, 2 of them after the point. Run
+`./demo`:
+
+```
+The application did not start:
+ Schema validation: wrong column type encountered in column [amount] in table [payment]; found [numeric (Types#NUMERIC)], but expecting [float(53) (Types#FLOAT)]
+
+RESULT: DID NOT START. Read the message above: it names the field and the column.
+```
+
+That is `spring.jpa.hibernate.ddl-auto=validate`: at startup Hibernate compares every field with its
+column, and refuses to start rather than convert every value through a double.
+
+### Step 2: Payment
+
+In `Payment.java`, replace the two fields, the constructor and `refund`:
+
+```java
+ @Column(nullable = false, precision = 19, scale = 2)
+ private BigDecimal amount;
+
+ @Column(nullable = false, precision = 19, scale = 2)
+ private BigDecimal refunded;
+```
+
+```java
+ public Payment(BigDecimal amount, LocalDate capturedOn) {
+ this.amount = amount;
+ this.refunded = BigDecimal.ZERO;
+ this.status = PaymentStatus.CAPTURED;
+ this.capturedOn = capturedOn;
+ }
+
+ public void refund(BigDecimal refund) {
+ BigDecimal refundedAfter = refunded.add(refund);
+ if (refundedAfter.compareTo(amount) > 0) {
+ throw new RefundExceedsCapturedException(id, refund, refundedAfter, amount);
+ }
+ refunded = refundedAfter;
+ status = refunded.compareTo(amount) == 0 ? PaymentStatus.REFUNDED : PaymentStatus.PARTIALLY_REFUNDED;
+ }
+```
+
+Then `getAmount()` and `getRefunded()` return `BigDecimal`. Import `java.math.BigDecimal`.
+
+`precision` and `scale` tell Hibernate what `numeric(19,2)` tells Postgres (they matter when
+Hibernate generates the schema). `BigDecimal` has no operators: `add`, `subtract`, `compareTo`.
+"Is it the same amount?" is `compareTo(...) == 0`, **not** `equals`: Task 4 shows why.
+
+### Step 3: PaymentService
+
+```java
+ public record DailyTotal(LocalDate date, int payments, BigDecimal total, long payoutCents) {
+ }
+```
+
+`capture(double amount)` becomes `capture(BigDecimal amount)` and `refund(long, double)` becomes
+`refund(long paymentId, BigDecimal amount)`. In both, `if (amount <= 0)` becomes
+`if (amount.signum() <= 0)`. Then `dailyTotal`:
+
+```java
+ @Transactional(readOnly = true)
+ public DailyTotal dailyTotal(LocalDate date) {
+ List captured = payments.findByCapturedOnOrderById(date);
+ BigDecimal total = BigDecimal.ZERO;
+ for (Payment payment : captured) {
+ total = total.add(payment.getAmount());
+ }
+ long payoutCents = total.movePointRight(2).longValueExact();
+ return new DailyTotal(date, captured.size(), total, payoutCents);
+ }
+```
+
+Import `java.math.BigDecimal`. A `BigDecimal` is immutable: `total.add(x)` on its own line does
+nothing. `movePointRight(2)` turns 100.00 into 10000 exactly, and `longValueExact()` throws if
+anything is left after the point instead of cutting it like the cast did.
+
+### Step 4: PaymentController
+
+Change the three records:
+
+```java
+ public record PaymentRequest(BigDecimal amount) {
+ }
+```
+
+In `PaymentResponse`, `double amount, double refunded` becomes `BigDecimal amount, BigDecimal
+refunded`. In `DailyTotalResponse`, `double total` becomes `BigDecimal total`. Import
+`java.math.BigDecimal`. Jackson reads `"0.10"` and `0.10` into a `BigDecimal` digit by digit.
+
+### After
+
+```bash
+./demo
+./demo --scenario refund
+```
+
+```
+ 200 {"date":"2026-11-27","payments":1000,"total":100.00,"currency":"EUR","payoutCents":10000}
+RESULT: OK. 1000 payments of 0.10 add up to 100.00: the app, Postgres and the payout (10000 cents) all agree.
+
+ 200 {"id":1,"amount":19.99,"refunded":19.99,"currency":"EUR","status":"REFUNDED"}
+RESULT: OK. 19.99 captured, 10.00 + 9.99 refunded, status REFUNDED.
+```
+
+`./check 2` prints 5 of 5.
+
+---
+
+## Task 3: Inspect the Storage
+
+### Step 1 and 2: before and after
+
+```bash
+./demo
+./inspect
+```
+
+```
+COLUMNS OF THE payment TABLE (information_schema.columns)
+ column_name data_type numeric_precision numeric_scale
+ ----------- --------- ----------------- -------------
+ amount numeric 19 2
+ refunded numeric 19 2
+
+PAYMENTS AS POSTGRES STORES THEM (the first 5 of 1000)
+ id status amount exact value of amount refunded exact value of refunded
+ -- -------- ------ --------------------- -------- -----------------------
+ 1 CAPTURED 0.10 0.10 0.00 0.00
+
+THE DAY'S TOTAL, TWICE (every payment captured on 2026-11-27)
+ Postgres, select sum(amount) over 1000 rows: 100.00
+ The app, GET /api/payments/daily-total: 200 {"date":"2026-11-27","payments":1000,"total":100.00,"currency":"EUR","payoutCents":10000}
+```
+
+Before the fix the same sections said:
+
+```
+ amount double precision 53
+ 1 CAPTURED 0.1 0.1000000000000000055511151231257827021181583404541015625 0 0
+ Postgres, select sum(amount) over 1000 rows: 99.9999999999986
+```
+
+`53` is the precision of a double in **bits**, not decimal digits. A `numeric` stores decimal
+digits, so what Postgres prints is what it holds: `0.10`, with its scale. The 19.99 payment from
+Task 1 is now `19.99` exactly and pays out 1999 cents.
+
+### Step 3: four column types
+
+```
+THE SAME 1,000 PAYMENTS OF 0.10 IN FOUR COLUMN TYPES (a temporary table, gone when ./inspect ends)
+ column type 0.10 is stored as sum() of the 1,000 rows
+ ---------------- --------------------------------------------------------- -----------------------
+ real 0.100000001490116119384765625 99.99905
+ double precision 0.1000000000000000055511151231257827021181583404541015625 99.9999999999986
+ numeric(19,2) 0.10 100.00
+ numeric 0.10 100.00
+```
+
+`real` is a 32-bit float, about 7 significant digits: off in the 9th decimal of one payment, almost
+a cent after 1,000, and Postgres prints `0.1` for it too. `numeric` without a precision is exact but
+accepts any number of decimals, 0.123456 included.
+
+### Step 4: a third decimal
+
+```
+WHAT numeric(19,2) DOES WITH MORE THAN 2 DECIMALS (no error, no warning)
+ inserted stored
+ ------------------- ------
+ 0.105 0.11
+ 0.115 0.12
+ 0.30000000000000004 0.30
+ -0.105 -0.11
+```
+
+Postgres rounds to the column's scale, half away from zero, and says nothing: a mistake in the
+client becomes a silently different amount.
+
+### Step 5: the API says one thing, the database another
+
+Run `./demo --scenario json`:
+
+```
+ 201 {"id":3,"amount":0.30000000000000004,"refunded":0,"currency":"EUR","status":"CAPTURED"}
+Payment of 0.30000000000000004 (what 0.1 + 0.2 gives in JavaScript): 201, stored in Postgres as 0.30
+```
+
+The response repeats what the client sent; the row says 0.30. Task 7 makes the API refuse it.
+
+### Step 6: why 19 and 2
+
+2 is the euro's number of decimals; 19 leaves 17 digits before the point, more than any payment.
+The declared precision does not change the size on disk: a `numeric` takes the bytes its digits
+need. `numeric(19,4)` is common for prices per unit and exchange rates, rounded to 2 when charged.
+Postgres also has a `money` type: avoid it. It follows the server's `lc_monetary` setting
+(`select 12.345::money` printed `$12.35` here) and does not store a currency.
+
+---
+
+## Task 4: Fix the BigDecimal Traps
+
+### Before
+
+Run `./demo --scenario traps`:
+
+```
+ new BigDecimal(15 / 100.0) 0.1499999999999999944488848768742172978818416595458984375
+ InvoiceMath.percentOf(9.90, 15) 1.48 WRONG (15% of 9.90 is 1.485: half up, that is 1.49)
+ new BigDecimal("2.0").equals(new BigDecimal("2.00")) false
+ a HashSet of BigDecimal 2.0 and 2.00: size() 2
+ InvoiceMath.isPaidInFull(due 100.00, paid 100) false WRONG (100 euros paid of 100.00 due)
+ a HashSet of ChargeKey(INV-7, 10.0) and (INV-7, 10.00) 2 entries WRONG (the same charge twice: a double click)
+ InvoiceMath.unitPrice(10.00, 3) ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. WRONG (3 for 10.00 is 3.33 each)
+
+RESULT: 4 TRAPS. percentOf, isPaidInFull, ChargeKey and unitPrice give a wrong answer or throw.
+```
+
+- **`new BigDecimal(double)`** keeps every digit of the double: 0.15 becomes 0.14999..., so 1.485
+ becomes 1.48499... and rounds down. `BigDecimal.valueOf(0.15)` goes through `Double.toString`
+ and gives `0.15`. Best: never let the number be a double.
+- **`equals`** compares the number **and the scale**: `2.0` is 20 with scale 1, `2.00` is 200 with
+ scale 2. `hashCode` too, so a `HashSet` keeps both. A record's generated `equals` and `hashCode`
+ call the fields' ones, so `ChargeKey` inherits the problem.
+- **`divide(divisor)`** must return the exact result, and 10/3 has none.
+
+### The fix
+
+Replace `InvoiceMath.java`:
+
+```java
+package com.amigoscode.money.invoice;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public final class InvoiceMath {
+
+ private InvoiceMath() {
+ }
+
+ public static BigDecimal percentOf(BigDecimal amount, int percent) {
+ BigDecimal rate = BigDecimal.valueOf(percent, 2);
+ return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
+ }
+
+ public static boolean isPaidInFull(BigDecimal due, BigDecimal paid) {
+ return paid.compareTo(due) >= 0;
+ }
+
+ public static BigDecimal unitPrice(BigDecimal bundlePrice, int units) {
+ return bundlePrice.divide(BigDecimal.valueOf(units), 2, RoundingMode.HALF_UP);
+ }
+}
+```
+
+`BigDecimal.valueOf(15, 2)` is the unscaled value 15 with scale 2: exactly `0.15`. Then `ChargeKey`
+gets a compact constructor that gives every key the same scale:
+
+```java
+package com.amigoscode.money.payment;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public record ChargeKey(String invoiceNumber, BigDecimal amount) {
+
+ public ChargeKey {
+ amount = amount.setScale(2, RoundingMode.UNNECESSARY);
+ }
+}
+```
+
+`RoundingMode.UNNECESSARY` means "if this needs rounding, throw": a key of 10.005 euros is a bug.
+
+### After
+
+`./demo --scenario traps` marks all four lines `RIGHT` and ends in `RESULT: OK. percentOf,
+isPaidInFull, ChargeKey and unitPrice all give the right answer.` `./check 4` prints 5 of 5.
+
+### Inspect
+
+- The lines without `RIGHT` or `WRONG` did not change: they are facts about Java. A `HashSet` of
+ `2.0` and `2.00` still has two elements; a `TreeSet` has one, because it uses `compareTo`.
+- `stripTrailingZeros()` would also make `ChargeKey` pass (`10.0` and `10.00` both become `1E+1`),
+ but `new BigDecimal("100.00").stripTrailingZeros()` prints `1E+2`. Task 7 shows where that ends up.
+
+---
+
+## Task 5: Fix the VAT Rounding
+
+### Before
+
+Run `./demo --scenario vat`:
+
+```
+PER_LINE POST /api/invoices/quote {"vatRate":"0.20","vatRounding":"PER_LINE",...}
+ net vat gross
+ Espresso 0.99 0.2 1.19
+ Espresso 0.99 0.2 1.19
+ Espresso 0.99 0.2 1.19
+ invoice 2.97 0.59 3.56
+
+Invoice 1 x 9.90 at 15%: VAT 1.49 (exactly 1.485)
+Credit note 1 x -9.90 at 15%: VAT -1.48 (exactly -1.485)
+Together: VAT 0.01
+
+RESULT: LINES DO NOT ADD UP. With PER_LINE the VAT on the lines adds up to 0.6, the invoice says 0.59.
+RESULT: RULE IGNORED. PER_LINE should give 0.60 and ON_TOTAL 0.59. The app gave 0.59 and 0.59.
+RESULT: CREDIT NOTE DOES NOT CANCEL. The invoice has 1.49 of VAT, its credit note -1.48.
+```
+
+The `ON_TOTAL` table (not shown) is identical: the rule is ignored. Three bugs:
+
+1. **The lines do not add up.** Every line is rounded (0.198 to 0.20), the invoice is not
+ (0.594 to 0.59). The customer adds up the VAT on the receipt and gets 0.60.
+2. **`Math.round` is not half up.** It is `floor(x + 0.5)`: `Math.round(148.5)` is 149, but
+ `Math.round(-148.5)` is -148. The credit note gets 1 cent less VAT than the invoice it cancels.
+3. **The double again.** `6.70 * 0.15` prints as `1.005`, but the double is `1.00499999999999989...`,
+ so `* 100` is `100.49999999999999` and rounds to 1.00 instead of 1.01.
+
+### Step 1: round with BigDecimal and the configured mode
+
+In `VatCalculator`, replace `vat`:
+
+```java
+ public BigDecimal vat(BigDecimal net, BigDecimal vatRate) {
+ return net.multiply(vatRate).setScale(2, roundingMode);
+ }
+```
+
+`multiply` of two `BigDecimal`s is exact (`6.70 x 0.15 = 1.0050`). `setScale(2, mode)` is the one
+place where it is rounded. `./check 5` prints 3 of 5, and the credit note now cancels the invoice.
+
+### Step 2: one rule for the whole invoice
+
+Replace `quote`:
+
+```java
+ public Quote quote(List lines, int discountPercent, BigDecimal vatRate, VatRounding rounding) {
+ List quoted = new ArrayList<>();
+ BigDecimal net = BigDecimal.ZERO;
+ BigDecimal vatOfTheLines = BigDecimal.ZERO;
+ for (Line line : lines) {
+ BigDecimal lineNet = line.unitPrice().multiply(BigDecimal.valueOf(line.quantity()));
+ lineNet = lineNet.subtract(InvoiceMath.percentOf(lineNet, discountPercent));
+ net = net.add(lineNet);
+ if (rounding == VatRounding.PER_LINE) {
+ BigDecimal lineVat = vat(lineNet, vatRate);
+ vatOfTheLines = vatOfTheLines.add(lineVat);
+ quoted.add(new QuotedLine(line.description(), line.unitPrice(), line.quantity(),
+ lineNet, lineVat, lineNet.add(lineVat)));
+ } else {
+ quoted.add(new QuotedLine(line.description(), line.unitPrice(), line.quantity(), lineNet, null, null));
+ }
+ }
+ BigDecimal vat = rounding == VatRounding.PER_LINE ? vatOfTheLines : vat(net, vatRate);
+ return new Quote(quoted, net, vat, net.add(vat));
+ }
+```
+
+`PER_LINE`: the invoice VAT **is** the sum of the rounded lines. `ON_TOTAL`: the VAT is rounded once
+and the lines show none. The `stripTrailingZeros()` is gone too.
+
+### After
+
+Run `./demo --scenario vat`:
+
+```
+ON_TOTAL POST /api/invoices/quote {"vatRate":"0.20","vatRounding":"ON_TOTAL",...}
+ net vat gross
+ Espresso 0.99 - -
+ Espresso 0.99 - -
+ Espresso 0.99 - -
+ invoice 2.97 0.59 3.56
+
+Invoice 1 x 9.90 at 15%: VAT 1.49 (exactly 1.485)
+Credit note 1 x -9.90 at 15%: VAT -1.49 (exactly -1.485)
+Together: VAT 0.00
+
+RESULT: OK. PER_LINE 0.60 (the lines add up), ON_TOTAL 0.59, and the credit note cancels the invoice exactly.
+```
+
+`./check 5` prints 5 of 5.
+
+### Inspect: the rounding mode
+
+`./demo --scenario vat --rounding-mode HALF_EVEN` gives the invoice 1.48 of VAT and the credit note
+-1.48. `HALF_EVEN` rounds an exact half to the even neighbour: 1.485 to 1.48, 0.135 to 0.14. Half the
+halves go down and half go up, so over many roundings the error averages out: banker's rounding.
+`PER_LINE` gives 0.60 with both modes, because 0.198 is not a half.
+
+Two decisions, both explicit: **how** (`billing.vat.rounding-mode`) and **where**
+(`billing.vat.rounding`, or `vatRounding` in the request). A country's tax rules may decide both.
+None allows an invoice whose lines do not add up to its total.
+
+---
+
+## Task 6: Split a Bill Without Losing a Cent, in Any Currency
+
+### Before
+
+```bash
+./demo --scenario split
+./demo --scenario split --amount 1000 --currency JPY
+```
+
+```
+ 200 {"currency":"EUR","amount":100.00,"people":3,"parts":[33.33,33.33,33.33],"partsInMinorUnits":[3333,3333,3333],"sumOfParts":99.99}
+RESULT: OFF BY 0.01. The parts add up to 99.99, the bill is 100.00.
+
+ 200 {"currency":"JPY","amount":1000,"people":3,"parts":[333.33,333.33,333.33],"partsInMinorUnits":[33333,33333,33333],"sumOfParts":999.99}
+RESULT: OFF BY 0.01. The parts add up to 999.99, the bill is 1000.
+RESULT: WRONG DECIMALS. JPY has 0 decimals, but a part is 333.33.
+```
+
+Rounding each part on its own throws the remainder away. And 2 decimals is a euro fact: the yen has
+no minor unit, the Bahraini dinar has 1,000 fils.
+
+### Step 1: MinorUnits
+
+Replace `MinorUnits.java`:
+
+```java
+package com.amigoscode.money.money;
+
+import java.math.BigDecimal;
+import java.util.Currency;
+
+public final class MinorUnits {
+
+ private MinorUnits() {
+ }
+
+ public static long toMinor(BigDecimal amount, Currency currency) {
+ return amount.movePointRight(decimals(currency)).longValueExact();
+ }
+
+ public static BigDecimal fromMinor(long minor, Currency currency) {
+ return BigDecimal.valueOf(minor, decimals(currency));
+ }
+
+ private static int decimals(Currency currency) {
+ int decimals = currency.getDefaultFractionDigits();
+ if (decimals < 0) {
+ throw new IllegalArgumentException(currency.getCurrencyCode() + " is not a currency you can pay with");
+ }
+ return decimals;
+ }
+}
+```
+
+`Currency.getDefaultFractionDigits()` is 2 for EUR, 0 for JPY, 3 for BHD (and -1 for `XAU`, gold).
+The old code did `(long) (amount.doubleValue() * 100)`: `19.99 * 100` is `1998.9999999999998`, so
+1998. `./check 6` prints 3 of 7: the three `MinorUnits` tests pass.
+
+### Step 2: BillSplitter
+
+Replace `BillSplitter.java`:
+
+```java
+package com.amigoscode.money.split;
+
+import com.amigoscode.money.money.MinorUnits;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Currency;
+import java.util.List;
+
+public final class BillSplitter {
+
+ private BillSplitter() {
+ }
+
+ public static List split(BigDecimal amount, Currency currency, int people) {
+ if (people < 1) {
+ throw new IllegalArgumentException("people must be at least 1");
+ }
+ long total = MinorUnits.toMinor(amount, currency);
+ long each = Math.floorDiv(total, people);
+ long remainder = Math.floorMod(total, people);
+ List parts = new ArrayList<>();
+ for (int i = 0; i < people; i++) {
+ long part = i < remainder ? each + 1 : each;
+ parts.add(MinorUnits.fromMinor(part, currency));
+ }
+ return parts;
+ }
+}
+```
+
+10000 cents / 3 is 3333, remainder 1: the first person pays one cent more. Integer division says
+exactly how many cents are left over. (`floorDiv` and `floorMod` keep it right for negative amounts.)
+
+### After
+
+```bash
+./demo --scenario split --amount 1000 --currency JPY
+./demo --scenario split --amount 10.000 --currency BHD
+```
+
+```
+ 200 {"currency":"JPY","amount":1000,"people":3,"parts":[334,333,333],"partsInMinorUnits":[334,333,333],"sumOfParts":1000}
+RESULT: OK. 334 + 333 + 333 = 1000 JPY.
+RESULT: OK. 3.334 + 3.333 + 3.333 = 10.000 BHD.
+```
+
+`./check 6` prints 7 of 7.
+
+### Inspect: and 12.345 euros?
+
+`./demo --scenario split --amount 12.345` answers `500 Internal Server Error`. `longValueExact()`
+refused 1234.5 cents: the right decision in the wrong place, because the mistake is the client's.
+Task 7 turns it into a 400.
+
+---
+
+## Task 7: Fix the JSON
+
+### Before
+
+Run `./demo --scenario json`:
+
+```
+Payment of "0.10": "amount" is sent as a JSON number: 0.10
+Payment of "12345678901234567.89": "amount" on the wire: 12345678901234567.89
+ JavaScript's JSON.parse reads: 12345678901234568
+Quote of 80.00 + 25% VAT: "gross" on the wire: 100.00
+Payment of 0.30000000000000004 (what 0.1 + 0.2 gives in JavaScript): 201, stored in Postgres as 0.30
+
+RESULT: MONEY AS JSON NUMBERS. A JavaScript client reads every JSON number as a 64-bit double.
+RESULT: PRECISION LOST. 12345678901234567.89 was sent, a JavaScript client reads 12345678901234568.
+RESULT: ACCEPTED 0.30000000000000004. The API took an amount with 17 decimals and stored 0.30.
+```
+
+In `start/` as it came, the server itself sent `"amount":1.2345678901234568E16`, and the run also
+printed `RESULT: EXPONENT. The invoice total went out as 1E+2.`
+
+- Jackson writes a `BigDecimal` as a JSON number with its scale. The server is right now, but JSON
+ has one number type, and JavaScript reads it into a double.
+- The `1E+2` came from the `stripTrailingZeros()` that Task 5 removed: Jackson writes
+ `BigDecimal.toString()`, which uses an exponent when the scale is negative.
+- A new payment answers `"refunded":0`: `BigDecimal.ZERO` has scale 0. The format of an amount
+ should not depend on how it was computed.
+
+### Step 1: AmountFormat
+
+Create `src/main/java/com/amigoscode/money/money/AmountFormat.java`:
+
+```java
+package com.amigoscode.money.money;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.Currency;
+
+public final class AmountFormat {
+
+ private AmountFormat() {
+ }
+
+ public static String format(BigDecimal amount, Currency currency) {
+ if (amount == null) {
+ return null;
+ }
+ return amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.UNNECESSARY).toPlainString();
+ }
+
+ public static BigDecimal parse(BigDecimal amount, Currency currency, String field) {
+ if (amount == null) {
+ throw new IllegalArgumentException(field + " is required");
+ }
+ int decimals = currency.getDefaultFractionDigits();
+ if (amount.stripTrailingZeros().scale() > decimals) {
+ throw new IllegalArgumentException(field + " " + amount.toPlainString() + " has more decimals than "
+ + currency.getCurrencyCode() + " allows (" + decimals + ")");
+ }
+ return amount.setScale(decimals, RoundingMode.UNNECESSARY);
+ }
+}
+```
+
+`format` always gives the currency's decimals, and `toPlainString()` never uses an exponent. `parse`
+accepts `"0.100"` (trailing zeros) and refuses `0.105`; `IllegalArgumentException` is already a 400
+in `ApiExceptionHandler`.
+
+### Step 2: PaymentController
+
+Replace the two response records and the three methods:
+
+```java
+ public record PaymentResponse(long id, String amount, String refunded, String currency, PaymentStatus status) {
+
+ static PaymentResponse from(Payment payment) {
+ return new PaymentResponse(payment.getId(),
+ AmountFormat.format(payment.getAmount(), Payment.CURRENCY),
+ AmountFormat.format(payment.getRefunded(), Payment.CURRENCY),
+ Payment.CURRENCY.getCurrencyCode(), payment.getStatus());
+ }
+ }
+
+ public record DailyTotalResponse(LocalDate date, int payments, String total, String currency, long payoutCents) {
+ }
+```
+
+```java
+ @PostMapping
+ @ResponseStatus(HttpStatus.CREATED)
+ public PaymentResponse capture(@RequestBody PaymentRequest request) {
+ BigDecimal amount = AmountFormat.parse(request.amount(), Payment.CURRENCY, "amount");
+ return PaymentResponse.from(service.capture(amount));
+ }
+```
+
+`refund` gets the same `AmountFormat.parse` line before `service.refund(id, amount)`. In
+`dailyTotal`, pass `AmountFormat.format(total.total(), Payment.CURRENCY)` to `DailyTotalResponse`.
+Import `com.amigoscode.money.money.AmountFormat`. The request keeps `BigDecimal amount`, so `"0.10"`
+and `0.10` both work. `./check 7` prints 4 of 5: the quote still sends numbers.
+
+### Step 3: InvoiceController and SplitController
+
+In `InvoiceController`, the `BigDecimal` fields of `LineResponse` and `QuoteResponse` become
+`String`. Check the prices that come in, and format the ones that go out:
+
+```java
+ List lines = request.lines().stream()
+ .map(line -> new VatCalculator.Line(line.description(),
+ AmountFormat.parse(line.unitPrice(), EUR, "unitPrice"), line.quantity()))
+ .toList();
+
+ VatCalculator.Quote quote = calculator.quote(lines, discount, request.vatRate(), rounding);
+
+ List quotedLines = quote.lines().stream()
+ .map(line -> new LineResponse(line.description(), line.quantity(), money(line.unitPrice()),
+ money(line.net()), money(line.vat()), money(line.gross())))
+ .toList();
+ return new QuoteResponse(EUR.getCurrencyCode(), request.vatRate().toPlainString(), rounding,
+ calculator.roundingMode(), discount, quotedLines, money(quote.net()), money(quote.vat()),
+ money(quote.gross()));
+ }
+
+ private static String money(BigDecimal amount) {
+ return AmountFormat.format(amount, EUR);
+ }
+```
+
+In `SplitController`, `amount`, `parts` and `sumOfParts` in `SplitResponse` become `String` and
+`List`, and the method checks and formats with the bill's currency:
+
+```java
+ Currency currency = Currency.getInstance(request.currency());
+ BigDecimal amount = AmountFormat.parse(request.amount(), currency, "amount");
+
+ List parts = BillSplitter.split(amount, currency, request.people());
+
+ BigDecimal sum = parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
+ return new SplitResponse(currency.getCurrencyCode(), AmountFormat.format(amount, currency), request.people(),
+ parts.stream().map(part -> AmountFormat.format(part, currency)).toList(),
+ parts.stream().map(part -> MinorUnits.toMinor(part, currency)).toList(),
+ AmountFormat.format(sum, currency));
+```
+
+(The `if (amount == null)` check is gone: `parse` does it.) Import `AmountFormat` in both.
+
+### After
+
+Run `./demo --scenario json`:
+
+```
+ 400 {"code":"BAD_REQUEST","message":"amount 0.30000000000000004 has more decimals than EUR allows (2)"}
+Payment of "0.10": "amount" is sent as a JSON string: "0.10"
+Payment of "12345678901234567.89": "amount" on the wire: "12345678901234567.89"
+ JavaScript's JSON.parse reads: "12345678901234567.89" (a string: every digit kept)
+Quote of 80.00 + 25% VAT: "gross" on the wire: "100.00"
+
+RESULT: OK. Money goes out as strings with 2 decimals, comes back exactly, and 0.30000000000000004 is refused with a 400.
+```
+
+`./demo --scenario split --amount 12.345` now ends in `RESULT: REFUSED. The split was answered with
+400: amount 12.345 has more decimals than EUR allows (2)`, and `./check` prints 34 passes and no
+failures.
+
+### Inspect
+
+`JSON.parse('{"a":100.00}').a` is `100` in JavaScript: the scale is gone even when the value is
+right. The other safe shape is an integer of minor units with the currency, `{"amount":1999,
+"currency":"EUR"}`: whole numbers are exact in a double up to 2^53, about 90 trillion euros in cents.
+
+---
+
+## Task 8: Compare and Choose
+
+### Step 1 and 2: the summary, cause and fix
+
+`./demo --scenario all` in `start/` as it came prints 13 `RESULT` lines; after every task, six lines
+of `RESULT: OK`. Here is each problem, what caused it, and where you fixed it:
+
+| RESULT | Caused by | Fixed in |
+|---|---|---|
+| OFF BY 0.01, DRIFT | `double` amounts and `(long) (total * 100)` | Task 2 |
+| DRIFT IN POSTGRES | a `double precision` column | Task 2 |
+| REFUND REFUSED | `10.0 + 9.99 > 19.99` in doubles | Task 2 |
+| 4 TRAPS | `new BigDecimal(double)`, `equals`, a record key, `divide` without a scale | Task 4 |
+| LINES DO NOT ADD UP, RULE IGNORED, CREDIT NOTE | rounding in two places, `Math.round` | Task 5 |
+| OFF BY 0.01 (split) | rounding every part, a hard-coded 2 decimals | Task 6 |
+| JSON NUMBERS, PRECISION LOST, EXPONENT, ACCEPTED | `BigDecimal` as a JSON number, no check of the scale | Task 7 |
+
+### Step 3 and 4: long cents, and 4 decimals
+
+With `long` cents, `Payment.amount` is a `long`, the column a `bigint`, the JSON `"amountMinor":1999`.
+The total is plain `+`, safely. VAT and percentages still make fractions of a cent, so you still
+decide where and how to round. Most payment provider APIs take amounts this way. For a money type that carries its currency, look at JSR 354 (`javax.money`) and
+its reference implementation, Moneta.
+
+Fuel at 1.7999 per litre: keep the price at scale 4 (`numeric(19,4)`), multiply exactly, and round
+once to cents when you charge, with the mode the business chose. Rounding the price first, to 1.80,
+would charge more on every litre.
+
+### When to use which
+
+| | `double` | `BigDecimal` | `long` minor units |
+|---|---|---|---|
+| Exact for 0.10 | No | Yes | Yes (10 cents) |
+| Rounding | Hidden, binary | Explicit: scale + `RoundingMode` | Integer division: you handle the remainder |
+| Speed and memory | Fastest | Slowest, an object per value | Fast, a primitive |
+| Database | `double precision`: no | `numeric(19,2)` | `bigint` (+ currency) |
+| JSON | A number: no | A string: `"19.99"` | An integer: `1999` |
+| Use it for | Science, statistics. Never money | Prices, tax, interest, anything with a rate | Payment provider APIs, ledgers, high volume |
+
+### How to say it in an interview
+
+> "I never use `double` for money. A double is a binary fraction, so 0.10 cannot be stored
+> exactly: 1,000 payments of 0.10 add up to 99.9999999999986, and a cast to cents makes that 99.99.
+> In Java I use `BigDecimal`, built from a string or with `valueOf`, never from a double, and I
+> compare with `compareTo`, because `equals` also compares the scale. Every division and every
+> rounding gets an explicit scale and `RoundingMode`, and where to round, per line or on the total,
+> is a business rule I write down and test. In Postgres the column is `numeric(19,2)`, not `real`
+> or `double precision`, and I validate the scale in the API because `numeric` rounds silently. To
+> split an amount I work in minor units and hand out the remainder one cent at a time, with the
+> number of decimals from the currency. In JSON I send money as a string with the currency, or as
+> an integer of minor units, because a JavaScript client reads every number as a double. If the
+> system is high-volume or talks to payment providers, I store `long` minor units and a currency."
+
+Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of
+[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md).
+
+---
+
+## Clean up
+
+```bash
+docker compose down
+```
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/.mvn/jvm.config b/java/concepts/junior-mid/13-money-as-double/solution/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/13-money-as-double/solution/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/.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.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/check b/java/concepts/junior-mid/13-money-as-double/solution/check
new file mode 100755
index 0000000..222bd2b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.money.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/check.cmd b/java/concepts/junior-mid/13-money-as-double/solution/check.cmd
new file mode 100644
index 0000000..0ddfe59
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.money.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/compose.yaml b/java/concepts/junior-mid/13-money-as-double/solution/compose.yaml
new file mode 100644
index 0000000..6b086b6
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/compose.yaml
@@ -0,0 +1,18 @@
+# The project name is set here because the folder is called "solution" (or "start") in every
+# project of this repository: without it, "docker compose down" in another project would stop this one.
+name: money-as-double
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: money-as-double-postgres
+ environment:
+ POSTGRES_DB: money
+ POSTGRES_USER: money
+ POSTGRES_PASSWORD: money
+ ports:
+ - "5452:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U money -d money"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/demo b/java/concepts/junior-mid/13-money-as-double/solution/demo
new file mode 100755
index 0000000..3381037
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.money.demo.Demo -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/demo.cmd b/java/concepts/junior-mid/13-money-as-double/solution/demo.cmd
new file mode 100644
index 0000000..dbf76ae
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.money.demo.Demo" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/inspect b/java/concepts/junior-mid/13-money-as-double/solution/inspect
new file mode 100755
index 0000000..d0831fd
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.money.demo.Inspect -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/inspect.cmd b/java/concepts/junior-mid/13-money-as-double/solution/inspect.cmd
new file mode 100644
index 0000000..863a6d0
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.money.demo.Inspect" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/mvnw b/java/concepts/junior-mid/13-money-as-double/solution/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/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/java/concepts/junior-mid/13-money-as-double/solution/mvnw.cmd b/java/concepts/junior-mid/13-money-as-double/solution/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/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/java/concepts/junior-mid/13-money-as-double/solution/pom.xml b/java/concepts/junior-mid/13-money-as-double/solution/pom.xml
new file mode 100644
index 0000000..68e5b64
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/pom.xml
@@ -0,0 +1,110 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ money-as-double
+ 0.0.1-SNAPSHOT
+ money-as-double
+ Money as double: watch a total drift by a cent, then fix it with BigDecimal, numeric columns, explicit rounding and minor units
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa-test
+ test
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/ApiExceptionHandler.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/ApiExceptionHandler.java
new file mode 100644
index 0000000..102883b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/ApiExceptionHandler.java
@@ -0,0 +1,41 @@
+package com.amigoscode.money;
+
+import com.amigoscode.money.payment.PaymentNotFoundException;
+import com.amigoscode.money.payment.RefundExceedsCapturedException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/** Anything not listed here, an ArithmeticException for example, becomes a 500. */
+@RestControllerAdvice
+public class ApiExceptionHandler {
+
+ public record ApiError(String code, String message) {
+ }
+
+ @ExceptionHandler(PaymentNotFoundException.class)
+ public ResponseEntity notFound(PaymentNotFoundException e) {
+ return error(HttpStatus.NOT_FOUND, "PAYMENT_NOT_FOUND", e.getMessage());
+ }
+
+ @ExceptionHandler(RefundExceedsCapturedException.class)
+ public ResponseEntity refundTooLarge(RefundExceedsCapturedException e) {
+ return error(HttpStatus.UNPROCESSABLE_CONTENT, "REFUND_EXCEEDS_CAPTURED", e.getMessage());
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity badRequest(IllegalArgumentException e) {
+ return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", e.getMessage());
+ }
+
+ @ExceptionHandler(HttpMessageNotReadableException.class)
+ public ResponseEntity unreadable(HttpMessageNotReadableException e) {
+ return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", "The request body is not valid JSON for this endpoint");
+ }
+
+ private static ResponseEntity error(HttpStatus status, String code, String message) {
+ return ResponseEntity.status(status).body(new ApiError(code, message));
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/MoneyApplication.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/MoneyApplication.java
new file mode 100644
index 0000000..004a51c
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/MoneyApplication.java
@@ -0,0 +1,20 @@
+package com.amigoscode.money;
+
+import java.time.Clock;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+
+@SpringBootApplication
+public class MoneyApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(MoneyApplication.class, args);
+ }
+
+ /** "Today", for the daily total. The tests replace it with a fixed date. */
+ @Bean
+ Clock clock() {
+ return Clock.systemDefaultZone();
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/App.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/App.java
new file mode 100644
index 0000000..85a1104
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/App.java
@@ -0,0 +1,46 @@
+package com.amigoscode.money.demo;
+
+import com.amigoscode.money.MoneyApplication;
+import java.util.ArrayList;
+import java.util.List;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/** Starts the real application on a free port, quietly. Shared by the demo and inspect tools. */
+final class App {
+
+ private App() {
+ }
+
+ static ConfigurableApplicationContext start(List extraArgs) {
+ List args = new ArrayList<>(List.of(
+ "--server.port=0",
+ "--logging.level.root=WARN",
+ // A 500 is shown as one line in the output instead of a full stack trace.
+ "--logging.level.org.apache.catalina.core.ContainerBase=OFF",
+ "--logging.level.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=OFF",
+ // When the application cannot start, the demo prints the reason in one line instead.
+ "--logging.level.org.springframework.boot.SpringApplication=OFF",
+ "--logging.level.org.springframework.boot.diagnostics=OFF"));
+ args.addAll(extraArgs);
+ SpringApplication app = new SpringApplication(MoneyApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ return app.run(args.toArray(String[]::new));
+ }
+
+ static String baseUrl(ConfigurableApplicationContext context) {
+ return "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
+ }
+
+ /** The message that explains why the application did not start, without the stack trace. */
+ static String why(Throwable failure) {
+ Throwable root = failure;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ return message.lines().findFirst().orElse("");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Db.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Db.java
new file mode 100644
index 0000000..94555f5
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Db.java
@@ -0,0 +1,41 @@
+package com.amigoscode.money.demo;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5452/money");
+ static final String USER = env("DB_USER", "money");
+ static final String PASSWORD = env("DB_PASSWORD", "money");
+
+ private Db() {
+ }
+
+ static Connection connect() throws SQLException {
+ return DriverManager.getConnection(URL, USER, PASSWORD);
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ System.out.println();
+ System.out.println("Cannot reach Postgres at " + URL);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")");
+ return false;
+ }
+ }
+
+ private static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Demo.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Demo.java
new file mode 100644
index 0000000..4629b70
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Demo.java
@@ -0,0 +1,634 @@
+package com.amigoscode.money.demo;
+
+import com.amigoscode.money.invoice.InvoiceMath;
+import com.amigoscode.money.payment.ChargeKey;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.jdbc.core.JdbcTemplate;
+import tools.jackson.databind.JsonNode;
+
+/**
+ * Starts the real application, sends it real HTTP requests and prints what came back, next to what
+ * the right answer is. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags.
+ */
+public final class Demo {
+
+ private static final List SCENARIOS = List.of("payments", "refund", "traps", "vat", "split", "json", "all");
+
+ private record Options(String scenario, int count, BigDecimal amount, String currency, int people,
+ RoundingMode roundingMode) {
+ }
+
+ private final Options options;
+ private final Http http;
+ private final JdbcTemplate jdbc;
+ private final List results = new ArrayList<>();
+
+ private Demo(Options options, Http http, JdbcTemplate jdbc) {
+ this.options = options;
+ this.http = http;
+ this.jdbc = jdbc;
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+
+ List appArgs = new ArrayList<>();
+ if (options.roundingMode() != null) {
+ appArgs.add("--billing.vat.rounding-mode=" + options.roundingMode());
+ }
+ ConfigurableApplicationContext context;
+ try {
+ context = App.start(appArgs);
+ } catch (RuntimeException e) {
+ System.out.println();
+ System.out.println("The application did not start:");
+ System.out.println(" " + App.why(e));
+ System.out.println();
+ System.out.println("RESULT: DID NOT START. Read the message above: it names the field and the column.");
+ System.out.println();
+ return;
+ }
+ try (context) {
+ Demo demo = new Demo(options, new Http(App.baseUrl(context)), context.getBean(JdbcTemplate.class));
+ demo.run();
+ }
+ }
+
+ private void run() throws Exception {
+ if (!options.scenario().equals("all")) {
+ runScenario(options.scenario());
+ return;
+ }
+ Map> summary = new LinkedHashMap<>();
+ for (String scenario : SCENARIOS.subList(0, SCENARIOS.size() - 1)) {
+ results.clear();
+ runScenario(scenario);
+ summary.put(scenario, List.copyOf(results));
+ System.out.println("------------------------------------------------------------------------");
+ }
+ System.out.println();
+ System.out.println("SUMMARY");
+ for (Map.Entry> entry : summary.entrySet()) {
+ for (String result : entry.getValue()) {
+ System.out.printf(" %-9s %s%n", entry.getKey(), result);
+ }
+ }
+ System.out.println();
+ }
+
+ private void runScenario(String scenario) throws Exception {
+ jdbc.execute("truncate table payment restart identity");
+ switch (scenario) {
+ case "payments" -> payments();
+ case "refund" -> refund();
+ case "traps" -> traps();
+ case "vat" -> vat();
+ case "split" -> split();
+ case "json" -> json();
+ default -> throw new IllegalStateException(scenario);
+ }
+ System.out.println();
+ results.forEach(System.out::println);
+ System.out.println();
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // payments: many small payments, one daily total
+
+ private void payments() throws Exception {
+ BigDecimal amount = options.amount() == null ? new BigDecimal("0.10") : options.amount();
+ int count = options.count();
+ System.out.println();
+ System.out.println("Scenario: payments | " + count + " payments of " + amount.toPlainString() + " EUR, captured today");
+ System.out.println();
+
+ String body = "{\"amount\":\"" + amount.toPlainString() + "\"}";
+ System.out.println("POST /api/payments " + body + " x " + count);
+ Http.Response first = null;
+ for (int i = 0; i < count; i++) {
+ Http.Response response = http.post("/api/payments", body);
+ if (first == null) {
+ first = response;
+ }
+ if (response.status() != 201) {
+ System.out.println(" " + response.status() + " " + Http.shorten(response.body(), 150));
+ results.add(refusedOrError(response, "Payment " + (i + 1)));
+ return;
+ }
+ }
+ System.out.println(" first answer: " + first.status() + " " + Http.shorten(first.body(), 150));
+ Http.Response daily = http.get("/api/payments/daily-total");
+ System.out.println("GET /api/payments/daily-total");
+ System.out.println(" " + daily.status() + " " + Http.shorten(daily.body(), 150));
+ if (daily.status() != 200) {
+ results.add("RESULT: ERROR. The daily total was answered with " + daily.status() + ".");
+ return;
+ }
+
+ BigDecimal expected = amount.multiply(BigDecimal.valueOf(count));
+ BigDecimal appTotal = Http.amount(daily.get("total"));
+ long payoutCents = daily.get("payoutCents").asLong();
+ BigDecimal payout = BigDecimal.valueOf(payoutCents, 2);
+ String postgresSum = jdbc.queryForObject("select sum(amount)::text from payment", String.class);
+ String columnType = jdbc.queryForObject("""
+ select data_type from information_schema.columns
+ where table_name = 'payment' and column_name = 'amount'
+ """, String.class);
+
+ System.out.println();
+ System.out.println("What the payments add up to: " + expected.toPlainString()
+ + " (" + count + " x " + amount.toPlainString() + ", worked out by the demo with BigDecimal)");
+ System.out.println("Total from the app: " + appTotal.toPlainString());
+ System.out.println("Total from Postgres, sum(amount): " + postgresSum + " (column type: " + columnType + ")");
+ System.out.println("Paid out to the shop's bank: " + payout.toPlainString() + " (payoutCents: " + payoutCents + ")");
+
+ boolean payoutWrong = payout.compareTo(expected) != 0;
+ if (payoutWrong) {
+ results.add("RESULT: OFF BY " + expected.subtract(payout).abs().toPlainString() + ". " + count
+ + " payments of " + amount.toPlainString() + " add up to " + expected.toPlainString()
+ + ", but " + payout.toPlainString() + " is paid out.");
+ }
+ if (appTotal.compareTo(expected) != 0) {
+ results.add("RESULT: DRIFT. The app's total says " + appTotal.toPlainString() + ", not "
+ + expected.toPlainString() + ".");
+ }
+ if (new BigDecimal(postgresSum).compareTo(expected) != 0) {
+ results.add("RESULT: DRIFT IN POSTGRES. sum(amount) over a " + columnType + " column says "
+ + postgresSum + ", not " + expected.toPlainString() + ".");
+ }
+ if (results.isEmpty()) {
+ results.add("RESULT: OK. " + count + " payments of " + amount.toPlainString() + " add up to "
+ + expected.toPlainString() + ": the app, Postgres and the payout (" + payoutCents
+ + " cents) all agree.");
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // refund: one payment, refunded in two parts
+
+ private void refund() throws Exception {
+ System.out.println();
+ System.out.println("Scenario: refund | capture 19.99 EUR, refund 10.00 for one item, then the remaining 9.99");
+ System.out.println();
+
+ Http.Response captured = step("POST /api/payments", "/api/payments", "{\"amount\":\"19.99\"}");
+ if (captured.status() != 201) {
+ results.add("RESULT: ERROR. The payment was answered with " + captured.status() + ".");
+ return;
+ }
+ long id = captured.get("id").asLong();
+ String refunds = "/api/payments/" + id + "/refunds";
+ Http.Response first = step("POST " + refunds, refunds, "{\"amount\":\"10.00\"}");
+ Http.Response second = step("POST " + refunds, refunds, "{\"amount\":\"9.99\"}");
+
+ Map row = jdbc.queryForMap(
+ "select amount::text as amount, refunded::text as refunded, status from payment where id = ?", id);
+ System.out.println();
+ System.out.println("Captured: 19.99");
+ System.out.println("Refunded, worked by hand: 10.00 + 9.99 = 19.99");
+ System.out.println("In the database: amount " + row.get("amount") + ", refunded " + row.get("refunded")
+ + ", status " + row.get("status"));
+
+ if (first.status() != 200) {
+ results.add("RESULT: ERROR. The first refund was answered with " + first.status() + ".");
+ } else if (second.status() == 422) {
+ results.add("RESULT: REFUND REFUSED. 10.00 + 9.99 is exactly 19.99, but the app said the refunds"
+ + " add up to more than the 19.99 captured.");
+ } else if (second.status() != 200) {
+ results.add("RESULT: ERROR. The second refund was answered with " + second.status() + ".");
+ } else if (!"REFUNDED".equals(row.get("status"))) {
+ results.add("RESULT: NOT FULLY REFUNDED. Everything was refunded, but the status is " + row.get("status") + ".");
+ } else {
+ results.add("RESULT: OK. 19.99 captured, 10.00 + 9.99 refunded, status REFUNDED.");
+ }
+ }
+
+ /** A 400 is the API refusing bad input, which can be the right answer. Anything else is an error. */
+ private static String refusedOrError(Http.Response response, String what) {
+ if (response.status() == 400 && response.get("message") != null) {
+ return "RESULT: REFUSED. " + what + " was answered with 400: " + response.get("message").asString();
+ }
+ return "RESULT: ERROR. " + what + " was answered with " + response.status() + ".";
+ }
+
+ private Http.Response step(String label, String path, String body) throws Exception {
+ System.out.println(label + " " + body);
+ Http.Response response = http.post(path, body);
+ System.out.println(" " + response.status() + " " + Http.shorten(response.body(), 170));
+ return response;
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // traps: what BigDecimal does that surprises people
+
+ private void traps() throws Exception {
+ System.out.println();
+ System.out.println("Scenario: traps | the BigDecimal mistakes that compile, run, and give a wrong answer");
+ List hit = new ArrayList<>();
+
+ System.out.println();
+ System.out.println("1. Where the BigDecimal comes from");
+ fact("new BigDecimal(0.1)", new BigDecimal(0.1).toPlainString());
+ fact("BigDecimal.valueOf(0.1)", BigDecimal.valueOf(0.1).toPlainString());
+ fact("new BigDecimal(\"0.1\")", new BigDecimal("0.1").toPlainString());
+ fact("new BigDecimal(15 / 100.0)", new BigDecimal(15 / 100.0).toPlainString());
+ BigDecimal discount = InvoiceMath.percentOf(new BigDecimal("9.90"), 15);
+ verdict("InvoiceMath.percentOf(9.90, 15)", discount.toPlainString(),
+ discount.compareTo(new BigDecimal("1.49")) == 0, "15% of 9.90 is 1.485: half up, that is 1.49");
+ if (discount.compareTo(new BigDecimal("1.49")) != 0) {
+ hit.add("percentOf");
+ }
+ Http.Response quote = http.post("/api/invoices/quote", """
+ {"vatRate":"0.20","discountPercent":15,"lines":[{"description":"Notebook","unitPrice":"9.90","quantity":1}]}""");
+ JsonNode line = quote.json() == null || quote.json().get("lines") == null ? null : quote.json().get("lines").get(0);
+ fact("POST /api/invoices/quote, 9.90 at 15% off", line == null
+ ? quote.status() + " " + Http.shorten(quote.body(), 90)
+ : "net " + Http.amount(line.get("net")).toPlainString() + " (9.90 - 1.49 = 8.41)");
+
+ System.out.println();
+ System.out.println("2. equals is not compareTo");
+ fact("new BigDecimal(\"2.0\").equals(new BigDecimal(\"2.00\"))", String.valueOf(new BigDecimal("2.0").equals(new BigDecimal("2.00"))));
+ fact("new BigDecimal(\"2.0\").compareTo(new BigDecimal(\"2.00\"))", String.valueOf(new BigDecimal("2.0").compareTo(new BigDecimal("2.00"))));
+ fact("a HashSet of BigDecimal 2.0 and 2.00: size()", String.valueOf(new HashSet<>(List.of(new BigDecimal("2.0"), new BigDecimal("2.00"))).size()));
+ boolean paid = InvoiceMath.isPaidInFull(new BigDecimal("100.00"), new BigDecimal("100"));
+ verdict("InvoiceMath.isPaidInFull(due 100.00, paid 100)", String.valueOf(paid), paid, "100 euros paid of 100.00 due");
+ if (!paid) {
+ hit.add("isPaidInFull");
+ }
+ Set seen = new HashSet<>();
+ seen.add(new ChargeKey("INV-7", new BigDecimal("10.0")));
+ seen.add(new ChargeKey("INV-7", new BigDecimal("10.00")));
+ verdict("a HashSet of ChargeKey(INV-7, 10.0) and (INV-7, 10.00)", seen.size() + (seen.size() == 1 ? " entry" : " entries"),
+ seen.size() == 1, "the same charge twice: a double click");
+ if (seen.size() != 1) {
+ hit.add("ChargeKey");
+ }
+
+ System.out.println();
+ System.out.println("3. divide");
+ String unitPrice = attempt(() -> InvoiceMath.unitPrice(new BigDecimal("10.00"), 3).toPlainString());
+ verdict("InvoiceMath.unitPrice(10.00, 3)", unitPrice, unitPrice.equals("3.33"), "3 for 10.00 is 3.33 each");
+ if (!unitPrice.equals("3.33")) {
+ hit.add("unitPrice");
+ }
+
+ if (hit.isEmpty()) {
+ results.add("RESULT: OK. percentOf, isPaidInFull, ChargeKey and unitPrice all give the right answer.");
+ } else {
+ String names = hit.size() == 1 ? hit.get(0)
+ : String.join(", ", hit.subList(0, hit.size() - 1)) + " and " + hit.get(hit.size() - 1);
+ results.add("RESULT: " + hit.size() + (hit.size() == 1 ? " TRAP. " : " TRAPS. ") + names
+ + (hit.size() == 1 ? " gives a wrong answer or throws." : " give a wrong answer or throw."));
+ }
+ }
+
+ private static String attempt(Supplier call) {
+ try {
+ return call.get();
+ } catch (RuntimeException e) {
+ return e.getClass().getSimpleName() + ": " + e.getMessage();
+ }
+ }
+
+ private static void fact(String what, String value) {
+ System.out.printf(" %-60s %s%n", what, value);
+ }
+
+ private static void verdict(String what, String value, boolean right, String why) {
+ System.out.printf(" %-60s %s %s (%s)%n", what, value, right ? "RIGHT" : "WRONG", why);
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // vat: where and how to round
+
+ private void vat() throws Exception {
+ String lines = """
+ [{"description":"Espresso","unitPrice":"0.99","quantity":1},
+ {"description":"Espresso","unitPrice":"0.99","quantity":1},
+ {"description":"Espresso","unitPrice":"0.99","quantity":1}]""";
+ Http.Response perLine = http.post("/api/invoices/quote",
+ "{\"vatRate\":\"0.20\",\"vatRounding\":\"PER_LINE\",\"lines\":" + lines + "}");
+ if (perLine.status() != 200) {
+ System.out.println("POST /api/invoices/quote: " + perLine.status() + " " + Http.shorten(perLine.body(), 150));
+ results.add("RESULT: ERROR. The quote was answered with " + perLine.status() + ".");
+ return;
+ }
+ RoundingMode mode = RoundingMode.valueOf(perLine.get("roundingMode").asString());
+ System.out.println();
+ System.out.println("Scenario: vat | 3 x 0.99 at 20% VAT, then 9.90 at 15% and its credit note. Rounding mode: " + mode);
+
+ Http.Response onTotal = http.post("/api/invoices/quote",
+ "{\"vatRate\":\"0.20\",\"vatRounding\":\"ON_TOTAL\",\"lines\":" + lines + "}");
+ BigDecimal perLineVat = printQuote("PER_LINE", perLine);
+ BigDecimal onTotalVat = printQuote("ON_TOTAL", onTotal);
+ BigDecimal linesAddUpTo = sumOfLineVat(perLine);
+
+ // The right answers, worked out here with BigDecimal and the same rounding mode.
+ BigDecimal expectedPerLine = new BigDecimal("0.198").setScale(2, mode).multiply(BigDecimal.valueOf(3));
+ BigDecimal expectedOnTotal = new BigDecimal("0.594").setScale(2, mode);
+
+ Http.Response invoice = http.post("/api/invoices/quote", """
+ {"vatRate":"0.15","vatRounding":"PER_LINE","lines":[{"description":"Notebook","unitPrice":"9.90","quantity":1}]}""");
+ Http.Response creditNote = http.post("/api/invoices/quote", """
+ {"vatRate":"0.15","vatRounding":"PER_LINE","lines":[{"description":"Notebook, returned","unitPrice":"-9.90","quantity":1}]}""");
+ BigDecimal invoiceVat = Http.amount(invoice.get("vat"));
+ BigDecimal creditVat = Http.amount(creditNote.get("vat"));
+ System.out.println();
+ System.out.println("Invoice 1 x 9.90 at 15%: VAT " + invoiceVat.toPlainString() + " (exactly 1.485)");
+ System.out.println("Credit note 1 x -9.90 at 15%: VAT " + creditVat.toPlainString() + " (exactly -1.485)");
+ System.out.println("Together: VAT " + invoiceVat.add(creditVat).toPlainString());
+
+ if (linesAddUpTo != null && linesAddUpTo.compareTo(perLineVat) != 0) {
+ results.add("RESULT: LINES DO NOT ADD UP. With PER_LINE the VAT on the lines adds up to "
+ + linesAddUpTo.toPlainString() + ", the invoice says " + perLineVat.toPlainString() + ".");
+ }
+ if (perLineVat.compareTo(expectedPerLine) != 0 || onTotalVat.compareTo(expectedOnTotal) != 0) {
+ results.add("RESULT: RULE IGNORED. PER_LINE should give " + expectedPerLine.toPlainString() + " and ON_TOTAL "
+ + expectedOnTotal.toPlainString() + ". The app gave " + perLineVat.toPlainString() + " and "
+ + onTotalVat.toPlainString() + ".");
+ }
+ if (invoiceVat.add(creditVat).signum() != 0) {
+ results.add("RESULT: CREDIT NOTE DOES NOT CANCEL. The invoice has " + invoiceVat.toPlainString()
+ + " of VAT, its credit note " + creditVat.toPlainString() + ".");
+ }
+ if (results.isEmpty()) {
+ results.add("RESULT: OK. PER_LINE " + perLineVat.toPlainString() + " (the lines add up), ON_TOTAL "
+ + onTotalVat.toPlainString() + ", and the credit note cancels the invoice exactly.");
+ }
+ }
+
+ private static BigDecimal printQuote(String rule, Http.Response quote) {
+ System.out.println();
+ System.out.println(rule + " POST /api/invoices/quote {\"vatRate\":\"0.20\",\"vatRounding\":\"" + rule + "\",...}");
+ System.out.printf(" %-10s %8s %8s %8s%n", "", "net", "vat", "gross");
+ for (JsonNode line : quote.json().get("lines")) {
+ System.out.printf(" %-10s %8s %8s %8s%n", line.get("description").asString(),
+ text(line.get("net")), text(line.get("vat")), text(line.get("gross")));
+ }
+ System.out.printf(" %-10s %8s %8s %8s%n", "invoice", text(quote.get("net")), text(quote.get("vat")),
+ text(quote.get("gross")));
+ return Http.amount(quote.get("vat"));
+ }
+
+ /** The VAT on the lines added up, or null when the lines carry no VAT. */
+ private static BigDecimal sumOfLineVat(Http.Response quote) {
+ BigDecimal sum = BigDecimal.ZERO;
+ for (JsonNode line : quote.json().get("lines")) {
+ BigDecimal vat = Http.amount(line.get("vat"));
+ if (vat == null) {
+ return null;
+ }
+ sum = sum.add(vat);
+ }
+ return sum;
+ }
+
+ private static String text(JsonNode node) {
+ BigDecimal amount = Http.amount(node);
+ return amount == null ? "-" : amount.toPlainString();
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // split: share a bill without losing a cent
+
+ private void split() throws Exception {
+ BigDecimal amount = options.amount() == null ? new BigDecimal("100.00") : options.amount();
+ String currency = options.currency();
+ int people = options.people();
+ System.out.println();
+ System.out.println("Scenario: split | " + amount.toPlainString() + " " + currency + " between " + people + " people");
+ System.out.println();
+
+ String body = "{\"amount\":\"" + amount.toPlainString() + "\",\"currency\":\"" + currency + "\",\"people\":" + people + "}";
+ System.out.println("POST /api/bills/split " + body);
+ Http.Response response = http.post("/api/bills/split", body);
+ System.out.println(" " + response.status() + " " + Http.shorten(response.body(), 200));
+ if (response.status() != 200) {
+ results.add(refusedOrError(response, "The split"));
+ return;
+ }
+ List parts = new ArrayList<>();
+ response.get("parts").forEach(part -> parts.add(Http.amount(part)));
+ BigDecimal sum = parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
+ int decimals = java.util.Currency.getInstance(currency).getDefaultFractionDigits();
+ BigDecimal largest = parts.stream().max(BigDecimal::compareTo).orElseThrow();
+ BigDecimal smallest = parts.stream().min(BigDecimal::compareTo).orElseThrow();
+
+ System.out.println();
+ List shown = parts.stream().limit(10).map(BigDecimal::toPlainString).toList();
+ System.out.println("Parts: " + String.join(" + ", shown) + (parts.size() > 10 ? " + ..." : ""));
+ System.out.println("They add up to: " + sum.toPlainString() + " " + currency);
+ System.out.println("The bill: " + amount.toPlainString() + " " + currency + " (" + currency + " has "
+ + decimals + (decimals == 1 ? " decimal)" : " decimals)"));
+
+ if (sum.compareTo(amount) != 0) {
+ results.add("RESULT: OFF BY " + amount.subtract(sum).abs().toPlainString() + ". The parts add up to "
+ + sum.toPlainString() + ", the bill is " + amount.toPlainString() + ".");
+ }
+ if (parts.stream().anyMatch(part -> part.stripTrailingZeros().scale() > decimals)) {
+ results.add("RESULT: WRONG DECIMALS. " + currency + " has " + decimals + " decimals, but a part is "
+ + largest.toPlainString() + ".");
+ }
+ if (largest.subtract(smallest).compareTo(BigDecimal.ONE.movePointLeft(decimals)) > 0) {
+ results.add("RESULT: UNFAIR. The largest part is " + largest.toPlainString() + ", the smallest "
+ + smallest.toPlainString() + ".");
+ }
+ if (results.isEmpty()) {
+ results.add("RESULT: OK. " + String.join(" + ", shown) + (parts.size() > 10 ? " + ..." : "") + " = "
+ + amount.toPlainString() + " " + currency + ".");
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // json: what goes over the wire
+
+ private void json() throws Exception {
+ System.out.println();
+ System.out.println("Scenario: json | what the API sends, what a JavaScript client reads, what it accepts");
+
+ System.out.println();
+ Http.Response small = step("POST /api/payments", "/api/payments", "{\"amount\":\"0.10\"}");
+ Http.Response big = step("POST /api/payments", "/api/payments", "{\"amount\":\"12345678901234567.89\"}");
+ Http.Response quote = step("POST /api/invoices/quote", "/api/invoices/quote",
+ "{\"vatRate\":\"0.25\",\"lines\":[{\"description\":\"Chair\",\"unitPrice\":\"80.00\",\"quantity\":1}]}");
+ Http.Response sum = step("POST /api/payments", "/api/payments", "{\"amount\":0.30000000000000004}");
+
+ JsonNode bigAmount = big.get("amount");
+ JsonNode gross = quote.get("gross");
+ System.out.println();
+ System.out.println("Payment of \"0.10\": \"amount\" is sent as a JSON " + kind(small.get("amount")));
+ if (bigAmount != null) {
+ String wire = Http.raw(big.body(), "amount");
+ System.out.println("Payment of \"12345678901234567.89\": \"amount\" on the wire: " + wire
+ + "\n "
+ + " JavaScript's JSON.parse reads: "
+ + (bigAmount.isNumber() ? Http.asJavaScriptReadsIt(wire) : wire + " (a string: every digit kept)"));
+
+ }
+ if (gross != null) {
+ System.out.println("Quote of 80.00 + 25% VAT: \"gross\" on the wire: " + Http.raw(quote.body(), "gross"));
+ }
+ String stored = sum.status() == 201
+ ? jdbc.queryForObject("select amount::text from payment where id = ?", String.class, sum.get("id").asLong())
+ : null;
+ System.out.println("Payment of 0.30000000000000004 (what 0.1 + 0.2 gives in JavaScript): "
+ + sum.status() + (stored == null ? "" : ", stored in Postgres as " + stored));
+
+ if (small.get("amount") != null && small.get("amount").isNumber()) {
+ results.add("RESULT: MONEY AS JSON NUMBERS. A JavaScript client reads every JSON number as a 64-bit double.");
+ }
+ if (bigAmount != null) {
+ BigDecimal back = Http.amount(bigAmount);
+ String jsSees = bigAmount.isNumber() ? Http.asJavaScriptReadsIt(Http.raw(big.body(), "amount")) : back.toPlainString();
+ if (back.compareTo(new BigDecimal("12345678901234567.89")) != 0 || !jsSees.equals("12345678901234567.89")) {
+ results.add("RESULT: PRECISION LOST. 12345678901234567.89 was sent, a JavaScript client reads " + jsSees + ".");
+ }
+ }
+ if (gross != null && Http.raw(quote.body(), "gross").toUpperCase(Locale.ROOT).contains("E")) {
+ results.add("RESULT: EXPONENT. The invoice total went out as " + Http.raw(quote.body(), "gross") + ".");
+ }
+ if (sum.status() == 201) {
+ results.add("RESULT: ACCEPTED 0.30000000000000004. The API took an amount with 17 decimals and stored " + stored + ".");
+ }
+ if (results.isEmpty()) {
+ results.add("RESULT: OK. Money goes out as strings with 2 decimals, comes back exactly, and"
+ + " 0.30000000000000004 is refused with a " + sum.status() + ".");
+ }
+ }
+
+ private static String kind(JsonNode node) {
+ if (node == null) {
+ return "(missing)";
+ }
+ return node.isNumber() ? "number: " + node.decimalValue() : "string: \"" + node.asString() + "\"";
+ }
+
+ // ---------------------------------------------------------------------------------------------
+
+ private static Options parse(String[] args) {
+ String scenario = "payments";
+ int count = 1000;
+ BigDecimal amount = null;
+ String currency = "EUR";
+ int people = 3;
+ RoundingMode roundingMode = null;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--scenario" -> {
+ scenario = value(args, ++i, arg).toLowerCase(Locale.ROOT);
+ if (!SCENARIOS.contains(scenario)) {
+ throw new IllegalArgumentException("--scenario must be one of " + String.join(" | ", SCENARIOS) + ", got: " + scenario);
+ }
+ }
+ case "--count" -> count = number(value(args, ++i, arg), arg, 1, 10_000);
+ case "--amount" -> amount = decimal(value(args, ++i, arg), arg);
+ case "--currency" -> currency = currency(value(args, ++i, arg));
+ case "--people" -> people = number(value(args, ++i, arg), arg, 1, 1_000);
+ case "--rounding-mode" -> roundingMode = roundingMode(value(args, ++i, arg));
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ return new Options(scenario, count, amount, currency, people, roundingMode);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static int number(String value, String option, int min, int max) {
+ try {
+ int number = Integer.parseInt(value);
+ if (number < min || number > max) {
+ throw new NumberFormatException();
+ }
+ return number;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value);
+ }
+ }
+
+ private static BigDecimal decimal(String value, String option) {
+ try {
+ BigDecimal amount = new BigDecimal(value);
+ if (amount.signum() <= 0) {
+ throw new NumberFormatException();
+ }
+ return amount;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be an amount more than 0, like 0.10, got: " + value);
+ }
+ }
+
+ private static String currency(String value) {
+ try {
+ return java.util.Currency.getInstance(value.toUpperCase(Locale.ROOT)).getCurrencyCode();
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("--currency must be an ISO 4217 code like EUR, JPY or BHD, got: " + value);
+ }
+ }
+
+ private static RoundingMode roundingMode(String value) {
+ try {
+ return RoundingMode.valueOf(value.toUpperCase(Locale.ROOT).replace('-', '_'));
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("--rounding-mode must be HALF_UP, HALF_EVEN, HALF_DOWN, UP, DOWN, CEILING or FLOOR, got: " + value);
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --scenario " + String.join(" | ", SCENARIOS) + " (default: payments)");
+ System.out.println(" payments many small payments and the daily total");
+ System.out.println(" refund 19.99 captured, refunded as 10.00 + 9.99");
+ System.out.println(" traps the BigDecimal mistakes: constructor, equals, divide");
+ System.out.println(" vat VAT rounded per line or on the total, and a credit note");
+ System.out.println(" split a bill shared between people");
+ System.out.println(" json what the API sends and accepts, and what JavaScript reads");
+ System.out.println(" all every scenario, then a summary");
+ System.out.println(" --count payments: how many payments (default: 1000)");
+ System.out.println(" --amount payments: the amount of each one (default: 0.10)");
+ System.out.println(" split: the bill (default: 100.00)");
+ System.out.println(" --currency split: EUR, JPY, BHD, ... (default: EUR)");
+ System.out.println(" --people split: how many people share the bill (default: 3)");
+ System.out.println(" --rounding-mode vat: HALF_UP or HALF_EVEN, ... (default: billing.vat.rounding-mode)");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --count 10");
+ System.out.println(" ./demo --scenario split --amount 1000 --currency JPY");
+ System.out.println(" ./demo --scenario vat --rounding-mode HALF_EVEN");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Http.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Http.java
new file mode 100644
index 0000000..558bb4d
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Http.java
@@ -0,0 +1,97 @@
+package com.amigoscode.money.demo;
+
+import java.math.BigDecimal;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.cfg.JsonNodeFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Sends real HTTP requests to the application and reads the JSON it sends back, exactly. */
+final class Http {
+
+ /** A response, and its body parsed. JSON numbers are read as BigDecimal, with every digit the server sent. */
+ record Response(int status, String body, JsonNode json) {
+
+ JsonNode get(String field) {
+ return json == null ? null : json.get(field);
+ }
+ }
+
+ private static final JsonMapper JSON = JsonMapper.builder()
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .disable(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES)
+ .build();
+
+ private final HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ private final String baseUrl;
+
+ Http(String baseUrl) {
+ this.baseUrl = baseUrl;
+ }
+
+ Response post(String path, String json) throws Exception {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build());
+ }
+
+ Response get(String path) throws Exception {
+ return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET().build());
+ }
+
+ private Response send(HttpRequest request) throws Exception {
+ HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
+ JsonNode json;
+ try {
+ json = JSON.readTree(response.body());
+ } catch (RuntimeException e) {
+ json = null;
+ }
+ return new Response(response.statusCode(), response.body(), json);
+ }
+
+ /** An amount from the JSON, whether the server sent it as a number (0.1) or as a string ("0.10"). */
+ static BigDecimal amount(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ return node.isNumber() ? node.decimalValue() : new BigDecimal(node.asString());
+ }
+
+ /**
+ * What JSON.parse in a browser or in Node.js makes of a JSON number: a 64-bit double, printed
+ * the way JavaScript prints numbers. "12345678901234567.89" becomes 12345678901234568.
+ */
+ static String asJavaScriptReadsIt(String jsonNumber) {
+ double value = Double.parseDouble(jsonNumber);
+ return new BigDecimal(Double.toString(value)).stripTrailingZeros().toPlainString();
+ }
+
+ /**
+ * The value of a field exactly as it appears in the JSON text, 1.2345678901234568E16 or "0.10"
+ * with its quotes. If the field appears more than once, the last one: the invoice total comes
+ * after the lines.
+ */
+ static String raw(String body, String field) {
+ Matcher matcher = Pattern.compile("\"" + field + "\"\\s*:\\s*(\"[^\"]*\"|[^,}\\]]+)")
+ .matcher(body == null ? "" : body);
+ String last = "";
+ while (matcher.find()) {
+ last = matcher.group(1).strip();
+ }
+ return last;
+ }
+
+ /** The body on one line, cut to a readable length. */
+ static String shorten(String body, int max) {
+ String oneLine = body == null ? "" : body.replaceAll("\\s+", " ");
+ return oneLine.length() <= max ? oneLine : oneLine.substring(0, max) + "...";
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Inspect.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Inspect.java
new file mode 100644
index 0000000..ea179d7
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/demo/Inspect.java
@@ -0,0 +1,244 @@
+package com.amigoscode.money.demo;
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/**
+ * Shows how the money really sits in the database: the column types, the stored values exactly as
+ * Postgres holds them, the day's total worked out by Postgres and by the application, and the same
+ * values in four column types side by side. Run ./demo first, then ./inspect (or .\inspect).
+ */
+public final class Inspect {
+
+ private static final int ROWS_SHOWN = 5;
+
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0) {
+ System.out.println("Usage: ./inspect (Windows: .\\inspect)");
+ System.out.println();
+ System.out.println("Run ./demo first (any scenario), then ./inspect to see what it left in the database.");
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Connection connection = Db.connect()) {
+ if (!tableExists(connection)) {
+ System.out.println();
+ System.out.println("There is no payment table yet. Run ./demo first.");
+ return;
+ }
+ columns(connection);
+ storedValues(connection);
+ appTotal(postgresTotal(connection));
+ fourColumnTypes(connection);
+ }
+ System.out.println();
+ }
+
+ private static boolean tableExists(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement();
+ ResultSet result = statement.executeQuery("select to_regclass('payment') is not null")) {
+ result.next();
+ return result.getBoolean(1);
+ }
+ }
+
+ private static void columns(Connection connection) throws SQLException {
+ System.out.println();
+ System.out.println("COLUMNS OF THE payment TABLE (information_schema.columns)");
+ Table.print(connection, """
+ select column_name, data_type, coalesce(numeric_precision::text, '') as numeric_precision,
+ coalesce(numeric_scale::text, '') as numeric_scale
+ from information_schema.columns
+ where table_name = 'payment' and column_name in ('amount', 'refunded')
+ order by ordinal_position
+ """);
+ }
+
+ private static void storedValues(Connection connection) throws SQLException {
+ long rows = Table.count(connection, "select count(*) from payment");
+ System.out.println();
+ System.out.println("PAYMENTS AS POSTGRES STORES THEM (the first " + Math.min(rows, ROWS_SHOWN) + " of " + rows + ")");
+ if (rows == 0) {
+ System.out.println(" none. Run ./demo first.");
+ return;
+ }
+ List table = new ArrayList<>();
+ table.add(new String[] {"id", "status", "amount", "exact value of amount", "refunded", "exact value of refunded"});
+ try (Statement statement = connection.createStatement();
+ ResultSet result = statement.executeQuery(
+ "select id, status, amount, amount::text, refunded, refunded::text from payment order by id limit " + ROWS_SHOWN)) {
+ while (result.next()) {
+ table.add(new String[] {result.getString(1), result.getString(2),
+ result.getString(4), exact(result.getObject(3)),
+ result.getString(6), exact(result.getObject(5))});
+ }
+ }
+ Table.print(table);
+ System.out.println(" \"amount\" is what Postgres prints. \"exact value\" is the number the column really holds:");
+ System.out.println(" read with getDouble() and printed with new BigDecimal(double), or read as a BigDecimal.");
+ }
+
+ /** The exact number behind a value read from the database. */
+ private static String exact(Object value) {
+ return switch (value) {
+ case null -> "";
+ case Float f -> new BigDecimal(f.doubleValue()).toPlainString();
+ case Double d -> new BigDecimal(d).toPlainString();
+ case BigDecimal b -> b.toPlainString();
+ default -> value.toString();
+ };
+ }
+
+ /** Prints Postgres's sum for the day of the first payment and returns that day, or null. */
+ private static String postgresTotal(Connection connection) throws SQLException {
+ String day;
+ try (Statement statement = connection.createStatement();
+ ResultSet result = statement.executeQuery("select captured_on::text from payment order by id limit 1")) {
+ day = result.next() ? result.getString(1) : null;
+ }
+ if (day == null) {
+ return null;
+ }
+ System.out.println();
+ System.out.println("THE DAY'S TOTAL, TWICE (every payment captured on " + day + ")");
+ try (PreparedStatement statement = connection.prepareStatement(
+ "select count(*), sum(amount)::text from payment where captured_on = ?::date")) {
+ statement.setString(1, day);
+ try (ResultSet result = statement.executeQuery()) {
+ result.next();
+ long rows = result.getLong(1);
+ System.out.println(" Postgres, select sum(amount) over " + rows + (rows == 1 ? " row: " : " rows: ")
+ + result.getString(2));
+ }
+ }
+ return day;
+ }
+
+ private static void appTotal(String day) {
+ if (day == null) {
+ return;
+ }
+ // The real application, started just for this: it must not run schema.sql (that would empty the table).
+ try (ConfigurableApplicationContext context = App.start(List.of("--spring.sql.init.mode=never"))) {
+ Http.Response response = new Http(App.baseUrl(context)).get("/api/payments/daily-total?date=" + day);
+ System.out.println(" The app, GET /api/payments/daily-total: " + response.status() + " "
+ + Http.shorten(response.body(), 140));
+ } catch (Exception e) {
+ System.out.println(" The app did not start: " + App.why(e));
+ }
+ }
+
+ private static void fourColumnTypes(Connection connection) throws SQLException {
+ System.out.println();
+ System.out.println("THE SAME 1,000 PAYMENTS OF 0.10 IN FOUR COLUMN TYPES (a temporary table, gone when ./inspect ends)");
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("""
+ create temporary table side_by_side (
+ as_real real,
+ as_double double precision,
+ as_numeric numeric(19,2),
+ as_any numeric
+ )""");
+ statement.execute("""
+ insert into side_by_side
+ select 0.10, 0.10, 0.10, 0.10 from generate_series(1, 1000)""");
+ List table = new ArrayList<>();
+ table.add(new String[] {"column type", "0.10 is stored as", "sum() of the 1,000 rows"});
+ row(statement, table, "real", "as_real");
+ row(statement, table, "double precision", "as_double");
+ row(statement, table, "numeric(19,2)", "as_numeric");
+ row(statement, table, "numeric", "as_any");
+ Table.print(table);
+
+ System.out.println();
+ System.out.println("WHAT numeric(19,2) DOES WITH MORE THAN 2 DECIMALS (no error, no warning)");
+ List rounding = new ArrayList<>();
+ rounding.add(new String[] {"inserted", "stored"});
+ for (String value : List.of("0.105", "0.115", "0.30000000000000004", "-0.105")) {
+ try (ResultSet result = statement.executeQuery(
+ "insert into side_by_side (as_numeric) values (" + value + ") returning as_numeric::text")) {
+ result.next();
+ rounding.add(new String[] {value, result.getString(1)});
+ }
+ }
+ Table.print(rounding);
+ statement.execute("drop table side_by_side");
+ }
+ }
+
+ private static void row(Statement statement, List table, String type, String column) throws SQLException {
+ try (ResultSet result = statement.executeQuery(
+ "select (select " + column + " from side_by_side limit 1), sum(" + column + ")::text from side_by_side")) {
+ result.next();
+ table.add(new String[] {type, exact(result.getObject(1)), result.getString(2)});
+ }
+ }
+
+ /** Prints rows as a plain text table. */
+ private static final class Table {
+
+ static long count(Connection connection, String sql) throws SQLException {
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) {
+ result.next();
+ return result.getLong(1);
+ }
+ }
+
+ static void print(Connection connection, String sql) throws SQLException {
+ List rows = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) {
+ int columns = result.getMetaData().getColumnCount();
+ String[] header = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ header[c] = result.getMetaData().getColumnLabel(c + 1).toLowerCase(Locale.ROOT);
+ }
+ rows.add(header);
+ while (result.next()) {
+ String[] row = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ String value = result.getString(c + 1);
+ row[c] = value == null ? "" : value;
+ }
+ rows.add(row);
+ }
+ }
+ print(rows);
+ }
+
+ static void print(List rows) {
+ int[] widths = new int[rows.get(0).length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ }
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceController.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceController.java
new file mode 100644
index 0000000..7fed90d
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceController.java
@@ -0,0 +1,71 @@
+package com.amigoscode.money.invoice;
+
+import com.amigoscode.money.money.AmountFormat;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.Currency;
+import java.util.List;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/invoices")
+public class InvoiceController {
+
+ private static final Currency EUR = Currency.getInstance("EUR");
+
+ public record LineRequest(String description, BigDecimal unitPrice, int quantity) {
+ }
+
+ /** vatRate is a fraction: "0.20" is 20%. vatRounding and discountPercent are optional. */
+ public record QuoteRequest(BigDecimal vatRate, VatRounding vatRounding, Integer discountPercent,
+ List lines) {
+ }
+
+ public record LineResponse(String description, int quantity, String unitPrice, String net, String vat,
+ String gross) {
+ }
+
+ public record QuoteResponse(String currency, String vatRate, VatRounding vatRounding, RoundingMode roundingMode,
+ int discountPercent, List lines, String net, String vat,
+ String gross) {
+ }
+
+ private final VatCalculator calculator;
+ private final VatRounding defaultRounding;
+
+ public InvoiceController(VatCalculator calculator, @Value("${billing.vat.rounding}") VatRounding defaultRounding) {
+ this.calculator = calculator;
+ this.defaultRounding = defaultRounding;
+ }
+
+ @PostMapping("/quote")
+ public QuoteResponse quote(@RequestBody QuoteRequest request) {
+ if (request.vatRate() == null || request.lines() == null || request.lines().isEmpty()) {
+ throw new IllegalArgumentException("vatRate and at least one line are required");
+ }
+ VatRounding rounding = request.vatRounding() == null ? defaultRounding : request.vatRounding();
+ int discount = request.discountPercent() == null ? 0 : request.discountPercent();
+ List lines = request.lines().stream()
+ .map(line -> new VatCalculator.Line(line.description(),
+ AmountFormat.parse(line.unitPrice(), EUR, "unitPrice"), line.quantity()))
+ .toList();
+
+ VatCalculator.Quote quote = calculator.quote(lines, discount, request.vatRate(), rounding);
+
+ List quotedLines = quote.lines().stream()
+ .map(line -> new LineResponse(line.description(), line.quantity(), money(line.unitPrice()),
+ money(line.net()), money(line.vat()), money(line.gross())))
+ .toList();
+ return new QuoteResponse(EUR.getCurrencyCode(), request.vatRate().toPlainString(), rounding,
+ calculator.roundingMode(), discount, quotedLines, money(quote.net()), money(quote.vat()),
+ money(quote.gross()));
+ }
+
+ private static String money(BigDecimal amount) {
+ return AmountFormat.format(amount, EUR);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java
new file mode 100644
index 0000000..648fec6
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java
@@ -0,0 +1,31 @@
+package com.amigoscode.money.invoice;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+/** Small calculations the invoicing code uses everywhere. */
+public final class InvoiceMath {
+
+ private InvoiceMath() {
+ }
+
+ /** percent % of the amount, rounded half up to the cent: 15% of 9.90 is 1.485, so 1.49. */
+ public static BigDecimal percentOf(BigDecimal amount, int percent) {
+ // Exactly 0.15. new BigDecimal(15 / 100.0) would be the double nearest to 0.15:
+ // 0.1499999999999999944488848768742172978818416595458984375
+ BigDecimal rate = BigDecimal.valueOf(percent, 2);
+ return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
+ }
+
+ /** compareTo, not equals: equals says 100 and 100.00 are different, because their scale is. */
+ public static boolean isPaidInFull(BigDecimal due, BigDecimal paid) {
+ return paid.compareTo(due) >= 0;
+ }
+
+ /** The price of one item in a bundle, rounded half up to the cent: 3 for 10.00 is 3.33 each. */
+ public static BigDecimal unitPrice(BigDecimal bundlePrice, int units) {
+ // Without a scale and a rounding mode, divide() must return the exact answer, and 10/3 has no
+ // exact decimal answer: ArithmeticException.
+ return bundlePrice.divide(BigDecimal.valueOf(units), 2, RoundingMode.HALF_UP);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatCalculator.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatCalculator.java
new file mode 100644
index 0000000..2f374c2
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatCalculator.java
@@ -0,0 +1,62 @@
+package com.amigoscode.money.invoice;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.ArrayList;
+import java.util.List;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/** Works out the net, VAT and gross of an invoice. All amounts are in euros. */
+@Component
+public class VatCalculator {
+
+ public record Line(String description, BigDecimal unitPrice, int quantity) {
+ }
+
+ /** {@code vat} and {@code gross} are null with ON_TOTAL: the VAT is not worked out per line. */
+ public record QuotedLine(String description, BigDecimal unitPrice, int quantity,
+ BigDecimal net, BigDecimal vat, BigDecimal gross) {
+ }
+
+ public record Quote(List lines, BigDecimal net, BigDecimal vat, BigDecimal gross) {
+ }
+
+ private final RoundingMode roundingMode;
+
+ public VatCalculator(@Value("${billing.vat.rounding-mode}") RoundingMode roundingMode) {
+ this.roundingMode = roundingMode;
+ }
+
+ public RoundingMode roundingMode() {
+ return roundingMode;
+ }
+
+ public Quote quote(List lines, int discountPercent, BigDecimal vatRate, VatRounding rounding) {
+ List quoted = new ArrayList<>();
+ BigDecimal net = BigDecimal.ZERO;
+ BigDecimal vatOfTheLines = BigDecimal.ZERO;
+ for (Line line : lines) {
+ BigDecimal lineNet = line.unitPrice().multiply(BigDecimal.valueOf(line.quantity()));
+ lineNet = lineNet.subtract(InvoiceMath.percentOf(lineNet, discountPercent));
+ net = net.add(lineNet);
+ if (rounding == VatRounding.PER_LINE) {
+ BigDecimal lineVat = vat(lineNet, vatRate);
+ vatOfTheLines = vatOfTheLines.add(lineVat);
+ quoted.add(new QuotedLine(line.description(), line.unitPrice(), line.quantity(),
+ lineNet, lineVat, lineNet.add(lineVat)));
+ } else {
+ quoted.add(new QuotedLine(line.description(), line.unitPrice(), line.quantity(), lineNet, null, null));
+ }
+ }
+ // One rule for the whole invoice. With PER_LINE the invoice VAT IS the sum of the rounded lines,
+ // so what the customer reads on the lines always adds up to the total.
+ BigDecimal vat = rounding == VatRounding.PER_LINE ? vatOfTheLines : vat(net, vatRate);
+ return new Quote(quoted, net, vat, net.add(vat));
+ }
+
+ /** The VAT on one amount, rounded to the cent with the configured rounding mode. No double anywhere. */
+ public BigDecimal vat(BigDecimal net, BigDecimal vatRate) {
+ return net.multiply(vatRate).setScale(2, roundingMode);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatRounding.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatRounding.java
new file mode 100644
index 0000000..bab6145
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/invoice/VatRounding.java
@@ -0,0 +1,9 @@
+package com.amigoscode.money.invoice;
+
+/** Where VAT is rounded to the cent. The two give different answers, so an invoice has to say which. */
+public enum VatRounding {
+ /** Work out and round the VAT on every line, then add the rounded amounts up. */
+ PER_LINE,
+ /** Add the lines up first, then work out and round the VAT once, on the total. */
+ ON_TOTAL
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/AmountFormat.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/AmountFormat.java
new file mode 100644
index 0000000..18b61b0
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/AmountFormat.java
@@ -0,0 +1,41 @@
+package com.amigoscode.money.money;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.Currency;
+
+/**
+ * How money crosses the HTTP boundary. Out: a JSON string with exactly the currency's decimals.
+ * In: a string or a number, refused when it has more decimals than the currency has.
+ */
+public final class AmountFormat {
+
+ private AmountFormat() {
+ }
+
+ /**
+ * "0.10", "100.00", "12345678901234567.89", "334" for yen. Never an exponent ("1E+2"), never
+ * a lost zero ("0.1"). A string, because a JavaScript client reads every JSON number as a double.
+ */
+ public static String format(BigDecimal amount, Currency currency) {
+ if (amount == null) {
+ return null;
+ }
+ // UNNECESSARY: if the amount has more decimals than the currency, something upstream forgot to
+ // round. Fail loudly instead of rounding it here where nobody will look.
+ return amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.UNNECESSARY).toPlainString();
+ }
+
+ /** The amount a client sent, with the currency's scale. 0.30000000000000004 euros is a 400, not 0.30. */
+ public static BigDecimal parse(BigDecimal amount, Currency currency, String field) {
+ if (amount == null) {
+ throw new IllegalArgumentException(field + " is required");
+ }
+ int decimals = currency.getDefaultFractionDigits();
+ if (amount.stripTrailingZeros().scale() > decimals) {
+ throw new IllegalArgumentException(field + " " + amount.toPlainString() + " has more decimals than "
+ + currency.getCurrencyCode() + " allows (" + decimals + ")");
+ }
+ return amount.setScale(decimals, RoundingMode.UNNECESSARY);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/MinorUnits.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/MinorUnits.java
new file mode 100644
index 0000000..9b3022e
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/money/MinorUnits.java
@@ -0,0 +1,35 @@
+package com.amigoscode.money.money;
+
+import java.math.BigDecimal;
+import java.util.Currency;
+
+/**
+ * Money as a whole number of the currency's smallest unit: cents for EUR, yen for JPY (no minor
+ * unit), fils for BHD (1/1000 of a dinar). This is what most payment providers want in their API.
+ */
+public final class MinorUnits {
+
+ private MinorUnits() {
+ }
+
+ /** 19.99 EUR is 1999, 500 JPY is 500, 1.234 BHD is 1234. 12.345 EUR is an ArithmeticException. */
+ public static long toMinor(BigDecimal amount, Currency currency) {
+ // movePointRight is exact: no double, no rounding. longValueExact() throws when a fraction
+ // is left over, so an amount the currency cannot hold is refused instead of rounded.
+ return amount.movePointRight(decimals(currency)).longValueExact();
+ }
+
+ /** 1999 cents is 19.99 EUR, 500 is 500 JPY, 1234 fils is 1.234 BHD. */
+ public static BigDecimal fromMinor(long minor, Currency currency) {
+ return BigDecimal.valueOf(minor, decimals(currency));
+ }
+
+ /** 2 for EUR, 0 for JPY, 3 for BHD. The JDK knows them: Currency.getDefaultFractionDigits(). */
+ private static int decimals(Currency currency) {
+ int decimals = currency.getDefaultFractionDigits();
+ if (decimals < 0) {
+ throw new IllegalArgumentException(currency.getCurrencyCode() + " is not a currency you can pay with");
+ }
+ return decimals;
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/ChargeKey.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/ChargeKey.java
new file mode 100644
index 0000000..3fe4278
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/ChargeKey.java
@@ -0,0 +1,18 @@
+package com.amigoscode.money.payment;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+/**
+ * The key of the duplicate-charge check: the same invoice charged the same amount twice within a
+ * few seconds is a double click, not two purchases. The check keeps the keys it has seen in a HashSet.
+ */
+public record ChargeKey(String invoiceNumber, BigDecimal amount) {
+
+ public ChargeKey {
+ // A record's equals and hashCode call BigDecimal.equals and BigDecimal.hashCode, and both look
+ // at the scale: 10.0 and 10.00 would be two different keys. Give every key the same scale.
+ // UNNECESSARY: an amount with more than 2 decimals is a bug, so fail instead of rounding it.
+ amount = amount.setScale(2, RoundingMode.UNNECESSARY);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/Payment.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/Payment.java
new file mode 100644
index 0000000..5786493
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/Payment.java
@@ -0,0 +1,83 @@
+package com.amigoscode.money.payment;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import java.util.Currency;
+
+/** One card payment, captured in euros. Refunds are added up in {@code refunded}. */
+@Entity
+@Table(name = "payment")
+public class Payment {
+
+ /** The shop only takes euros. */
+ public static final Currency CURRENCY = Currency.getInstance("EUR");
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ /**
+ * numeric(19,2) in schema.sql: 17 digits before the point, 2 after, stored as decimal digits.
+ * precision and scale tell Hibernate the same thing, for when it generates or checks the schema.
+ */
+ @Column(nullable = false, precision = 19, scale = 2)
+ private BigDecimal amount;
+
+ @Column(nullable = false, precision = 19, scale = 2)
+ private BigDecimal refunded;
+
+ @Enumerated(EnumType.STRING)
+ @Column(nullable = false)
+ private PaymentStatus status;
+
+ @Column(name = "captured_on", nullable = false)
+ private LocalDate capturedOn;
+
+ protected Payment() {
+ }
+
+ public Payment(BigDecimal amount, LocalDate capturedOn) {
+ this.amount = amount;
+ this.refunded = BigDecimal.ZERO;
+ this.status = PaymentStatus.CAPTURED;
+ this.capturedOn = capturedOn;
+ }
+
+ /** Refunds part or all of the payment. compareTo, never == or equals: 19.99 and 19.990 are the same money. */
+ public void refund(BigDecimal refund) {
+ BigDecimal refundedAfter = refunded.add(refund);
+ if (refundedAfter.compareTo(amount) > 0) {
+ throw new RefundExceedsCapturedException(id, refund, refundedAfter, amount);
+ }
+ refunded = refundedAfter;
+ status = refunded.compareTo(amount) == 0 ? PaymentStatus.REFUNDED : PaymentStatus.PARTIALLY_REFUNDED;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public BigDecimal getAmount() {
+ return amount;
+ }
+
+ public BigDecimal getRefunded() {
+ return refunded;
+ }
+
+ public PaymentStatus getStatus() {
+ return status;
+ }
+
+ public LocalDate getCapturedOn() {
+ return capturedOn;
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentController.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentController.java
new file mode 100644
index 0000000..77442e8
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentController.java
@@ -0,0 +1,64 @@
+package com.amigoscode.money.payment;
+
+import com.amigoscode.money.money.AmountFormat;
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/payments")
+public class PaymentController {
+
+ /** {"amount": "0.10"}. A JSON number (0.10) is accepted too. */
+ public record PaymentRequest(BigDecimal amount) {
+ }
+
+ /** Money goes out as a string with the currency's decimals: "0.10", never 0.1 or 1E+1. */
+ public record PaymentResponse(long id, String amount, String refunded, String currency, PaymentStatus status) {
+
+ static PaymentResponse from(Payment payment) {
+ return new PaymentResponse(payment.getId(),
+ AmountFormat.format(payment.getAmount(), Payment.CURRENCY),
+ AmountFormat.format(payment.getRefunded(), Payment.CURRENCY),
+ Payment.CURRENCY.getCurrencyCode(), payment.getStatus());
+ }
+ }
+
+ public record DailyTotalResponse(LocalDate date, int payments, String total, String currency, long payoutCents) {
+ }
+
+ private final PaymentService service;
+
+ public PaymentController(PaymentService service) {
+ this.service = service;
+ }
+
+ @PostMapping
+ @ResponseStatus(HttpStatus.CREATED)
+ public PaymentResponse capture(@RequestBody PaymentRequest request) {
+ BigDecimal amount = AmountFormat.parse(request.amount(), Payment.CURRENCY, "amount");
+ return PaymentResponse.from(service.capture(amount));
+ }
+
+ @PostMapping("/{id}/refunds")
+ public PaymentResponse refund(@PathVariable long id, @RequestBody PaymentRequest request) {
+ BigDecimal amount = AmountFormat.parse(request.amount(), Payment.CURRENCY, "amount");
+ return PaymentResponse.from(service.refund(id, amount));
+ }
+
+ @GetMapping("/daily-total")
+ public DailyTotalResponse dailyTotal(@RequestParam(required = false) LocalDate date) {
+ PaymentService.DailyTotal total = service.dailyTotal(date == null ? service.today() : date);
+ return new DailyTotalResponse(total.date(), total.payments(),
+ AmountFormat.format(total.total(), Payment.CURRENCY), Payment.CURRENCY.getCurrencyCode(),
+ total.payoutCents());
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentNotFoundException.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentNotFoundException.java
new file mode 100644
index 0000000..bac9367
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentNotFoundException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.money.payment;
+
+public class PaymentNotFoundException extends RuntimeException {
+
+ public PaymentNotFoundException(long id) {
+ super("Payment " + id + " does not exist");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentRepository.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentRepository.java
new file mode 100644
index 0000000..c95e591
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentRepository.java
@@ -0,0 +1,10 @@
+package com.amigoscode.money.payment;
+
+import java.time.LocalDate;
+import java.util.List;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface PaymentRepository extends JpaRepository {
+
+ List findByCapturedOnOrderById(LocalDate capturedOn);
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentService.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentService.java
new file mode 100644
index 0000000..d205aa0
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentService.java
@@ -0,0 +1,60 @@
+package com.amigoscode.money.payment;
+
+import java.math.BigDecimal;
+import java.time.Clock;
+import java.time.LocalDate;
+import java.util.List;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class PaymentService {
+
+ /** What the finance team sees at the end of the day, and what is paid out to the shop's bank account. */
+ public record DailyTotal(LocalDate date, int payments, BigDecimal total, long payoutCents) {
+ }
+
+ private final PaymentRepository payments;
+ private final Clock clock;
+
+ public PaymentService(PaymentRepository payments, Clock clock) {
+ this.payments = payments;
+ this.clock = clock;
+ }
+
+ @Transactional
+ public Payment capture(BigDecimal amount) {
+ if (amount.signum() <= 0) {
+ throw new IllegalArgumentException("amount must be more than 0");
+ }
+ return payments.save(new Payment(amount, today()));
+ }
+
+ @Transactional
+ public Payment refund(long paymentId, BigDecimal amount) {
+ if (amount.signum() <= 0) {
+ throw new IllegalArgumentException("amount must be more than 0");
+ }
+ Payment payment = payments.findById(paymentId).orElseThrow(() -> new PaymentNotFoundException(paymentId));
+ payment.refund(amount);
+ return payment;
+ }
+
+ /** Adds the day's payments up in Java, one by one, the way a report or a reconciliation job does. */
+ @Transactional(readOnly = true)
+ public DailyTotal dailyTotal(LocalDate date) {
+ List captured = payments.findByCapturedOnOrderById(date);
+ BigDecimal total = BigDecimal.ZERO;
+ for (Payment payment : captured) {
+ total = total.add(payment.getAmount());
+ }
+ // The bank file wants whole cents. movePointRight(2) is exact, and longValueExact() throws
+ // instead of quietly dropping anything that is left over.
+ long payoutCents = total.movePointRight(2).longValueExact();
+ return new DailyTotal(date, captured.size(), total, payoutCents);
+ }
+
+ public LocalDate today() {
+ return LocalDate.now(clock);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentStatus.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentStatus.java
new file mode 100644
index 0000000..0dca89b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/PaymentStatus.java
@@ -0,0 +1,7 @@
+package com.amigoscode.money.payment;
+
+public enum PaymentStatus {
+ CAPTURED,
+ PARTIALLY_REFUNDED,
+ REFUNDED
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/RefundExceedsCapturedException.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/RefundExceedsCapturedException.java
new file mode 100644
index 0000000..c1dfb5b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/payment/RefundExceedsCapturedException.java
@@ -0,0 +1,9 @@
+package com.amigoscode.money.payment;
+
+public class RefundExceedsCapturedException extends RuntimeException {
+
+ public RefundExceedsCapturedException(long paymentId, Object refund, Object refundedAfter, Object captured) {
+ super("Refunding " + refund + " on payment " + paymentId + " would make the total refunded "
+ + refundedAfter + ", more than the " + captured + " captured");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/BillSplitter.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/BillSplitter.java
new file mode 100644
index 0000000..57aa9df
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/BillSplitter.java
@@ -0,0 +1,32 @@
+package com.amigoscode.money.split;
+
+import com.amigoscode.money.money.MinorUnits;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Currency;
+import java.util.List;
+
+/** Splits a bill between people so that the parts add up to the bill, to the last cent. */
+public final class BillSplitter {
+
+ private BillSplitter() {
+ }
+
+ /** 100.00 EUR between 3 is 33.34 + 33.33 + 33.33. 1000 JPY between 3 is 334 + 333 + 333. */
+ public static List split(BigDecimal amount, Currency currency, int people) {
+ if (people < 1) {
+ throw new IllegalArgumentException("people must be at least 1");
+ }
+ // Work in whole minor units (cents, yen, fils): integers divide with a remainder, and the
+ // remainder is exactly the number of parts that get one unit more.
+ long total = MinorUnits.toMinor(amount, currency);
+ long each = Math.floorDiv(total, people);
+ long remainder = Math.floorMod(total, people);
+ List parts = new ArrayList<>();
+ for (int i = 0; i < people; i++) {
+ long part = i < remainder ? each + 1 : each;
+ parts.add(MinorUnits.fromMinor(part, currency));
+ }
+ return parts;
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/SplitController.java b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/SplitController.java
new file mode 100644
index 0000000..17a3291
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/java/com/amigoscode/money/split/SplitController.java
@@ -0,0 +1,41 @@
+package com.amigoscode.money.split;
+
+import com.amigoscode.money.money.AmountFormat;
+import com.amigoscode.money.money.MinorUnits;
+import java.math.BigDecimal;
+import java.util.Currency;
+import java.util.List;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/bills")
+public class SplitController {
+
+ /** {"amount": "100.00", "currency": "EUR", "people": 3} */
+ public record SplitRequest(BigDecimal amount, String currency, int people) {
+ }
+
+ public record SplitResponse(String currency, String amount, int people, List parts,
+ List partsInMinorUnits, String sumOfParts) {
+ }
+
+ @PostMapping("/split")
+ public SplitResponse split(@RequestBody SplitRequest request) {
+ if (request.currency() == null) {
+ throw new IllegalArgumentException("currency is required");
+ }
+ Currency currency = Currency.getInstance(request.currency());
+ BigDecimal amount = AmountFormat.parse(request.amount(), currency, "amount");
+
+ List parts = BillSplitter.split(amount, currency, request.people());
+
+ BigDecimal sum = parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
+ return new SplitResponse(currency.getCurrencyCode(), AmountFormat.format(amount, currency), request.people(),
+ parts.stream().map(part -> AmountFormat.format(part, currency)).toList(),
+ parts.stream().map(part -> MinorUnits.toMinor(part, currency)).toList(),
+ AmountFormat.format(sum, currency));
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/application.properties b/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/application.properties
new file mode 100644
index 0000000..3697c98
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/application.properties
@@ -0,0 +1,18 @@
+spring.application.name=money-as-double
+
+# Postgres from compose.yaml. Port 5452 so it does not clash with a Postgres you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5452/money}
+spring.datasource.username=${DB_USER:money}
+spring.datasource.password=${DB_PASSWORD:money}
+
+# schema.sql drops the table and creates it again on every start.
+spring.sql.init.mode=always
+# Hibernate compares every entity field with its column at startup. Change the Java type without the
+# column type (or the other way round) and the application refuses to start, with a message that says why.
+spring.jpa.hibernate.ddl-auto=validate
+spring.jpa.open-in-view=false
+
+# How VAT is rounded to the cent, and where: on every line (PER_LINE) or once on the total (ON_TOTAL).
+# A quote request can ask for the other place with "vatRounding".
+billing.vat.rounding-mode=HALF_UP
+billing.vat.rounding=PER_LINE
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/schema.sql
new file mode 100644
index 0000000..d7b8c1d
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/main/resources/schema.sql
@@ -0,0 +1,12 @@
+-- Applied on every start (./demo, ./check, ./mvnw verify): the table is dropped and created again,
+-- so the database always has exactly what this file says. In a real project this would be a
+-- Flyway or Liquibase migration.
+drop table if exists payment;
+
+create table payment (
+ id bigserial primary key,
+ amount numeric(19,2) not null check (amount > 0),
+ refunded numeric(19,2) not null default 0 check (refunded >= 0 and refunded <= amount),
+ status text not null,
+ captured_on date not null
+);
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/Check.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/Check.java
new file mode 100644
index 0000000..b11ae94
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/Check.java
@@ -0,0 +1,115 @@
+package com.amigoscode.money;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Tasks 3 and 8 are inspection tasks: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the HTTP contract (passes from the start, must stay green)");
+ TASKS.put("1", "Task 1: See the cent go missing");
+ TASKS.put("2", "Task 2: Fix the payments: BigDecimal and numeric(19,2)");
+ TASKS.put("4", "Task 4: Fix the BigDecimal traps");
+ TASKS.put("5", "Task 5: Fix the VAT rounding");
+ TASKS.put("6", "Task 6: Split a bill without losing a cent, in any currency");
+ TASKS.put("7", "Task 7: Fix the JSON");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/DoubleFactsTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/DoubleFactsTest.java
new file mode 100644
index 0000000..96132e1
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/DoubleFactsTest.java
@@ -0,0 +1,45 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.math.BigDecimal;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Task 1. These pass on purpose: they pin down what a double does with money, so you can see
+ * exactly what goes wrong. They test Java itself, not your code, so no fix will ever change them.
+ */
+@Tag("task1")
+class DoubleFactsTest {
+
+ @Test
+ @DisplayName("double: 0.1 + 0.2 is not 0.3, it is 0.30000000000000004 (this documents the problem)")
+ void pointOnePlusPointTwo() {
+ double sum = 0.1 + 0.2;
+
+ assertThat(sum == 0.3).as("0.1 + 0.2 == 0.3").isFalse();
+ assertThat(Double.toString(sum)).isEqualTo("0.30000000000000004");
+ }
+
+ @Test
+ @DisplayName("double: 1,000 payments of 0.10 add up to 99.9999999999986, and (long) (total * 100) is 9999 cents (this documents the problem)")
+ void aThousandPaymentsOfTenCents() {
+ double total = 0;
+ for (int i = 0; i < 1000; i++) {
+ total += 0.10;
+ }
+
+ assertThat(Double.toString(total)).isEqualTo("99.9999999999986");
+ assertThat((long) (total * 100)).as("cents paid out").isEqualTo(9999);
+ }
+
+ @Test
+ @DisplayName("double: 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and new BigDecimal(double) shows it (this documents the problem)")
+ void pointOneIsNotPointOne() {
+ assertThat(new BigDecimal(0.1).toPlainString())
+ .isEqualTo("0.1000000000000000055511151231257827021181583404541015625");
+ assertThat(BigDecimal.valueOf(0.1).toPlainString()).as("BigDecimal.valueOf(0.1)").isEqualTo("0.1");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/HttpContractIT.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/HttpContractIT.java
new file mode 100644
index 0000000..2e7c60b
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/HttpContractIT.java
@@ -0,0 +1,43 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.money.support.IntegrationTest;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** The HTTP contract. These pass from the start and must keep passing, whatever you change. */
+@Tag("baseline")
+class HttpContractIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("HTTP: a payment is captured: 201, with an id and status CAPTURED")
+ void aPaymentIsCaptured() {
+ Reply reply = capture("\"19.99\"");
+
+ assertThat(reply.status()).as("status").isEqualTo(201);
+ assertThat(reply.get("id").asLong()).as("id").isEqualTo(1);
+ assertThat(reply.get("status").asString()).as("payment status").isEqualTo("CAPTURED");
+ }
+
+ @Test
+ @DisplayName("HTTP: a refund on a payment that does not exist returns 404 PAYMENT_NOT_FOUND")
+ void refundOnAnUnknownPayment() {
+ Reply reply = post("/api/payments/99/refunds", "{\"amount\":\"1.00\"}");
+
+ assertThat(reply.status()).as("status").isEqualTo(404);
+ assertThat(reply.get("code").asString()).isEqualTo("PAYMENT_NOT_FOUND");
+ }
+
+ @Test
+ @DisplayName("HTTP: a refund larger than the amount captured returns 422 REFUND_EXCEEDS_CAPTURED")
+ void refundLargerThanCaptured() {
+ capture("\"19.99\"");
+
+ Reply reply = post("/api/payments/1/refunds", "{\"amount\":\"20.00\"}");
+
+ assertThat(reply.status()).as("status").isEqualTo(422);
+ assertThat(reply.get("code").asString()).isEqualTo("REFUND_EXCEEDS_CAPTURED");
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/InvoiceMathTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/InvoiceMathTest.java
new file mode 100644
index 0000000..8b0b7d7
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/InvoiceMathTest.java
@@ -0,0 +1,57 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.money.invoice.InvoiceMath;
+import com.amigoscode.money.payment.ChargeKey;
+import java.math.BigDecimal;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Task 4: unit tests, no Spring, no database. */
+@Tag("task4")
+class InvoiceMathTest {
+
+ @Test
+ @DisplayName("percentOf: 15% of 9.90 is 1.49 (exactly 1.485, rounded half up), not 1.48")
+ void fifteenPercentOfNineNinety() {
+ assertThat(InvoiceMath.percentOf(new BigDecimal("9.90"), 15)).isEqualByComparingTo("1.49");
+ }
+
+ @Test
+ @DisplayName("isPaidInFull: 100 paid on an invoice of 100.00 is paid in full")
+ void sameAmountWithAnotherScaleIsPaid() {
+ assertThat(InvoiceMath.isPaidInFull(new BigDecimal("100.00"), new BigDecimal("100"))).isTrue();
+ }
+
+ @Test
+ @DisplayName("isPaidInFull: 99.99 paid on an invoice of 100.00 is not paid in full")
+ void lessIsNotPaid() {
+ assertThat(InvoiceMath.isPaidInFull(new BigDecimal("100.00"), new BigDecimal("99.99"))).isFalse();
+ }
+
+ @Test
+ @DisplayName("unitPrice: a bundle of 3 for 10.00 costs 3.33 each, instead of throwing ArithmeticException")
+ void bundleOfThree() {
+ assertThat(InvoiceMath.unitPrice(new BigDecimal("10.00"), 3)).isEqualByComparingTo("3.33");
+ assertThat(InvoiceMath.unitPrice(new BigDecimal("20.00"), 3)).as("3 for 20.00").isEqualByComparingTo("6.67");
+ }
+
+ @Test
+ @DisplayName("ChargeKey: 10.0 and 10.00 for the same invoice are the same charge, also inside a HashSet")
+ void sameChargeWithAnotherScale() {
+ ChargeKey first = new ChargeKey("INV-7", new BigDecimal("10.0"));
+ ChargeKey second = new ChargeKey("INV-7", new BigDecimal("10.00"));
+
+ Set seen = new HashSet<>();
+ seen.add(first);
+ boolean addedAgain = seen.add(second);
+
+ assertThat(first).isEqualTo(second);
+ assertThat(addedAgain).as("HashSet.add of the same charge returns false").isFalse();
+ assertThat(seen).hasSize(1);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MinorUnitsTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MinorUnitsTest.java
new file mode 100644
index 0000000..38176a9
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MinorUnitsTest.java
@@ -0,0 +1,43 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.money.money.MinorUnits;
+import java.math.BigDecimal;
+import java.util.Currency;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Task 6: unit tests, no Spring, no database. */
+@Tag("task6")
+class MinorUnitsTest {
+
+ private static final Currency EUR = Currency.getInstance("EUR");
+ private static final Currency JPY = Currency.getInstance("JPY");
+ private static final Currency BHD = Currency.getInstance("BHD");
+
+ @Test
+ @DisplayName("Minor units: 19.99 EUR is 1999 cents, 500 JPY is 500 yen, 1.234 BHD is 1234 fils")
+ void toMinorUnits() {
+ assertThat(MinorUnits.toMinor(new BigDecimal("19.99"), EUR)).as("19.99 EUR").isEqualTo(1999);
+ assertThat(MinorUnits.toMinor(new BigDecimal("500"), JPY)).as("500 JPY").isEqualTo(500);
+ assertThat(MinorUnits.toMinor(new BigDecimal("1.234"), BHD)).as("1.234 BHD").isEqualTo(1234);
+ }
+
+ @Test
+ @DisplayName("Minor units: 12.345 EUR is refused with an ArithmeticException, not rounded to 1234 or 1235 cents")
+ void moreDecimalsThanTheCurrencyHasIsRefused() {
+ assertThatThrownBy(() -> MinorUnits.toMinor(new BigDecimal("12.345"), EUR))
+ .isInstanceOf(ArithmeticException.class);
+ }
+
+ @Test
+ @DisplayName("Minor units: 1999 cents is 19.99 EUR, 500 yen is 500 JPY, 1234 fils is 1.234 BHD")
+ void fromMinorUnits() {
+ assertThat(MinorUnits.fromMinor(1999, EUR)).as("1999 EUR cents").isEqualTo(new BigDecimal("19.99"));
+ assertThat(MinorUnits.fromMinor(500, JPY)).as("500 yen").isEqualTo(new BigDecimal("500"));
+ assertThat(MinorUnits.fromMinor(1234, BHD)).as("1234 fils").isEqualTo(new BigDecimal("1.234"));
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MoneyJsonIT.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MoneyJsonIT.java
new file mode 100644
index 0000000..26fd031
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/MoneyJsonIT.java
@@ -0,0 +1,76 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.money.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import tools.jackson.databind.JsonNode;
+
+/** Task 7: what goes over the wire. */
+@Tag("task7")
+class MoneyJsonIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("JSON: money in a response is a string with 2 decimals: \"0.10\" and \"0.00\" for a payment, \"0.10\" for the daily total")
+ void moneyIsAStringWithTheCurrencyDecimals() {
+ Reply payment = capture("\"0.10\"");
+ Reply total = get("/api/payments/daily-total");
+
+ assertString(payment.get("amount"), "0.10");
+ assertString(payment.get("refunded"), "0.00");
+ assertString(total.get("total"), "0.10");
+ }
+
+ @Test
+ @DisplayName("JSON: an invoice of 80.00 + 25% VAT has a gross of \"100.00\", never 1E+2")
+ void noExponent() {
+ Reply quote = post("/api/invoices/quote",
+ "{\"vatRate\":\"0.25\",\"lines\":[{\"description\":\"Chair\",\"unitPrice\":\"80.00\",\"quantity\":1}]}");
+
+ assertThat(quote.status()).as("status: " + quote.body()).isEqualTo(200);
+ assertString(quote.get("net"), "80.00");
+ assertString(quote.get("vat"), "20.00");
+ assertString(quote.get("gross"), "100.00");
+ assertThat(quote.body()).as("the whole response").doesNotContain("E+");
+ }
+
+ @Test
+ @DisplayName("JSON: 12345678901234567.89 comes back as \"12345678901234567.89\", every digit (a JavaScript client would read 12345678901234568 from a number)")
+ void largeAmountComesBackExactly() {
+ Reply payment = capture("\"12345678901234567.89\"");
+
+ assertThat(payment.status()).as("status: " + payment.body()).isEqualTo(201);
+ assertString(payment.get("amount"), "12345678901234567.89");
+ }
+
+ @Test
+ @DisplayName("JSON: an amount may be sent as a string (\"0.10\") or as a number (0.10)")
+ void stringOrNumber() {
+ Reply asString = capture("\"0.10\"");
+ Reply asNumber = capture("0.10");
+
+ assertThat(asString.status()).as("\"0.10\": " + asString.body()).isEqualTo(201);
+ assertThat(asNumber.status()).as("0.10: " + asNumber.body()).isEqualTo(201);
+ List stored = jdbc.queryForList("select amount::numeric from payment order by id", BigDecimal.class);
+ assertThat(stored).hasSize(2).allSatisfy(amount -> assertThat(amount).isEqualByComparingTo("0.10"));
+ }
+
+ @Test
+ @DisplayName("JSON: an amount with more decimals than EUR has (0.30000000000000004) is refused with 400, not rounded to 0.30")
+ void tooManyDecimalsIsRefused() {
+ Reply reply = capture("0.30000000000000004");
+
+ assertThat(reply.status()).as("status: " + reply.body()).isEqualTo(400);
+ assertThat(jdbc.queryForObject("select count(*) from payment", Integer.class)).as("payments stored").isZero();
+ }
+
+ private static void assertString(JsonNode node, String expected) {
+ assertThat(node).as("field is missing").isNotNull();
+ assertThat(node.isString()).as("sent as a JSON string, but it was: " + node).isTrue();
+ assertThat(node.asString()).isEqualTo(expected);
+ }
+}
diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PaymentsIT.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PaymentsIT.java
new file mode 100644
index 0000000..dfa7a61
--- /dev/null
+++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PaymentsIT.java
@@ -0,0 +1,88 @@
+package com.amigoscode.money;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.money.support.IntegrationTest;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Task 2: the payments are stored and added up exactly. */
+@Tag("task2")
+class PaymentsIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Payments: the daily total of 1,000 payments of 0.10 is exactly 100.00")
+ void dailyTotalIsExact() {
+ captureTenCentsTimes(1000);
+
+ Reply total = get("/api/payments/daily-total");
+
+ assertThat(total.status()).as("status").isEqualTo(200);
+ assertThat(total.get("payments").asInt()).as("payments").isEqualTo(1000);
+ assertThat(amount(total.get("total"))).as("total").isEqualByComparingTo("100.00");
+ }
+
+ @Test
+ @DisplayName("Payments: 1,000 payments of 0.10 pay out 10000 cents to the bank, not 9999")
+ void payoutIsExact() {
+ captureTenCentsTimes(1000);
+
+ Reply total = get("/api/payments/daily-total");
+
+ assertThat(total.get("payoutCents").asLong()).as("payoutCents").isEqualTo(10000);
+ }
+
+ @Test
+ @DisplayName("Refunds: 19.99 captured, refunded as 10.00 then 9.99: both refunds are accepted and the payment is REFUNDED")
+ void refundInTwoParts() {
+ capture("\"19.99\"");
+
+ Reply first = post("/api/payments/1/refunds", "{\"amount\":\"10.00\"}");
+ Reply second = post("/api/payments/1/refunds", "{\"amount\":\"9.99\"}");
+
+ assertThat(first.status()).as("first refund").isEqualTo(200);
+ assertThat(second.status()).as("second refund: " + second.body()).isEqualTo(200);
+ assertThat(second.get("status").asString()).as("payment status").isEqualTo("REFUNDED");
+ assertThat(amount(second.get("refunded"))).as("refunded").isEqualByComparingTo("19.99");
+ }
+
+ @Test
+ @DisplayName("Storage: amount and refunded are numeric(19,2) columns, not double precision")
+ void columnsAreNumeric() {
+ List