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> columns = jdbc.queryForList(""" + select column_name, data_type, numeric_precision, numeric_scale + from information_schema.columns + where table_name = 'payment' and column_name in ('amount', 'refunded') + order by column_name + """); + + assertThat(columns).hasSize(2).allSatisfy(column -> { + assertThat(column.get("data_type")).as(column.get("column_name") + " type").isEqualTo("numeric"); + assertThat(column.get("numeric_precision")).as(column.get("column_name") + " precision").isEqualTo(19); + assertThat(column.get("numeric_scale")).as(column.get("column_name") + " scale").isEqualTo(2); + }); + } + + @Test + @DisplayName("Storage: a payment of 12345678901234567.89 is stored to the cent (a double keeps only about 16 digits)") + void largeAmountIsStoredExactly() { + Reply reply = capture("\"12345678901234567.89\""); + + assertThat(reply.status()).as("status: " + reply.body()).isEqualTo(201); + String stored = jdbc.queryForObject("select amount::text from payment where id = 1", String.class); + assertThat(stored).as("amount in the database").isEqualTo("12345678901234567.89"); + } + + private void captureTenCentsTimes(int payments) { + for (int i = 0; i < payments; i++) { + Reply reply = capture("\"0.10\""); + assertThat(reply.status()).as("payment " + (i + 1) + ": " + reply.body()).isEqualTo(201); + } + BigDecimal stored = jdbc.queryForObject("select count(*) from payment", BigDecimal.class); + assertThat(stored).isEqualByComparingTo(BigDecimal.valueOf(payments)); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java new file mode 100644 index 0000000..98b18fc --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java @@ -0,0 +1,25 @@ +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; + +/** Task 1. Passes on purpose: the database has the same problem as Java when the column is a float type. */ +@Tag("task1") +class PostgresColumnTypesIT extends IntegrationTest { + + @Test + @DisplayName("Postgres: sum() of 1,000 rows of 0.10 is 99.9999999999986 in a double precision column, 100.00 in numeric(19,2) (this documents the problem)") + void sumDependsOnTheColumnType() { + String asDouble = jdbc.queryForObject( + "select sum(x)::text from (select 0.10::double precision as x from generate_series(1, 1000)) t", String.class); + String asNumeric = jdbc.queryForObject( + "select sum(x)::text from (select 0.10::numeric(19,2) as x from generate_series(1, 1000)) t", String.class); + + assertThat(asDouble).as("double precision").isEqualTo("99.9999999999986"); + assertThat(asNumeric).as("numeric(19,2)").isEqualTo("100.00"); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/SplitTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/SplitTest.java new file mode 100644 index 0000000..c1e1885 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/SplitTest.java @@ -0,0 +1,55 @@ +package com.amigoscode.money; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.money.split.BillSplitter; +import java.math.BigDecimal; +import java.util.Currency; +import java.util.List; +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. The parts are compared with equals on purpose: a + * part of a yen bill has no decimals, a part of a dinar bill has three. + */ +@Tag("task6") +class SplitTest { + + private static final Currency EUR = Currency.getInstance("EUR"); + + @Test + @DisplayName("Split: 100.00 EUR between 3 is 33.34 + 33.33 + 33.33, which adds up to 100.00") + void hundredBetweenThree() { + List parts = BillSplitter.split(new BigDecimal("100.00"), EUR, 3); + + assertThat(parts).containsExactly(new BigDecimal("33.34"), new BigDecimal("33.33"), new BigDecimal("33.33")); + assertThat(sum(parts)).as("sum of the parts").isEqualByComparingTo("100.00"); + } + + @Test + @DisplayName("Split: 0.05 EUR between 3 is 0.02 + 0.02 + 0.01: no part is more than one cent bigger than another") + void fiveCentsBetweenThree() { + assertThat(BillSplitter.split(new BigDecimal("0.05"), EUR, 3)) + .containsExactly(new BigDecimal("0.02"), new BigDecimal("0.02"), new BigDecimal("0.01")); + } + + @Test + @DisplayName("Split: 1000 JPY between 3 is 334 + 333 + 333: the yen has no minor unit") + void yenHasNoDecimals() { + assertThat(BillSplitter.split(new BigDecimal("1000"), Currency.getInstance("JPY"), 3)) + .containsExactly(new BigDecimal("334"), new BigDecimal("333"), new BigDecimal("333")); + } + + @Test + @DisplayName("Split: 10.000 BHD between 3 is 3.334 + 3.333 + 3.333: the Bahraini dinar has 3 decimals") + void dinarHasThreeDecimals() { + assertThat(BillSplitter.split(new BigDecimal("10.000"), Currency.getInstance("BHD"), 3)) + .containsExactly(new BigDecimal("3.334"), new BigDecimal("3.333"), new BigDecimal("3.333")); + } + + private static BigDecimal sum(List parts) { + return parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/VatCalculatorTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/VatCalculatorTest.java new file mode 100644 index 0000000..60ce837 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/VatCalculatorTest.java @@ -0,0 +1,75 @@ +package com.amigoscode.money; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.money.invoice.VatCalculator; +import com.amigoscode.money.invoice.VatCalculator.Line; +import com.amigoscode.money.invoice.VatCalculator.Quote; +import com.amigoscode.money.invoice.VatCalculator.QuotedLine; +import com.amigoscode.money.invoice.VatRounding; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: unit tests, no Spring, no database. */ +@Tag("task5") +class VatCalculatorTest { + + private static final BigDecimal TWENTY_PERCENT = new BigDecimal("0.20"); + private static final BigDecimal FIFTEEN_PERCENT = new BigDecimal("0.15"); + + /** Three espressos at 0.99: 0.198 of VAT each, 0.594 on the total. */ + private static final List THREE_ESPRESSOS = List.of( + new Line("Espresso", new BigDecimal("0.99"), 1), + new Line("Espresso", new BigDecimal("0.99"), 1), + new Line("Espresso", new BigDecimal("0.99"), 1)); + + private final VatCalculator halfUp = new VatCalculator(RoundingMode.HALF_UP); + + @Test + @DisplayName("VAT: 15% of 6.70 is exactly 1.005, so 1.01 rounded half up (with doubles it comes out as 1.00)") + void halfACentIsRoundedUp() { + assertThat(halfUp.vat(new BigDecimal("6.70"), FIFTEEN_PERCENT)).isEqualByComparingTo("1.01"); + } + + @Test + @DisplayName("VAT: a credit note is the mirror image of its invoice: 15% of 9.90 is 1.49, 15% of -9.90 is -1.49") + void creditNoteMirrorsTheInvoice() { + assertThat(halfUp.vat(new BigDecimal("9.90"), FIFTEEN_PERCENT)).as("invoice").isEqualByComparingTo("1.49"); + assertThat(halfUp.vat(new BigDecimal("-9.90"), FIFTEEN_PERCENT)).as("credit note").isEqualByComparingTo("-1.49"); + } + + @Test + @DisplayName("PER_LINE: 3 x 0.99 at 20% is 0.20 of VAT on every line, and the invoice VAT is their sum, 0.60") + void perLineAddsUp() { + Quote quote = halfUp.quote(THREE_ESPRESSOS, 0, TWENTY_PERCENT, VatRounding.PER_LINE); + + assertThat(quote.lines()).extracting(QuotedLine::vat).allSatisfy(vat -> assertThat(vat).isEqualByComparingTo("0.20")); + assertThat(quote.vat()).as("invoice VAT").isEqualByComparingTo("0.60"); + assertThat(quote.gross()).as("invoice gross").isEqualByComparingTo("3.57"); + } + + @Test + @DisplayName("ON_TOTAL: 3 x 0.99 at 20%: the VAT is worked out once, on 2.97, so 0.59, and the lines carry no VAT") + void onTotalRoundsOnce() { + Quote quote = halfUp.quote(THREE_ESPRESSOS, 0, TWENTY_PERCENT, VatRounding.ON_TOTAL); + + assertThat(quote.vat()).as("invoice VAT").isEqualByComparingTo("0.59"); + assertThat(quote.gross()).as("invoice gross").isEqualByComparingTo("3.56"); + assertThat(quote.lines()).extracting(QuotedLine::vat).as("VAT on the lines").containsOnlyNulls(); + } + + @Test + @DisplayName("Rounding mode: 25% of 0.50 is exactly 0.125: HALF_UP makes it 0.13, HALF_EVEN 0.12") + void theRoundingModeIsUsed() { + VatCalculator halfEven = new VatCalculator(RoundingMode.HALF_EVEN); + BigDecimal fiftyCents = new BigDecimal("0.50"); + BigDecimal twentyFivePercent = new BigDecimal("0.25"); + + assertThat(halfUp.vat(fiftyCents, twentyFivePercent)).as("HALF_UP").isEqualByComparingTo("0.13"); + assertThat(halfEven.vat(fiftyCents, twentyFivePercent)).as("HALF_EVEN").isEqualByComparingTo("0.12"); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/support/IntegrationTest.java b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/support/IntegrationTest.java new file mode 100644 index 0000000..bc5cf40 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/java/com/amigoscode/money/support/IntegrationTest.java @@ -0,0 +1,127 @@ +package com.amigoscode.money.support; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.LocalDate; +import java.time.ZoneOffset; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcPrint; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.testcontainers.postgresql.PostgreSQLContainer; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.cfg.JsonNodeFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Base class for the *IT tests. They start the real application against a real Postgres started by + * Testcontainers (Docker must be running), because a double precision column only behaves like a + * double precision column in a real database. One container is shared by every test class. + * + * The tests talk to the application the way a client does: JSON over HTTP (MockMvc), and they read + * the table with plain SQL. So they do not care whether a field in your code is a double or a + * BigDecimal: only what goes over the wire and what lands in the database counts. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +// print = NONE: ./check prints one line per criterion, not every request and response. +@AutoConfigureMockMvc(print = MockMvcPrint.NONE) +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + /** "Today" for every test, so the daily total never depends on the clock. */ + protected static final LocalDate TODAY = LocalDate.of(2026, 3, 2); + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + /** Reads JSON numbers as BigDecimal with every digit the server sent: 100.00 stays 100.00. */ + private static final JsonMapper JSON = JsonMapper.builder() + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .disable(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES) + .build(); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + Clock fixedClock() { + return Clock.fixed(TODAY.atTime(12, 0).toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + } + } + + /** A response: the status, the body as text, and the body parsed. */ + public record Reply(int status, String body, JsonNode json) { + + public JsonNode get(String field) { + return json.get(field); + } + } + + @Autowired + protected MockMvc mvc; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyTable() { + jdbc.execute("truncate table payment restart identity"); + } + + protected Reply post(String path, String json) { + return send(MockMvcRequestBuilders.post(path).contentType(MediaType.APPLICATION_JSON).content(json)); + } + + protected Reply get(String path) { + return send(MockMvcRequestBuilders.get(path)); + } + + /** Captures a payment of this amount, written into the JSON as it is: {"amount":"0.10"} or {"amount":0.10}. */ + protected Reply capture(String jsonAmount) { + return post("/api/payments", "{\"amount\":" + jsonAmount + "}"); + } + + /** An amount from the JSON, whether the server sent it as a number (0.1) or as a string ("0.10"). */ + protected static BigDecimal amount(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + return node.isNumber() ? node.decimalValue() : new BigDecimal(node.asString()); + } + + private Reply send(RequestBuilder request) { + try { + MockHttpServletResponse response = mvc.perform(request).andReturn().getResponse(); + String body = response.getContentAsString(StandardCharsets.UTF_8); + return new Reply(response.getStatus(), body, body.isBlank() ? null : JSON.readTree(body)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/13-money-as-double/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/solution/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/13-money-as-double/start/.mvn/jvm.config b/java/concepts/junior-mid/13-money-as-double/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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/13-money-as-double/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/13-money-as-double/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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/13-money-as-double/start/check b/java/concepts/junior-mid/13-money-as-double/start/check new file mode 100755 index 0000000..222bd2b --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/check.cmd b/java/concepts/junior-mid/13-money-as-double/start/check.cmd new file mode 100644 index 0000000..0ddfe59 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/compose.yaml b/java/concepts/junior-mid/13-money-as-double/start/compose.yaml new file mode 100644 index 0000000..6b086b6 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/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/start/demo b/java/concepts/junior-mid/13-money-as-double/start/demo new file mode 100755 index 0000000..3381037 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/demo.cmd b/java/concepts/junior-mid/13-money-as-double/start/demo.cmd new file mode 100644 index 0000000..dbf76ae --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/inspect b/java/concepts/junior-mid/13-money-as-double/start/inspect new file mode 100755 index 0000000..d0831fd --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/inspect.cmd b/java/concepts/junior-mid/13-money-as-double/start/inspect.cmd new file mode 100644 index 0000000..863a6d0 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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.money.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/13-money-as-double/start/mvnw b/java/concepts/junior-mid/13-money-as-double/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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/13-money-as-double/start/mvnw.cmd b/java/concepts/junior-mid/13-money-as-double/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/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/13-money-as-double/start/pom.xml b/java/concepts/junior-mid/13-money-as-double/start/pom.xml new file mode 100644 index 0000000..68e5b64 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/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/start/src/main/java/com/amigoscode/money/ApiExceptionHandler.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/MoneyApplication.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/demo/App.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/demo/Db.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/demo/Demo.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/demo/Http.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/demo/Inspect.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/invoice/InvoiceController.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/InvoiceController.java new file mode 100644 index 0000000..e50144b --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/InvoiceController.java @@ -0,0 +1,64 @@ +package com.amigoscode.money.invoice; + +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, BigDecimal unitPrice, BigDecimal net, BigDecimal vat, + BigDecimal gross) { + } + + public record QuoteResponse(String currency, BigDecimal vatRate, VatRounding vatRounding, RoundingMode roundingMode, + int discountPercent, List lines, BigDecimal net, BigDecimal vat, + BigDecimal 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(), line.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(), line.unitPrice(), + line.net(), line.vat(), line.gross())) + .toList(); + return new QuoteResponse(EUR.getCurrencyCode(), request.vatRate(), rounding, + calculator.roundingMode(), discount, quotedLines, quote.net(), quote.vat(), quote.gross()); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java new file mode 100644 index 0000000..852fe72 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/InvoiceMath.java @@ -0,0 +1,26 @@ +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) { + BigDecimal rate = new BigDecimal(percent / 100.0); + return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP); + } + + public static boolean isPaidInFull(BigDecimal due, BigDecimal paid) { + return paid.equals(due); + } + + /** 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) { + return bundlePrice.divide(BigDecimal.valueOf(units)); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/VatCalculator.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/VatCalculator.java new file mode 100644 index 0000000..1a5a82a --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/VatCalculator.java @@ -0,0 +1,56 @@ +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; + for (Line line : lines) { + BigDecimal lineNet = line.unitPrice().multiply(BigDecimal.valueOf(line.quantity())); + lineNet = lineNet.subtract(InvoiceMath.percentOf(lineNet, discountPercent)); + BigDecimal lineVat = vat(lineNet, vatRate); + quoted.add(new QuotedLine(line.description(), line.unitPrice(), line.quantity(), + lineNet, lineVat, lineNet.add(lineVat))); + net = net.add(lineNet); + } + BigDecimal vat = vat(net, vatRate); + // Tidy up the totals (3.5600 becomes 3.56), so that equals() works on them. + return new Quote(quoted, net.stripTrailingZeros(), vat.stripTrailingZeros(), net.add(vat).stripTrailingZeros()); + } + + /** The VAT on one amount, rounded to the cent. */ + public BigDecimal vat(BigDecimal net, BigDecimal vatRate) { + double vat = net.doubleValue() * vatRate.doubleValue(); + return BigDecimal.valueOf(Math.round(vat * 100) / 100.0); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/invoice/VatRounding.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/money/MinorUnits.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/money/MinorUnits.java new file mode 100644 index 0000000..ef2ad30 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/money/MinorUnits.java @@ -0,0 +1,24 @@ +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) { + return (long) (amount.doubleValue() * 100); + } + + /** 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 / 100.0); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/ChargeKey.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/ChargeKey.java new file mode 100644 index 0000000..3a8fae6 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/ChargeKey.java @@ -0,0 +1,10 @@ +package com.amigoscode.money.payment; + +import java.math.BigDecimal; + +/** + * 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) { +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/Payment.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/Payment.java new file mode 100644 index 0000000..897c10c --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/Payment.java @@ -0,0 +1,78 @@ +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.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; + + @Column(nullable = false) + private double amount; + + @Column(nullable = false) + private double refunded; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private PaymentStatus status; + + @Column(name = "captured_on", nullable = false) + private LocalDate capturedOn; + + protected Payment() { + } + + public Payment(double amount, LocalDate capturedOn) { + this.amount = amount; + this.refunded = 0; + this.status = PaymentStatus.CAPTURED; + this.capturedOn = capturedOn; + } + + /** Refunds part or all of the payment. */ + public void refund(double refund) { + double refundedAfter = refunded + refund; + if (refundedAfter > amount) { + throw new RefundExceedsCapturedException(id, refund, refundedAfter, amount); + } + refunded = refundedAfter; + status = refunded == amount ? PaymentStatus.REFUNDED : PaymentStatus.PARTIALLY_REFUNDED; + } + + public Long getId() { + return id; + } + + public double getAmount() { + return amount; + } + + public double getRefunded() { + return refunded; + } + + public PaymentStatus getStatus() { + return status; + } + + public LocalDate getCapturedOn() { + return capturedOn; + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentController.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentController.java new file mode 100644 index 0000000..1276f07 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentController.java @@ -0,0 +1,56 @@ +package com.amigoscode.money.payment; + +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(double amount) { + } + + public record PaymentResponse(long id, double amount, double refunded, String currency, PaymentStatus status) { + + static PaymentResponse from(Payment payment) { + return new PaymentResponse(payment.getId(), payment.getAmount(), payment.getRefunded(), + Payment.CURRENCY.getCurrencyCode(), payment.getStatus()); + } + } + + public record DailyTotalResponse(LocalDate date, int payments, double 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) { + return PaymentResponse.from(service.capture(request.amount())); + } + + @PostMapping("/{id}/refunds") + public PaymentResponse refund(@PathVariable long id, @RequestBody PaymentRequest request) { + return PaymentResponse.from(service.refund(id, request.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(), total.total(), + Payment.CURRENCY.getCurrencyCode(), total.payoutCents()); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentNotFoundException.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/payment/PaymentRepository.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/payment/PaymentService.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentService.java new file mode 100644 index 0000000..f34cb04 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/payment/PaymentService.java @@ -0,0 +1,58 @@ +package com.amigoscode.money.payment; + +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, double 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(double amount) { + if (amount <= 0) { + throw new IllegalArgumentException("amount must be more than 0"); + } + return payments.save(new Payment(amount, today())); + } + + @Transactional + public Payment refund(long paymentId, double amount) { + if (amount <= 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); + double total = 0; + for (Payment payment : captured) { + total += payment.getAmount(); + } + // The bank file wants whole cents. + long payoutCents = (long) (total * 100); + 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/start/src/main/java/com/amigoscode/money/payment/PaymentStatus.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/payment/RefundExceedsCapturedException.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/main/java/com/amigoscode/money/split/BillSplitter.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/split/BillSplitter.java new file mode 100644 index 0000000..602f7e4 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/split/BillSplitter.java @@ -0,0 +1,24 @@ +package com.amigoscode.money.split; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Collections; +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"); + } + BigDecimal each = amount.divide(BigDecimal.valueOf(people), 2, RoundingMode.HALF_UP); + return new ArrayList<>(Collections.nCopies(people, each)); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/split/SplitController.java b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/split/SplitController.java new file mode 100644 index 0000000..2deac25 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/main/java/com/amigoscode/money/split/SplitController.java @@ -0,0 +1,41 @@ +package com.amigoscode.money.split; + +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, BigDecimal amount, int people, List parts, + List partsInMinorUnits, BigDecimal 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 = request.amount(); + if (amount == null) { + throw new IllegalArgumentException("amount is required"); + } + + List parts = BillSplitter.split(amount, currency, request.people()); + + BigDecimal sum = parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add); + return new SplitResponse(currency.getCurrencyCode(), amount, request.people(), parts, + parts.stream().map(part -> MinorUnits.toMinor(part, currency)).toList(), sum); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/main/resources/application.properties b/java/concepts/junior-mid/13-money-as-double/start/src/main/resources/application.properties new file mode 100644 index 0000000..3697c98 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/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/start/src/main/resources/schema.sql b/java/concepts/junior-mid/13-money-as-double/start/src/main/resources/schema.sql new file mode 100644 index 0000000..f04c87c --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/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 double precision not null check (amount > 0), + refunded double precision 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/start/src/test/java/com/amigoscode/money/Check.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/DoubleFactsTest.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/HttpContractIT.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/InvoiceMathTest.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/MinorUnitsTest.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/MoneyJsonIT.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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/start/src/test/java/com/amigoscode/money/PaymentsIT.java b/java/concepts/junior-mid/13-money-as-double/start/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/start/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> columns = jdbc.queryForList(""" + select column_name, data_type, numeric_precision, numeric_scale + from information_schema.columns + where table_name = 'payment' and column_name in ('amount', 'refunded') + order by column_name + """); + + assertThat(columns).hasSize(2).allSatisfy(column -> { + assertThat(column.get("data_type")).as(column.get("column_name") + " type").isEqualTo("numeric"); + assertThat(column.get("numeric_precision")).as(column.get("column_name") + " precision").isEqualTo(19); + assertThat(column.get("numeric_scale")).as(column.get("column_name") + " scale").isEqualTo(2); + }); + } + + @Test + @DisplayName("Storage: a payment of 12345678901234567.89 is stored to the cent (a double keeps only about 16 digits)") + void largeAmountIsStoredExactly() { + Reply reply = capture("\"12345678901234567.89\""); + + assertThat(reply.status()).as("status: " + reply.body()).isEqualTo(201); + String stored = jdbc.queryForObject("select amount::text from payment where id = 1", String.class); + assertThat(stored).as("amount in the database").isEqualTo("12345678901234567.89"); + } + + private void captureTenCentsTimes(int payments) { + for (int i = 0; i < payments; i++) { + Reply reply = capture("\"0.10\""); + assertThat(reply.status()).as("payment " + (i + 1) + ": " + reply.body()).isEqualTo(201); + } + BigDecimal stored = jdbc.queryForObject("select count(*) from payment", BigDecimal.class); + assertThat(stored).isEqualByComparingTo(BigDecimal.valueOf(payments)); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java new file mode 100644 index 0000000..98b18fc --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/PostgresColumnTypesIT.java @@ -0,0 +1,25 @@ +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; + +/** Task 1. Passes on purpose: the database has the same problem as Java when the column is a float type. */ +@Tag("task1") +class PostgresColumnTypesIT extends IntegrationTest { + + @Test + @DisplayName("Postgres: sum() of 1,000 rows of 0.10 is 99.9999999999986 in a double precision column, 100.00 in numeric(19,2) (this documents the problem)") + void sumDependsOnTheColumnType() { + String asDouble = jdbc.queryForObject( + "select sum(x)::text from (select 0.10::double precision as x from generate_series(1, 1000)) t", String.class); + String asNumeric = jdbc.queryForObject( + "select sum(x)::text from (select 0.10::numeric(19,2) as x from generate_series(1, 1000)) t", String.class); + + assertThat(asDouble).as("double precision").isEqualTo("99.9999999999986"); + assertThat(asNumeric).as("numeric(19,2)").isEqualTo("100.00"); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/SplitTest.java b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/SplitTest.java new file mode 100644 index 0000000..c1e1885 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/SplitTest.java @@ -0,0 +1,55 @@ +package com.amigoscode.money; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.money.split.BillSplitter; +import java.math.BigDecimal; +import java.util.Currency; +import java.util.List; +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. The parts are compared with equals on purpose: a + * part of a yen bill has no decimals, a part of a dinar bill has three. + */ +@Tag("task6") +class SplitTest { + + private static final Currency EUR = Currency.getInstance("EUR"); + + @Test + @DisplayName("Split: 100.00 EUR between 3 is 33.34 + 33.33 + 33.33, which adds up to 100.00") + void hundredBetweenThree() { + List parts = BillSplitter.split(new BigDecimal("100.00"), EUR, 3); + + assertThat(parts).containsExactly(new BigDecimal("33.34"), new BigDecimal("33.33"), new BigDecimal("33.33")); + assertThat(sum(parts)).as("sum of the parts").isEqualByComparingTo("100.00"); + } + + @Test + @DisplayName("Split: 0.05 EUR between 3 is 0.02 + 0.02 + 0.01: no part is more than one cent bigger than another") + void fiveCentsBetweenThree() { + assertThat(BillSplitter.split(new BigDecimal("0.05"), EUR, 3)) + .containsExactly(new BigDecimal("0.02"), new BigDecimal("0.02"), new BigDecimal("0.01")); + } + + @Test + @DisplayName("Split: 1000 JPY between 3 is 334 + 333 + 333: the yen has no minor unit") + void yenHasNoDecimals() { + assertThat(BillSplitter.split(new BigDecimal("1000"), Currency.getInstance("JPY"), 3)) + .containsExactly(new BigDecimal("334"), new BigDecimal("333"), new BigDecimal("333")); + } + + @Test + @DisplayName("Split: 10.000 BHD between 3 is 3.334 + 3.333 + 3.333: the Bahraini dinar has 3 decimals") + void dinarHasThreeDecimals() { + assertThat(BillSplitter.split(new BigDecimal("10.000"), Currency.getInstance("BHD"), 3)) + .containsExactly(new BigDecimal("3.334"), new BigDecimal("3.333"), new BigDecimal("3.333")); + } + + private static BigDecimal sum(List parts) { + return parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/VatCalculatorTest.java b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/VatCalculatorTest.java new file mode 100644 index 0000000..60ce837 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/VatCalculatorTest.java @@ -0,0 +1,75 @@ +package com.amigoscode.money; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.money.invoice.VatCalculator; +import com.amigoscode.money.invoice.VatCalculator.Line; +import com.amigoscode.money.invoice.VatCalculator.Quote; +import com.amigoscode.money.invoice.VatCalculator.QuotedLine; +import com.amigoscode.money.invoice.VatRounding; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: unit tests, no Spring, no database. */ +@Tag("task5") +class VatCalculatorTest { + + private static final BigDecimal TWENTY_PERCENT = new BigDecimal("0.20"); + private static final BigDecimal FIFTEEN_PERCENT = new BigDecimal("0.15"); + + /** Three espressos at 0.99: 0.198 of VAT each, 0.594 on the total. */ + private static final List THREE_ESPRESSOS = List.of( + new Line("Espresso", new BigDecimal("0.99"), 1), + new Line("Espresso", new BigDecimal("0.99"), 1), + new Line("Espresso", new BigDecimal("0.99"), 1)); + + private final VatCalculator halfUp = new VatCalculator(RoundingMode.HALF_UP); + + @Test + @DisplayName("VAT: 15% of 6.70 is exactly 1.005, so 1.01 rounded half up (with doubles it comes out as 1.00)") + void halfACentIsRoundedUp() { + assertThat(halfUp.vat(new BigDecimal("6.70"), FIFTEEN_PERCENT)).isEqualByComparingTo("1.01"); + } + + @Test + @DisplayName("VAT: a credit note is the mirror image of its invoice: 15% of 9.90 is 1.49, 15% of -9.90 is -1.49") + void creditNoteMirrorsTheInvoice() { + assertThat(halfUp.vat(new BigDecimal("9.90"), FIFTEEN_PERCENT)).as("invoice").isEqualByComparingTo("1.49"); + assertThat(halfUp.vat(new BigDecimal("-9.90"), FIFTEEN_PERCENT)).as("credit note").isEqualByComparingTo("-1.49"); + } + + @Test + @DisplayName("PER_LINE: 3 x 0.99 at 20% is 0.20 of VAT on every line, and the invoice VAT is their sum, 0.60") + void perLineAddsUp() { + Quote quote = halfUp.quote(THREE_ESPRESSOS, 0, TWENTY_PERCENT, VatRounding.PER_LINE); + + assertThat(quote.lines()).extracting(QuotedLine::vat).allSatisfy(vat -> assertThat(vat).isEqualByComparingTo("0.20")); + assertThat(quote.vat()).as("invoice VAT").isEqualByComparingTo("0.60"); + assertThat(quote.gross()).as("invoice gross").isEqualByComparingTo("3.57"); + } + + @Test + @DisplayName("ON_TOTAL: 3 x 0.99 at 20%: the VAT is worked out once, on 2.97, so 0.59, and the lines carry no VAT") + void onTotalRoundsOnce() { + Quote quote = halfUp.quote(THREE_ESPRESSOS, 0, TWENTY_PERCENT, VatRounding.ON_TOTAL); + + assertThat(quote.vat()).as("invoice VAT").isEqualByComparingTo("0.59"); + assertThat(quote.gross()).as("invoice gross").isEqualByComparingTo("3.56"); + assertThat(quote.lines()).extracting(QuotedLine::vat).as("VAT on the lines").containsOnlyNulls(); + } + + @Test + @DisplayName("Rounding mode: 25% of 0.50 is exactly 0.125: HALF_UP makes it 0.13, HALF_EVEN 0.12") + void theRoundingModeIsUsed() { + VatCalculator halfEven = new VatCalculator(RoundingMode.HALF_EVEN); + BigDecimal fiftyCents = new BigDecimal("0.50"); + BigDecimal twentyFivePercent = new BigDecimal("0.25"); + + assertThat(halfUp.vat(fiftyCents, twentyFivePercent)).as("HALF_UP").isEqualByComparingTo("0.13"); + assertThat(halfEven.vat(fiftyCents, twentyFivePercent)).as("HALF_EVEN").isEqualByComparingTo("0.12"); + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/support/IntegrationTest.java b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/support/IntegrationTest.java new file mode 100644 index 0000000..bc5cf40 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/test/java/com/amigoscode/money/support/IntegrationTest.java @@ -0,0 +1,127 @@ +package com.amigoscode.money.support; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.LocalDate; +import java.time.ZoneOffset; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcPrint; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.testcontainers.postgresql.PostgreSQLContainer; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.cfg.JsonNodeFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Base class for the *IT tests. They start the real application against a real Postgres started by + * Testcontainers (Docker must be running), because a double precision column only behaves like a + * double precision column in a real database. One container is shared by every test class. + * + * The tests talk to the application the way a client does: JSON over HTTP (MockMvc), and they read + * the table with plain SQL. So they do not care whether a field in your code is a double or a + * BigDecimal: only what goes over the wire and what lands in the database counts. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +// print = NONE: ./check prints one line per criterion, not every request and response. +@AutoConfigureMockMvc(print = MockMvcPrint.NONE) +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + /** "Today" for every test, so the daily total never depends on the clock. */ + protected static final LocalDate TODAY = LocalDate.of(2026, 3, 2); + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + /** Reads JSON numbers as BigDecimal with every digit the server sent: 100.00 stays 100.00. */ + private static final JsonMapper JSON = JsonMapper.builder() + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .disable(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES) + .build(); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + Clock fixedClock() { + return Clock.fixed(TODAY.atTime(12, 0).toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + } + } + + /** A response: the status, the body as text, and the body parsed. */ + public record Reply(int status, String body, JsonNode json) { + + public JsonNode get(String field) { + return json.get(field); + } + } + + @Autowired + protected MockMvc mvc; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyTable() { + jdbc.execute("truncate table payment restart identity"); + } + + protected Reply post(String path, String json) { + return send(MockMvcRequestBuilders.post(path).contentType(MediaType.APPLICATION_JSON).content(json)); + } + + protected Reply get(String path) { + return send(MockMvcRequestBuilders.get(path)); + } + + /** Captures a payment of this amount, written into the JSON as it is: {"amount":"0.10"} or {"amount":0.10}. */ + protected Reply capture(String jsonAmount) { + return post("/api/payments", "{\"amount\":" + jsonAmount + "}"); + } + + /** An amount from the JSON, whether the server sent it as a number (0.1) or as a string ("0.10"). */ + protected static BigDecimal amount(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + return node.isNumber() ? node.decimalValue() : new BigDecimal(node.asString()); + } + + private Reply send(RequestBuilder request) { + try { + MockHttpServletResponse response = mvc.perform(request).andReturn().getResponse(); + String body = response.getContentAsString(StandardCharsets.UTF_8); + return new Reply(response.getStatus(), body, body.isBlank() ? null : JSON.readTree(body)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/13-money-as-double/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/13-money-as-double/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/13-money-as-double/start/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/INTERVIEW_TASKS.md b/java/concepts/junior-mid/14-authorisation-and-jwt/INTERVIEW_TASKS.md new file mode 100644 index 0000000..63affce --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/INTERVIEW_TASKS.md @@ -0,0 +1,332 @@ +# Interview Tasks — Authorisation and JWT + +> **In `start/`, `./check` FAILS on purpose: 15 of 31 checks pass.** Tasks 2, 4, 5 and 6 turn the +> other 16 green. Tasks 1, 3, 7 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 7 are nothing else, and +Tasks 4 to 6 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. Do not change `TokenService` +(the tokens `POST /login` hands out are correct) or anything in `demo/`. The demo users all have +the password `password`. + +--- + +## Task 1: See It Break (10 min) + +**Story:** *A merchant phones support: "an invoice I have never seen is in our accounting export, +and one of ours has a different amount". The team says it cannot be another merchant: every request +needs a signed token. Before you change anything, find out what a valid token lets you do.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. Read the first two sections. Which broken tokens were + refused? Which got in? +2. Read the third section. alice works for merchant-a. Which invoices did she read, change and + delete? +3. `./demo --sql`. Find the SQL for `GET /invoices/4`. What is in its `WHERE` clause, and what is + missing? +4. Open `InvoiceService.get` and `InvoiceController.get`. Where does the code look at the token? +5. `./inspect`. How many invoices exist, how many can alice's token read, and which ones are + marked `NOT this token's merchant`? Look at the `updated_by` column. +6. Read the `RESULT` lines. Write down, for each one, whether it is an authentication problem or an + authorisation problem. + +**Acceptance Criteria** (`./check 1`, already passing: authentication works) +- [ ] You can explain the difference between authentication and authorisation, using this demo +- [ ] You can say which request turned a valid token into a data leak, and which line of code let it +- [ ] You can explain why a perfectly signed token does not help here +- [ ] `AuthenticationIT`: no token, garbage, a wrong key, `alg: none` and an edited payload are all + refused with a 401, and the right password returns a token that works + +**Hints:** +- Spring Security answered "who is this?" before the controller ran. What question did nobody ask? +- `findById` has one parameter + +--- + +## Task 2: Fix the IDOR (20 min) + +**Story:** *A merchant may only see and touch its own invoices. Whatever id is in the URL, the +answer for another merchant's invoice must be the same as for an invoice that does not exist. Fix +`InvoiceService`, `InvoiceController` and `InvoiceRepository`.* + +**Acceptance Criteria** (`./check 2`) +- [ ] alice still reads her own invoice — `ObjectLevelAuthorisationIT.ownInvoiceIsReadable` + (already passing: keep it that way) +- [ ] alice asks for invoice 4 (merchant-b), and bob for invoice 1 (merchant-a): 404, with none of + the invoice's data in the body — `ObjectLevelAuthorisationIT.anotherMerchantsInvoiceIsNotFound` +- [ ] alice updates invoice 5: 404, and the database still has the old amount + — `ObjectLevelAuthorisationIT.anotherMerchantsInvoiceCannotBeChanged` +- [ ] alice deletes invoice 6: 404, and the invoice is still there + — `ObjectLevelAuthorisationIT.anotherMerchantsInvoiceCannotBeDeleted` +- [ ] Another merchant's invoice and an id that does not exist get exactly the same 404 + — `ObjectLevelAuthorisationIT.anotherMerchantsInvoiceLooksLikeAnIdThatDoesNotExist` +- [ ] alice can still update and delete her own invoices + — `ObjectLevelAuthorisationIT.ownInvoicesCanStillBeChangedAndDeleted` (already passing) +- [ ] `./demo` prints `ok` on every row of the OBJECT-LEVEL AUTHORISATION section + +**Hints:** +- The merchant id is already in the token. `Caller.of(jwt)` reads it +- A Spring Data method name can carry two conditions +- Do not load the invoice and then compare the merchant in Java. Why not? (Think about the next + developer who adds an endpoint.) +- Bonus: `JpaRepository` hands every caller `findById`, `findAll` and `deleteById`. What could you + extend instead, so the unscoped query no longer exists? + +--- + +## Task 3: Inspect the Object-Level Fix (15 min) + +**Story:** *The tests are green. Now show what changed, and defend the 404 in a design review.* + +**Steps:** +1. `./demo --sql`. Compare the SQL for `GET /invoices/4` with Task 1 step 3. Who wrote the new + condition? +2. `./demo --bodies`. Compare the body of `GET /invoices/4` with the body of `GET /invoices/999`. + What could alice learn if one said 403 and the other 404? +3. `./inspect`, then `./inspect --user bob`. How many invoices exist, and how many can each token + read? What happened to invoice 4, and when will that be fixed? +4. Read the `RESULT` lines of `./demo`. alice still "read 3 invoices of merchant-b". Through which + request? +5. Find every place in `InvoiceService` that reads an invoice. How many queries does a new + developer have to remember to scope? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can quote the `WHERE` clause that does the authorisation, and say where the merchant id + in it comes from +- [ ] You can give two reasons to answer 404 rather than 403 for another tenant's record, and one + situation where 403 is the better answer +- [ ] You can explain why the check belongs in the query and not in an `if` after `findById` + +--- + +## Task 4: Fix the Merchant That Comes From the Request (20 min) + +**Story:** *The support tool sends `?merchantId=` to look at a merchant's invoices, and +`POST /invoices` reads the whole JSON body into the entity. Both let alice act as merchant B, and the +second one lets her choose the status and even the id. The merchant must come from the token and +from nowhere else, and a client may only send the fields it is allowed to choose.* + +**Acceptance Criteria** (`./check 4`) +- [ ] `GET /invoices` still returns alice's 3 invoices — `TenantFromRequestIT.listReturnsOwnInvoices` + (already passing) +- [ ] `GET /invoices?merchantId=merchant-b` as alice returns only merchant-a's invoices + — `TenantFromRequestIT.merchantIdParameterIsIgnored` +- [ ] `POST /invoices` with `"merchantId":"merchant-b"` creates the invoice for merchant-a + — `TenantFromRequestIT.merchantIdInTheBodyIsIgnored` +- [ ] `POST /invoices` with `"id":4` creates a new invoice and leaves invoice 4 alone + — `TenantFromRequestIT.idInTheBodyIsIgnored` +- [ ] `POST /invoices` with `"status":"PAID"` still creates a `DRAFT` + — `TenantFromRequestIT.statusInTheBodyIsIgnored` +- [ ] A missing customer or a negative amount is a 400, not a 500 + — `TenantFromRequestIT.invalidInvoiceIsABadRequest` + +**Hints:** +- A record with only the fields the client may set. What happens to the JSON fields it has no + component for? +- What does Spring Data's `save` do with an entity whose id is already set? +- `@Valid` and two Bean Validation annotations + +**Inspect:** +1. `./demo --bodies`. Read the body of each `POST /invoices` response. Which fields of the request + were ignored, and how? +2. `./demo --sql`. Find the SQL of the `{id: 4}` request. Before the fix it was a `select` and an + `update ... where id=?` (`TASKS_GUIDED.md` Task 1 shows it). Why did an insert become an update? +3. Is there a legitimate reason for a support person to read another merchant's invoices? Where + would that endpoint live, and what would protect it? (Task 5.) + +--- + +## Task 5: Fix the Admin Endpoint (20 min) + +**Story:** *`GET /admin/invoices` lists every merchant's invoices for the platform's support staff. +Right now bob, an ordinary user, can call it. Only callers with the role ADMIN may. Fix +`AdminController`, then whatever else it takes.* + +**Acceptance Criteria** (`./check 5`) +- [ ] bob (roles USER) gets 403 Forbidden — `AdminRoleIT.userIsForbidden` +- [ ] admin (roles USER, ADMIN) gets 200 with every merchant's invoices + — `AdminRoleIT.adminSeesEveryMerchant` (already passing: keep it that way) +- [ ] No token at all is still a 401, not a 403 — `AdminRoleIT.noTokenIsUnauthorizedNotForbidden` + (already passing) +- [ ] A MockMvc request with spring-security-test's `jwt()` and only `ROLE_USER` gets 403 + — `AdminRoleIT.mockMvcJwtWithOnlyRoleUserIsForbidden` +- [ ] A token with `"roles": ["USER","ADMIN"]` becomes the authorities `ROLE_USER` and `ROLE_ADMIN` + — `RolesConverterTest.rolesClaimBecomesRoleAuthorities` + +**Hints:** +- Add the annotation first and run `./demo` before you change anything else. Then run it again + after every change. Expect two surprises +- `./inspect --user admin` shows the authorities Spring Security built from the token +- `hasRole('ADMIN')` looks for one exact string. Which? +- `JwtGrantedAuthoritiesConverter` has a setter for the claim name and one for the prefix + +**Inspect:** +1. `./inspect --user admin` before and after the converter change. What is `FACTOR_BEARER`? +2. `./demo --bodies`. Compare the `WWW-Authenticate` header of bob's 403 with the one on a 401. +3. Which annotation would you use instead of `hasRole` if the token carried `"scope": "invoices:admin"`? + +--- + +## Task 6: Fix Token Validation (15 min) + +**Story:** *Security review: "an expired token from last week still works, and a token without a +merchant reaches the controllers". Every token must be fresh, from our issuer, and say who and +which merchant it is for. Fix the `JwtDecoder` in `SecurityConfig`.* + +**Acceptance Criteria** (`./check 6`) +- [ ] A token that expired an hour ago is a 401 whose `WWW-Authenticate` says `Jwt expired at` + — `TokenValidationIT.expiredTokenIsUnauthorized` +- [ ] A token that is not valid yet (`nbf` in the future) is a 401 + — `TokenValidationIT.notYetValidTokenIsUnauthorized` +- [ ] A token without `merchant_id` is a 401 — `TokenValidationIT.tokenWithoutMerchantIsUnauthorized` +- [ ] A token without `sub` is a 401 — `TokenValidationIT.tokenWithoutSubjectIsUnauthorized` +- [ ] A token from another issuer is still a 401 — `TokenValidationIT.otherIssuerIsUnauthorized` + (already passing) +- [ ] `./demo` prints `RESULT: OK` + +**Hints:** +- Read the Javadoc of `NimbusJwtDecoder.setJwtValidator`. Does it add a validator? +- `JwtValidators` has a factory method that takes the issuer +- `DelegatingOAuth2TokenValidator` combines validators; `JwtClaimValidator` checks one claim + +**Inspect:** +1. `./inspect --expired` before and after the fix. The signature matches both times. Why was that + never enough? +2. How long after `exp` is a token still accepted? Find the default in the Spring Security docs or + source, and say why it exists. +3. A token without `merchant_id` gave `200` and an empty list before the fix. Why is that worse + than a 401? + +--- + +## Task 7: Inspect a JWT (15 min) + +**Story:** *A colleague wants to put the user's email and date of birth "in the token, to save a +database call", and asks whether the token is encrypted. Answer with evidence.* + +**Steps:** +1. `./inspect`. Read the header and the payload. What did you need to decode them? +2. Copy the middle part of the token and decode it yourself with `jshell` (it ships with the JDK): + `new String(java.util.Base64.getUrlDecoder().decode(""))`. +3. `./inspect --edit merchant_id=merchant-b`. What changed in the payload, what in the signature + line, and what did Spring Security do? +4. `./inspect --alg-none`. What is in part 3? Why must a server never let the token choose its own + algorithm? +5. Open `application.properties`. Where does the signing key come from, and who else can make + valid tokens if they get it? +6. `./demo --bodies`: read the `WWW-Authenticate` header of the 401s. + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can say what each of the three parts of a JWT is, and which part proves anything +- [ ] You can say what must never go into a JWT, and why +- [ ] You can explain why HS256 with a shared key is fine for this project and not for a system + with several services, and what RS256 and a JWKS endpoint change + +--- + +## Task 8: Compare, and What JWTs Cannot Do (15 min) + +**Story:** *"We use JWTs, so we are secure" is the sentence this project exists to take apart. +Collect the evidence, then answer the follow-ups.* + +**Steps:** +1. Run `./demo` in `start/` (your fixed copy) and in `../solution`. Take the `RESULT` lines you + wrote down in Task 1 (they are also in `TASKS_GUIDED.md`, Task 1) and put each one under + authentication, object-level authorisation or function-level authorisation. +2. alice leaves the company at 10:00. Her token was issued at 09:58. Until when can she read + invoices? What would you change to shorten that, and what does each option cost? +3. An admin is demoted to USER. When does `/admin/invoices` start refusing them? +4. A new endpoint `GET /invoices/{id}/pdf` is added next month. Which of today's fixes protect it + automatically, and which does its author have to remember? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can explain why a JWT cannot be revoked by default, and two ways to live with that +- [ ] You can say where `@PreAuthorize` fits and where query scoping fits, and why you need both +- [ ] You can name a defence below the repository (in Hibernate or in Postgres) + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- What is the difference between authentication and authorisation? (Authentication is proving who + you are: here, a token signed by our issuer that names alice. Authorisation is deciding what that + person may do: which endpoints, and which records. Spring Security did the first on every request + from the start. Nobody did the second, so a valid token for merchant A read merchant B's data.) +- 401 or 403? (401 Unauthorized, despite its name, means not authenticated: no token, or one the + server does not trust, expired, wrong signature. It comes with `WWW-Authenticate: Bearer`. 403 + Forbidden means authenticated and not allowed: bob's valid token on an admin endpoint.) +- What is an IDOR? (Insecure Direct Object Reference, called Broken Object Level Authorization in + the OWASP API Security Top 10, where it is number one. The API takes an id from the client and + returns or changes that object without checking that it belongs to the caller. Changing + `/invoices/1` to `/invoices/4` is the whole attack.) +- How do you fix it? (Scope every query to the owner taken from the token: + `findByIdAndMerchantId(id, caller.merchantId())`. Never trust an owner id from the URL, a query + parameter or the body. Make the unscoped query hard to reach, for example a repository that + extends `Repository` and only declares scoped methods.) +- Why 404 and not 403 for another tenant's record? (A 403 confirms the id exists, so an attacker + can enumerate ids and learn how many invoices other merchants have. A 404 says nothing. It also + falls out naturally from a scoped query: the row is simply not found. 403 is right when the caller + may know the resource exists, for example a document shared with them read-only.) +- Are random UUIDs instead of 1, 2, 3 a fix? (No. They make ids harder to guess, but ids leak: in + URLs, logs, emails, browser history. It is defence in depth, never the authorisation check.) +- What is mass assignment? (Binding a request body straight onto an entity, so the client can set + fields it should never control: the tenant, the status, the id. Here `"id": 4` turned `save` + into a merge that overwrote another merchant's invoice. Fix: a request DTO with only the allowed + fields, and the server sets the rest.) +- Your `@PreAuthorize("hasRole('ADMIN')")` lets everyone in. Why? (Method security is off. In Spring + Security 6 and 7 you need `@EnableMethodSecurity`; without it the annotation is silently + ignored.) +- It now locks the admin out. Why? (`hasRole('ADMIN')` checks for the authority `ROLE_ADMIN`. The + default `JwtAuthenticationConverter` reads the `scope` or `scp` claim and makes `SCOPE_...` + authorities. A `roles` claim is ignored. Configure `JwtGrantedAuthoritiesConverter` with + `setAuthoritiesClaimName("roles")` and `setAuthorityPrefix("ROLE_")`, or check + `hasAuthority('SCOPE_...')` if your tokens carry scopes.) +- What is in a JWT, and who can read it? (Three base64url parts: header, payload, signature. The + header and payload are encoded, not encrypted: anyone holding the token can read them. The + signature proves who made it and that nobody changed it. So: no passwords, no secrets, no personal + data you would not print in a log.) +- What must the server check on every token? (The signature, with an algorithm the server chose, + never the one the header asks for. Then `exp` and `nbf`, the issuer, and for a real identity + provider the audience. Then the claims your code relies on. In Spring, careful: + `setJwtValidator` replaces the defaults instead of adding to them.) +- HS256 or RS256? (HS256 uses one shared secret: whoever can verify can also sign. Fine for one + application, like this project. With an identity provider and several services you use RS256 or + ES256: the provider signs with a private key, every API verifies with the public key it downloads + from the provider's JWKS endpoint, and a stolen API cannot mint tokens.) +- How do you log out with JWTs? (You cannot un-issue a token: it is valid until `exp` wherever it + goes. So keep access tokens short, 5 to 15 minutes, and use a refresh token that the server can + revoke. If you need instant revocation, keep a deny-list of token ids (`jti`) or a per-user + "tokens issued before" timestamp, and check it on every request. That brings back the database + lookup a stateless token was meant to avoid.) +- How do you test this? (With real tokens against the running application for the token rules, as + most tests here do. spring-security-test's `jwt()` post-processor for MockMvc is fast and good for + the rules after authentication, but it skips the `JwtDecoder`, so it cannot catch a decoder that + accepts expired tokens.) + +## Tips for Interviewers + +- The most common weak answer is "we validate the JWT, so we are fine". Ask what stops alice from + changing the id in the URL. Task 1 is that question with evidence. +- Ask the candidate to predict what `GET /invoices/4` with alice's token returns before running + `./demo`. A strong candidate asks what the query looks like before answering. +- In Task 2, watch for `findById` followed by `if (!invoice.getMerchantId().equals(...)) throw new + ForbiddenException()`. It works for this endpoint. Ask what happens with the next endpoint, and + with a list query, and whether a 403 leaks anything. +- In Task 4, ask what Spring Data `save` does with an entity whose id is set. Few candidates know + it merges, and that is the difference between "the client can create a wrong invoice" and "the + client can overwrite any invoice". +- In Task 5, ask the candidate to explain the second surprise (the admin locked out) before reading + any code. Candidates who know the `ROLE_` and `SCOPE_` prefixes find it in a minute. +- For senior candidates, go past the tasks: a support role that may read other tenants (an explicit + admin endpoint, audited), tenant isolation below the application (Hibernate `@TenantId` or + filters, Postgres row-level security), token revocation, and key rotation with `kid` and JWKS. diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/README.md b/java/concepts/junior-mid/14-authorisation-and-jwt/README.md new file mode 100644 index 0000000..0c97ea5 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/README.md @@ -0,0 +1,185 @@ +# Authorisation and JWT — Authenticated Is Not Authorised + +> **In `start/`, `./check` FAILS on purpose: 15 of 31 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5 and 6 turn the other 16 green. + +An invoicing API serves many merchants. Every request needs a valid JWT, Spring Security checks the +signature, and an unsigned or edited token gets a 401. It looks secure. Then alice, who works for +merchant A, changes `/invoices/1` to `/invoices/4` in the URL and reads merchant B's invoice. She +changes it, deletes another one, creates one in merchant B's name, and steals a fourth by putting +`"id": 4` in a request body. This project lets you watch that happen with real tokens, fix it, and +see what each fix changes. + +It answers the interview questions students most often get wrong: + +- "What is the difference between authentication and authorisation? When is it a 401, when a 403?" +- "What is an IDOR? How do you stop one user reading another user's data?" +- "Another tenant's record: 403 or 404?" +- "Your `@PreAuthorize("hasRole('ADMIN')")` lets everyone in, or locks the admin out. Why?" +- "What is inside a JWT? Can the user read it? Can the user change it?" +- "How do you log a user out when you use JWTs?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, **Spring Security 7** (OAuth2 resource server, JWT), Spring Data JPA +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers, spring-security-test + +## 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 5453 +./demo # watch alice read, change and delete merchant B's invoices +./check # 15 of 31 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 who can do what + +Starts the real application, logs in as alice (merchant A), bob (merchant B) and admin, and sends +real HTTP requests with real tokens: fair ones, broken tokens, and the requests an attacker would +send. Prints one row per request (who, request, status, whose data came back) and ends with one +`RESULT` line per problem found. Every run starts from the same six invoices. + +``` +./demo the whole tour +./demo --sql print the SQL of every request above its row: is the merchant in the WHERE clause? +./demo --bodies print every response body and WWW-Authenticate header +./demo --help +``` + +### `./inspect` — take a token apart + +Logs in (or makes a broken token), then shows the token's header and claims decoded, when it +expires, whether its signature matches, what Spring Security makes of it (accepted or refused, and +the authorities), and which invoices it can read compared with which exist. Only sends GET requests. + +``` +./inspect alice's token +./inspect --user admin bob or admin instead +./inspect --edit merchant_id=merchant-b alice's token, edited after signing +./inspect --alg-none alice's claims with no signature at all +./inspect --expired alice's claims, expired an hour ago +./inspect --token eyJ... any token you paste +``` + +### `./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.** Most of them start +the real application against a real Postgres (Testcontainers) and send it real HTTP requests with +real tokens. Nothing waits for a token to expire: the tests write the expiry in the past. + +## The code + +``` +start/src/main/java/com/amigoscode/authz/ +├── security/ +│ ├── SecurityConfig.java the filter chain, the JwtDecoder, the authorities converter. Tasks 5 and 6 +│ ├── TokenService.java makes the tokens POST /login hands out. Nothing to change here +│ ├── JwtProperties.java authz.jwt.*: the dev-only key, the issuer, how long a token lives +│ ├── Caller.java who is calling (username, merchant), read from the checked token +│ └── SecurityProblems.java the bodies of the 401 and the 403 +├── login/ POST /login: checks the bcrypt password, returns a token +├── invoice/ +│ ├── InvoiceController.java the /invoices endpoints. Tasks 2 and 4 +│ ├── InvoiceService.java THE MAIN BUG IS HERE. Tasks 2 and 4 +│ └── InvoiceRepository.java the queries. Task 2 +├── admin/AdminController.java GET /admin/invoices: every merchant's invoices. Task 5 +└── demo/ the demo and inspect tools. Nothing to change here +``` + +| Endpoint | What it does | +|---|---| +| `POST /login` | `{"username":"alice","password":"password"}` returns a token. The only endpoint without a token | +| `GET /invoices` | the caller's invoices | +| `GET` / `PUT` / `DELETE /invoices/{id}` | one invoice | +| `POST /invoices` | a new invoice | +| `GET /admin/invoices` | every merchant's invoices, for the platform's support staff | + +| User | Merchant | Roles | Password | +|---|---|---|---| +| alice | merchant-a (invoices 1-3) | USER | `password` | +| bob | merchant-b (invoices 4-6) | USER | `password` | +| admin | platform | USER, ADMIN | `password` | + +**About the signing key.** Tokens are signed with HMAC-SHA256. The key is in +`application.properties` as `dev-only-not-a-secret-...`, on purpose, in a public repository: it is +a placeholder for your laptop and nothing else. Set `JWT_SECRET` to override it. A real key never +lives in a file in git (Task 7 says where it does live, and why production uses an identity +provider with RS256 instead). + +## 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 it break: every token is checked, and alice still reads merchant B's invoices | `./check 1` (passes: authentication already works) | +| 2 | Fix the IDOR: scope every query to the merchant in the token | `./check 2` | +| 3 | Inspect the fix: the WHERE clause, and 404 rather than 403 | you answer questions | +| 4 | Fix the merchant that comes from the request, and the mass assignment | `./check 4` | +| 5 | Fix the admin endpoint: a role check that really checks | `./check 5` | +| 6 | Fix token validation: expired tokens and missing claims | `./check 6` | +| 7 | Inspect a JWT: who can read it, what the signature proves, where the key lives | you answer questions | +| 8 | Compare, and what JWTs cannot do | you answer questions | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 31 of 31. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +
+Spoiler: the bugs and the fixes + +**Authentication works (Task 1).** No token, garbage, a wrong key, `alg: none`, a payload edited +after signing: all 401, from the first run. The token tells the API *who* alice is. Nothing asks +whether invoice 4 is *hers*. + +**IDOR (Task 2).** `InvoiceService` loads invoices with `findById(id)`. Fix: every query carries +the merchant from the token, `findByIdAndMerchantId(id, caller.merchantId())`, and the repository +extends `Repository` instead of `JpaRepository` so the unscoped `findById` no longer exists. Another +merchant's invoice is a **404**, the same as an id that does not exist: a 403 would confirm that the +id exists. + +**Tenant from the request (Task 4).** `GET /invoices?merchantId=merchant-b` trusted the parameter, +and `POST /invoices` bound the JSON straight onto the entity, so the client chose the merchant, the +status and even the id (`"id": 4` turned the insert into a merge that overwrote invoice 4). Fix: the +merchant only ever comes from the token, and a `CreateInvoiceRequest` record holds only what the +client may choose, with `@Valid`. + +**Roles (Task 5).** `@PreAuthorize("hasRole('ADMIN')")` does nothing without +`@EnableMethodSecurity`. Once it works, it locks the admin out: the default +`JwtAuthenticationConverter` reads the `scope` claim into `SCOPE_` authorities, and our token says +`"roles": ["ADMIN"]`. Fix: read `roles` with the prefix `ROLE_`. + +**Token validation (Task 6).** `decoder.setJwtValidator(new JwtIssuerValidator(...))` *replaces* +the default validators, so expiry was no longer checked. Fix: +`JwtValidators.createDefaultWithIssuer(...)` plus required `sub` and `merchant_id` claims. + +**401 or 403.** 401: I do not know who you are (no token, or one I do not trust). 403: I know who +you are, and you may not do this. 404: as far as you are concerned, it does not exist. + +
diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/TASKS_GUIDED.md b/java/concepts/junior-mid/14-authorisation-and-jwt/TASKS_GUIDED.md new file mode 100644 index 0000000..0f739b5 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/TASKS_GUIDED.md @@ -0,0 +1,896 @@ +# Guided Tasks — Authorisation and JWT + +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. Tokens, times and port numbers differ on every run. The +statuses, the rows and the `RESULT` lines should match. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +**Two things to know about the tools** + +- `./demo` and `./inspect` start the real application on a free port and send it real HTTP requests + with a real `Authorization: Bearer` header. The good tokens come from `POST /login`. The broken + ones are made in Java (`demo/Forge.java`) the way an attacker would make them. +- `./demo` puts the six starting invoices back before it runs. `./inspect` changes nothing: run it + after `./demo` to see what the demo did to the data. + +--- + +## Task 1: See It Break + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +``` +Invoices 1-3 belong to merchant-a, invoices 4-6 to merchant-b (fresh data on every run). +alice works for merchant-a, bob for merchant-b, admin for the platform and has the ADMIN role. + +AUTHENTICATION: who are you? + who request status what came back verdict + ----- -------------------------------------------------- ------ ------------------------------------ ------- + - GET /invoices (no token) 401 nothing ok + alice POST /login (wrong password) 401 no token ok + alice POST /login 200 a token, 251 characters ok + bob POST /login 200 a token, 248 characters ok + admin POST /login 200 a token, 259 characters ok + alice GET /invoices 200 3 invoices of merchant-a ok + bob GET /invoices 200 3 invoices of merchant-b ok + +BROKEN TOKENS: alice's claims, but every token here must get a 401 + alice GET /invoices (merchant_id edited to merchant-b) 401 nothing ok + alice GET /invoices (alg none, no signature) 401 nothing ok + alice GET /invoices (signed with another key) 401 nothing ok + alice GET /invoices (expired an hour ago) 200 3 invoices of merchant-a <- LET IN, want 401 + alice GET /invoices (no merchant_id claim) 200 no invoices <- LET IN, want 401 + +OBJECT-LEVEL AUTHORISATION: is this invoice yours? + alice GET /invoices/1 200 invoice 1 of merchant-a ok + alice GET /invoices/4 200 invoice 4 of merchant-b <- LEAK, want 404 + alice GET /invoices/5 200 invoice 5 of merchant-b <- LEAK, want 404 + alice GET /invoices/6 200 invoice 6 of merchant-b <- LEAK, want 404 + alice GET /invoices/999 (does not exist) 404 nothing ok + alice PUT /invoices/5 {amountCents: 1} 200 CHANGED invoice 5 of merchant-b <- LEAK, want 404 + alice DELETE /invoices/6 204 DELETED invoice 6 of merchant-b <- LEAK, want 404 + +TENANT FROM THE REQUEST: who decides which merchant you are? + alice GET /invoices?merchantId=merchant-b 200 2 invoices of merchant-b <- LEAK, want only merchant-a + alice POST /invoices {merchantId:merchant-b,status:PAID} 201 new invoice 7, merchant-b, PAID <- LEAK, want merchant-a + alice POST /invoices {id: 4} 201 invoice 4 moved to merchant-a <- LEAK, want a new invoice + +ROLES: may you call this endpoint at all? + bob GET /admin/invoices (bob is a USER) 200 6 invoices of merchant-a, merchant-b <- LEAK, want 403 + admin GET /admin/invoices (admin is an ADMIN) 200 6 invoices of merchant-a, merchant-b ok + +RESULT: DATA LEAK. alice (merchant-a) read 3 invoices of merchant-b: [4, 5, 6]. +RESULT: DATA CHANGED. alice (merchant-a) changed 1, deleted 1 and took over 1 of merchant-b's invoices, and created 1 in merchant-b's name. +RESULT: MASS ASSIGNMENT. A new invoice took its status from the request body: PAID. +RESULT: NO ROLE CHECK. bob (USER) read the admin list: 6 invoices of every merchant. +RESULT: BAD TOKENS ACCEPTED. 2 of 5 tokens that must be refused got in: expired an hour ago, no merchant_id claim. +``` + +(Each section prints its own table header. They are left out here after the first.) + +### What just happened + +Read the first two sections. **Authentication works.** No token: 401. A wrong password: no token. +A token whose payload alice edited to say `merchant-b`: 401, because the signature no longer +matches. A token with no signature at all, or signed with somebody else's key: 401. Spring Security +checked every token before any controller ran. (Two broken tokens got in anyway. That is Task 6.) + +Then read the third section. alice has a perfectly valid token for merchant-a. She changes the +number in the URL and gets merchant-b's invoices 4, 5 and 6. She changes invoice 5 to 0.01, and she +deletes invoice 6. Nobody stopped her, because nobody asked the question. + +| | The question | Who answers it here | +|---|---|---| +| **Authentication** | Who are you? | Spring Security, from the token, on every request | +| **Authorisation** | Are you allowed to do *this*, to *this* record? | Nobody | + +The token proves that the request comes from alice of merchant-a. It says nothing about invoice 4. +This bug has a name: **IDOR**, Insecure Direct Object Reference. OWASP calls it **Broken Object +Level Authorization** and puts it first in its API Security Top 10. + +### See the SQL + +`./demo --sql`: + +``` + SQL: select ... from invoice i1_0 where i1_0.id=? + alice GET /invoices/4 200 invoice 4 of merchant-b <- LEAK, want 404 +``` + +`where id = ?`, and nothing else. The database was asked for invoice 4, so it returned invoice 4. + +### Find it in the code + +`InvoiceController.get` never even looks at the token, and `InvoiceService.get` loads by id alone: + +```java +public InvoiceResponse get(@PathVariable long id) { // InvoiceController +return invoices.findById(id).orElseThrow(() -> new InvoiceNotFoundException(id)); // InvoiceService +``` + +`update` and `delete` call `get`, so they have the same hole. + +### Look at the damage + +```bash +./inspect +``` + +The end of the output lists every invoice that exists and what alice's token gets for each: + +``` + id merchant_id number customer amount status updated_by GET /invoices/{id} + 1 merchant-a A-1001 Hill Road Florist 120.00 ISSUED alice 200 visible + 2 merchant-a A-1002 Garden Cafe 75.50 PAID alice 200 visible + 3 merchant-a A-1003 Bike Repair Shop 310.00 DRAFT alice 200 visible + 4 merchant-a X-2 Created by alice 5.00 DRAFT alice 200 visible + 5 merchant-b B-2002 Changed by alice 0.01 PAID alice 200 visible <- NOT this token's merchant + 7 merchant-b X-1 Created by alice 5.00 PAID alice 200 visible <- NOT this token's merchant + + This token can read 6 of the 6 invoices that exist: 4 of merchant-a, 2 of merchant-b. +``` + +Invoice 6 is gone. Invoice 5 says `updated_by alice` on a merchant-b invoice. Invoice 7 is a +merchant-b invoice that alice created, already `PAID`. And invoice 4, once bob's gym invoice, is now +alice's. The support call from the story, reproduced. + +### Check + +```bash +./check 1 +``` + +6 of 6 pass: no token, garbage, another key, `alg: none`, an edited payload, a wrong password. +They pass on purpose. They prove the point of this task: every one of them is green, and the API +leaks anyway. + +--- + +## Task 2: Fix the IDOR + +**The idea:** the merchant id is in the token, and the signature guarantees nobody changed it. Put +it into every query. Then another merchant's invoice is not "forbidden". It is simply not found. + +### Before + +`./check 2`: 2 of 6 pass (the two that touch alice's own invoices). + +### Step 1: a scoped query + +In `InvoiceRepository`: + +```java +Optional findByIdAndMerchantId(long id, String merchantId); +``` + +(Import `java.util.Optional`.) Spring Data reads the name and writes +`where id = ? and merchant_id = ?`. + +### Step 2: use it for every single-invoice operation + +In `InvoiceService`, replace `get`, `update` and `delete`: + +```java +@Transactional(readOnly = true) +public Invoice get(long id, Caller caller) { + return find(id, caller); +} + +public Invoice update(long id, UpdateInvoiceRequest change, Caller caller) { + Invoice invoice = find(id, caller); + invoice.change(change.customer(), change.amountCents(), caller.username()); + return invoice; +} + +public void delete(long id, Caller caller) { + invoices.delete(find(id, caller)); +} + +/** Another merchant's invoice is "not found", exactly like an id that does not exist. */ +private Invoice find(long id, Caller caller) { + return invoices.findByIdAndMerchantId(id, caller.merchantId()) + .orElseThrow(() -> new InvoiceNotFoundException(id)); +} +``` + +### Step 3: pass the caller in + +In `InvoiceController`, `get` and `delete` now need the token: + +```java +@GetMapping("/{id}") +public InvoiceResponse get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.get(id, Caller.of(jwt))); +} + +@DeleteMapping("/{id}") +@ResponseStatus(HttpStatus.NO_CONTENT) +public void delete(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) { + invoices.delete(id, Caller.of(jwt)); +} +``` + +`@AuthenticationPrincipal Jwt` is the token Spring Security already checked. `Caller.of(jwt)` reads +`sub` and `merchant_id` from it. + +### After + +`./check 2`: 6 of 6 pass. `./demo`: + +``` +OBJECT-LEVEL AUTHORISATION: is this invoice yours? + alice GET /invoices/1 200 invoice 1 of merchant-a ok + alice GET /invoices/4 404 nothing ok + alice GET /invoices/5 404 nothing ok + alice GET /invoices/6 404 nothing ok + alice GET /invoices/999 (does not exist) 404 nothing ok + alice PUT /invoices/5 {amountCents: 1} 404 nothing changed ok + alice DELETE /invoices/6 404 nothing deleted ok +``` + +### Step 4: make the wrong query impossible + +The fix works today. Next month somebody adds `GET /invoices/{id}/pdf` and types +`invoices.findById(id)`, because `JpaRepository` offers it. Take it away. Change the repository to +extend `Repository`, which has no methods at all, and declare only what the service needs: + +```java +import org.springframework.data.repository.Repository; // instead of ...jpa.repository.JpaRepository + +public interface InvoiceRepository extends Repository { + + // the three query methods stay as they are, then add: + Invoice save(Invoice invoice); + + void delete(Invoice invoice); +} +``` + +Spring Data implements `save` and `delete` exactly as before. `findById`, `findAll` and +`deleteById` no longer exist, so the compiler stops the next developer, not a code review. Run +`./check 2` again: still 6 of 6. + +> **Why not `findById` and then an `if`?** `if (!invoice.getMerchantId().equals(caller.merchantId())) +> throw ...` works for one endpoint. It has to be repeated in every method, it does not work for +> lists or counts, and the one place it is forgotten is the IDOR. A `WHERE` clause cannot be +> forgotten once the unscoped query is gone. + +--- + +## Task 3: Inspect the Object-Level Fix + +### Step 1: the SQL + +`./demo --sql`: + +``` + SQL: select ... from invoice i1_0 where i1_0.id=? and i1_0.merchant_id=? + alice GET /invoices/4 404 nothing ok +``` + +`and merchant_id = ?`. Spring Data wrote it from the method name, and the value is alice's +`merchant_id` claim. The database never sends merchant-b's row to the application at all. + +### Step 2: 404, not 403 + +`./demo --bodies`: + +``` + alice GET /invoices/4 404 nothing ok + body: {"detail":"Invoice 4 not found","instance":"/invoices/4","status":404,"title":"Invoice not found"} + alice GET /invoices/999 (does not exist) 404 nothing ok + body: {"detail":"Invoice 999 not found","instance":"/invoices/999","status":404,"title":"Invoice not found"} +``` + +Apart from the number, the same answer. Suppose invoice 4 got a 403 instead: + +- alice could try ids 1 to 100,000 and learn which exist: 403 means "real, someone else's", 404 + means "no such invoice". With sequential ids she learns how many invoices the other merchants + write, and how fast. +- "It exists but you may not see it" is already information. For a tenant's data the right amount + of information is none. +- It falls out of the design: the scoped query does not find the row, so the code throws the same + `InvoiceNotFoundException` it always throws. There is no second path to get wrong. + +403 is the right answer when the caller is allowed to know the resource exists: bob opens a +document that alice shared with him read-only and tries to edit it. Task 5 has the other 403: +"this endpoint is not for you". + +### Step 3: what each token can see + +```bash +./inspect --user bob +``` + +``` + id merchant_id number customer amount status updated_by GET /invoices/{id} + 1 merchant-a A-1001 Hill Road Florist 120.00 ISSUED alice 404 + ... + 4 merchant-a X-2 Created by alice 5.00 DRAFT alice 404 + 5 merchant-b B-2002 Book Corner 45.00 PAID bob 200 visible + 6 merchant-b B-2003 Town Dental Clinic 1200.00 ISSUED bob 200 visible + 7 merchant-b X-1 Created by alice 5.00 PAID alice 200 visible + + This token can read 3 of the 7 invoices that exist: 3 of merchant-b. +``` + +bob sees only merchant-b's rows, and alice (try `./inspect`) only merchant-a's. But look at invoice +4: it is merchant-a's now, and bob has lost it. Invoice 7 is in bob's list and alice created it. +Those came through `POST /invoices`, which Task 2 did not touch. + +### Step 4: the leak that is left + +``` +RESULT: DATA LEAK. alice (merchant-a) read 3 invoices of merchant-b: [4, 5, 6]. +RESULT: DATA CHANGED. alice (merchant-a) took over 1 of merchant-b's invoices, and created 1 in merchant-b's name. +``` + +Every `GET /invoices/{id}` row is `ok`, and alice still read three merchant-b invoices. Find the row +in the TENANT section: `GET /invoices?merchantId=merchant-b`. The list endpoint asks the client +which merchant it is. That is Task 4. + +### What to take away + +- The authorisation is a `WHERE` clause, with the tenant from the token. +- Another tenant's record is a 404, the same as a missing one: nothing to enumerate. +- A repository that cannot express the unscoped query protects the code you have not written yet. + +--- + +## Task 4: Fix the Merchant That Comes From the Request + +**The idea:** the token is the only place the server learns who the caller is. Anything in the URL, +the query string or the body was typed by the client, and the client is alice. + +### Before + +`./check 4`: 1 of 6. Two holes in `InvoiceController`: + +```java +public List list(@RequestParam(required = false) String merchantId, @AuthenticationPrincipal Jwt jwt) { + String merchant = merchantId != null ? merchantId : Caller.of(jwt).merchantId(); +``` + +```java +public InvoiceResponse create(@RequestBody Invoice invoice, @AuthenticationPrincipal Jwt jwt) { +``` + +The first trusts a query parameter. The second reads the JSON body straight into the JPA entity, so +every field the client sends lands in the database: `merchantId`, `status`, even `id`. That is +**mass assignment**. Look at what `{"id": 4, ...}` did in Task 1, with `./demo --sql`: + +``` + SQL: select ... from invoice i1_0 where i1_0.id=? + SQL: update invoice set amount_cents=?,customer=?,merchant_id=?,number=?,status=?,updated_by=? where id=? + alice POST /invoices {id: 4} 201 invoice 4 moved to merchant-a <- LEAK, want a new invoice +``` + +A `POST` that was meant to insert ran an `update`. Spring Data's `save` asks "is this entity new?". +With an id already set, the answer is no, so it calls `merge`: Hibernate loads row 4 and overwrites +it with alice's data, including her merchant. One request, and someone else's invoice is hers. + +### Step 1: the list asks the token + +```java +// InvoiceController +@GetMapping +public List list(@AuthenticationPrincipal Jwt jwt) { + return invoices.list(Caller.of(jwt)).stream().map(InvoiceResponse::from).toList(); +} + +// InvoiceService +@Transactional(readOnly = true) +public List list(Caller caller) { + return invoices.findByMerchantIdOrderById(caller.merchantId()); +} +``` + +Remove the `RequestParam` import. A client that still sends `?merchantId=merchant-b` gets its own +invoices: Spring ignores query parameters nobody declared. The support team gets their own endpoint +in Task 5, behind a role. + +### Step 2: a request type with only what the client may choose + +New file `invoice/CreateInvoiceRequest.java`: + +```java +package com.amigoscode.authz.invoice; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; + +/** POST /invoices: only what the client may choose. No id, no merchantId, no status. */ +public record CreateInvoiceRequest(@NotBlank String number, @NotBlank String customer, @Positive long amountCents) { +} +``` + +In `InvoiceController`: + +```java +@PostMapping +@ResponseStatus(HttpStatus.CREATED) +public InvoiceResponse create(@Valid @RequestBody CreateInvoiceRequest request, @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.create(request, Caller.of(jwt))); +} +``` + +### Step 3: the server sets the rest + +In `InvoiceService`, replace `create`: + +```java +public Invoice create(CreateInvoiceRequest request, Caller caller) { + return invoices.save(new Invoice(caller.merchantId(), request.number(), request.customer(), + request.amountCents(), InvoiceStatus.DRAFT, caller.username())); +} +``` + +The merchant comes from the token, the status is always `DRAFT`, and the id is `null`, so `save` +inserts. + +### Step 4: remove the setters + +`Invoice.setMerchantId`, `setStatus` and `setUpdatedBy` are now unused. Delete them. An invoice that +cannot change its merchant cannot be moved to another one by any future code either. + +### After + +`./check 4`: 6 of 6 pass. The 400 for a missing customer comes from `@Valid`: before, the request +reached the database and the `not null` constraint turned it into a 500. + +### Inspect + +```bash +./demo --bodies +``` + +``` + alice POST /invoices {merchantId:merchant-b,status:PAID} 201 new invoice 7, merchant-a, DRAFT ok + body: {"id":7,"merchantId":"merchant-a","number":"X-1","customer":"Created by alice","amountCents":500,"status":"DRAFT","updatedBy":"alice"} + alice POST /invoices {id: 4} 201 new invoice 8, merchant-a, DRAFT ok + body: {"id":8,"merchantId":"merchant-a","number":"X-2","customer":"Created by alice","amountCents":500,"status":"DRAFT","updatedBy":"alice"} +``` + +`merchantId`, `status` and `id` from the request are gone without an error. `CreateInvoiceRequest` +has no component for them, and Spring Boot configures Jackson not to fail on unknown properties, so +they are dropped. (If you would rather tell the client, set +`spring.jackson.deserialization.fail-on-unknown-properties=true` and those requests become 400s.) + +`./demo --sql` for the `{id: 4}` row is now a plain `insert into invoice ...`. The `RESULT` lines +about data are gone. Two are left: the admin endpoint and the tokens. + +--- + +## Task 5: Fix the Admin Endpoint + +**The idea:** some endpoints are not about one record but about who you are: only staff may list +every merchant's invoices. That is **function-level** authorisation, and the usual tool is a role. + +### Step 1: the annotation + +In `AdminController`, put `@PreAuthorize("hasRole('ADMIN')")` on `allInvoices()`, under +`@GetMapping` (import `org.springframework.security.access.prepost.PreAuthorize`). Now run +`./demo` before anything else: + +``` +ROLES: may you call this endpoint at all? + bob GET /admin/invoices (bob is a USER) 200 8 invoices of merchant-a, merchant-b <- LEAK, want 403 + admin GET /admin/invoices (admin is an ADMIN) 200 8 invoices of merchant-a, merchant-b ok +``` + +**Surprise one: nothing changed.** `@PreAuthorize` is only an annotation. Something has to read +it, and that something is method security, which is off until you switch it on. No warning, no +error: the annotation is simply ignored. + +### Step 2: switch method security on + +Put `@EnableMethodSecurity` on `SecurityConfig`, next to `@Configuration` (import +`org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity`). +`./demo`: + +``` + bob GET /admin/invoices (bob is a USER) 403 nothing ok + admin GET /admin/invoices (admin is an ADMIN) 403 nothing <- LOCKED OUT, want 200 + +RESULT: ADMIN LOCKED OUT. admin has the ADMIN role and got 403 from /admin/invoices. +``` + +**Surprise two: now the admin is locked out too.** Ask Spring Security what it thinks admin is: + +```bash +./inspect --user admin +``` + +``` + {"iss":"https://login.example.com","sub":"admin","merchant_id":"platform","exp":...,"iat":...,"roles":["USER","ADMIN"]} + ... + JwtDecoder: ACCEPTED. Requests with this token are authenticated. + Authorities: [FACTOR_BEARER] <- what hasRole(...) and hasAuthority(...) look at +``` + +The token says `"roles": ["USER","ADMIN"]`. Spring Security turned that into no role at all. + +- `hasRole('ADMIN')` checks for one exact authority: the string `ROLE_ADMIN`. +- Authorities come from a `JwtAuthenticationConverter`. By default it reads the claim `scope` (or + `scp`), splits it on spaces and prefixes every value with `SCOPE_`. A token with + `"scope": "invoices:read invoices:write"` becomes `SCOPE_invoices:read` and + `SCOPE_invoices:write`. A claim called `roles` is not read at all. +- `FACTOR_BEARER` is new in Spring Security 7. It records *how* the caller authenticated (with a + bearer token), for rules that require more than one factor. It is not a role. + +So the rule was right and the data it looks at was empty. The two classic mistakes here are +`hasRole('ADMIN')` against `SCOPE_` authorities, and a token that already says `ROLE_ADMIN` getting +another prefix: `ROLE_ROLE_ADMIN`. + +### Step 3: read the roles claim + +In `SecurityConfig`, replace the converter bean: + +```java +@Bean +public JwtAuthenticationConverter jwtAuthenticationConverter() { + JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter(); + roles.setAuthoritiesClaimName("roles"); // read "roles", not the default "scope" / "scp" + roles.setAuthorityPrefix("ROLE_"); // ADMIN -> ROLE_ADMIN, which is what hasRole('ADMIN') checks + JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); + converter.setJwtGrantedAuthoritiesConverter(roles); + return converter; +} +``` + +(Import `org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter`.) +The filter chain already passes this bean to `.jwt(jwt -> jwt.jwtAuthenticationConverter(...))`. + +### After + +``` + bob GET /admin/invoices (bob is a USER) 403 nothing ok + admin GET /admin/invoices (admin is an ADMIN) 200 8 invoices of merchant-a, merchant-b ok +``` + +`./inspect --user admin` now says +`Authorities: [ROLE_USER, ROLE_ADMIN, FACTOR_BEARER]` (the order can differ). + +`./check 5`: 5 of 5 pass. + +### Inspect: the 403 on the wire + +`./demo --bodies`: + +``` + bob GET /admin/invoices (bob is a USER) 403 nothing ok + body: {"detail":"Your token is valid, but it does not allow this request.","instance":"/admin/invoices","status":403,"title":"Not allowed"} + WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1" +``` + +A 401 says `error="invalid_token"`, a 403 says `error="insufficient_scope"`: RFC 6750, written by +Spring's `BearerTokenAccessDeniedHandler`. `security/SecurityProblems.java` lets Spring write the +status and the header, and only adds the JSON body. + +> **A trap worth knowing.** The 403 from `@PreAuthorize` is an `AccessDeniedException` thrown inside +> the controller call. It has to travel back up to Spring Security's filter to become a 403. Add a +> catch-all `@ExceptionHandler(Exception.class)` to `ApiExceptionHandler` and try it: bob gets +> `500 Internal Server Error` instead. That is why `ApiExceptionHandler` has no catch-all. + +**`@PreAuthorize` or the filter chain?** `.requestMatchers("/admin/**").hasRole("ADMIN")` before +`anyRequest()` in `SecurityConfig` passes Task 5 too, without method security (we tried), and +covers a whole URL space. `@PreAuthorize` sits on the method and can look at its arguments. Neither +can answer "is invoice 4 alice's?": that needs the row, which is why Task 2 put it in the query. + +### Two ways to test security + +Most tests here send **real tokens over real HTTP** (`support/Api.java`, `support/Tokens.java`): +login tokens, expired ones, unsigned ones. That is the only way to test the `JwtDecoder`. +`AdminRoleIT.mockMvcJwtWithOnlyRoleUserIsForbidden` uses spring-security-test's `jwt()` instead: + +```java +mvc.perform(get("/admin/invoices").with(jwt() + .jwt(token -> token.subject("bob").claim("merchant_id", "merchant-b").claim("roles", List.of("USER"))) + .authorities(new SimpleGrantedAuthority("ROLE_USER")))) + .andExpect(status().isForbidden()); +``` + +No token is made and no signature is checked: `jwt()` puts a finished authentication in place, and +you choose its authorities yourself. It is fast and good for "who may call what". It cannot catch a +decoder that accepts expired tokens, and it does not use your `JwtAuthenticationConverter` either, +which is why `RolesConverterTest` tests the converter on its own. + +--- + +## Task 6: Fix Token Validation + +**The idea:** a correct signature only proves who made the token. It does not prove the token is +still valid, or that it carries what the code relies on. + +### Before + +`./inspect --expired`: + +``` + exp 2026-11-27T13:44:32Z (1795787072) expires at: EXPIRED 1 h 0 min ago + ... + MATCHES. This server made this token, and nobody changed it since. + ... + JwtDecoder: ACCEPTED. Requests with this token are authenticated. + ... + This token can read 5 of the 8 invoices that exist: 5 of merchant-a. +``` + +Expired an hour ago, accepted. `./check 6`: 1 of 5 (only the issuer check passes). + +### Find it in the code + +```java +// Only accept tokens that we issued ourselves. +decoder.setJwtValidator(new JwtIssuerValidator(properties.issuer())); +``` + +It looks like it *adds* an issuer check. It **replaces** the validators. Out of the box a +`NimbusJwtDecoder` validates `exp` and `nbf`. `setJwtValidator` throws that away and keeps only +what you pass in: the issuer. Nothing checks the time any more. And nothing ever checked that +`merchant_id` is present: before the fix such a token got `200` and an empty list, a quiet bug that +looks like "this merchant has no invoices". + +### The fix + +Replace the `setJwtValidator` line: + +```java +// setJwtValidator REPLACES the defaults, so put them back: exp, nbf and iss. +decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>( + JwtValidators.createDefaultWithIssuer(properties.issuer()), + required(JwtClaimNames.SUB), + required("merchant_id"))); +``` + +and add the helper to `SecurityConfig`: + +```java +private static OAuth2TokenValidator required(String claim) { + return new JwtClaimValidator(claim, value -> value instanceof String text && !text.isBlank()); +} +``` + +Imports: `org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator`, +`org.springframework.security.oauth2.core.OAuth2TokenValidator`, and from +`org.springframework.security.oauth2.jwt`: `Jwt`, `JwtClaimNames`, `JwtClaimValidator`, +`JwtValidators`. The `JwtIssuerValidator` import is no longer needed. + +### After + +`./inspect --expired`: + +``` + JwtDecoder: REFUSED. Every request with this token gets a 401. + Reason: An error occurred while attempting to decode the Jwt: Jwt expired at 2026-11-27T13:45:03Z +``` + +`./demo --bodies`, the broken-token section: + +``` + alice GET /invoices (expired an hour ago) 401 nothing ok + body: {"detail":"An error occurred while attempting to decode the Jwt: Jwt expired at 2026-11-27T13:45:12Z","instance":"/invoices","status":401,"title":"Not authenticated"} + alice GET /invoices (no merchant_id claim) 401 nothing ok + body: {"detail":"An error occurred while attempting to decode the Jwt: The merchant_id claim is not valid","instance":"/invoices","status":401,"title":"Not authenticated"} +``` + +`./check 6` is 5 of 5, `./check` prints 31 passes, and `./demo` ends with: + +``` +RESULT: OK. Bad tokens got 401, bob got 403 on /admin, other merchants' invoices got 404. Nobody saw or changed data that was not theirs. +``` + +### Inspect: three details + +- **Clock skew.** The timestamp validator allows 60 seconds by default, because the clocks of the + server that issued a token and the server that checks it are never exactly equal. A token that + expired 30 seconds ago is still accepted; one that expired 90 seconds ago is refused (we checked + both). Pass a `JwtTimestampValidator` with your own `Duration` to change it. +- **The algorithm is the server's choice.** `.macAlgorithm(MacAlgorithm.HS256)` pins it. A token + that says `"alg":"HS512"` is refused with `Another algorithm expected`, and `"alg":"none"` with + `Unsupported algorithm of none`. Never let the header pick the algorithm. +- **The tests do not wait.** `TokenValidationIT` writes `exp` an hour in the past and `nbf` an hour + in the future. A test that sleeps until a token expires is slow and flaky. + +--- + +## Task 7: Inspect a JWT + +### Step 1: take one apart + +```bash +./inspect +``` + +``` +TOKEN (POST /login as alice) + eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUuY29tIiwic3ViIjoiYWxpY2UiLCJtZXJjaGFudF9pZCI6Im1lcmNoYW50LWEiLCJleHAiOjE3OTU3OTEwMDIsImlhdCI6MTc5NTc5MDEwMiwicm9sZXMiOlsiVVNFUiJdfQ.j_VHlHymaoq-qwY8HBaERKOrLMN3J-apPdHU4gk2aaA + +HEADER (part 1, base64url-decoded: no key needed, anyone can do this) + {"typ":"JWT","alg":"HS256"} + +PAYLOAD (part 2, base64url-decoded: no key needed, anyone can do this) + {"iss":"https://login.example.com","sub":"alice","merchant_id":"merchant-a","exp":1795791002,"iat":1795790102,"roles":["USER"]} + + claim value meaning + ----------- --------------------------------- ---------------------------------- + iss https://login.example.com issuer: who made the token + ... + exp 2026-11-27T14:50:02Z (1795791002) expires at: in 14 min 59 s + +SIGNATURE (part 3) + HMAC-SHA256 of part 1 + "." + part 2, with the server's key (authz.jwt.secret, not shown): + MATCHES. This server made this token, and nobody changed it since. +``` + +Three parts, separated by dots. Parts 1 and 2 are JSON, base64url-encoded: **encoded, not +encrypted**. Part 3 is an HMAC of the first two, made with the server's key. + +### Step 2: decode it yourself + +Paste the middle part of your token into `jshell`, which comes with the JDK: + +``` +jshell> System.out.println(new String(java.util.Base64.getUrlDecoder().decode("eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUuY29tIiwic3ViIjoiYWxpY2UiLCJtZXJjaGFudF9pZCI6Im1lcmNoYW50LWEiLCJleHAiOjE3OTU3OTEwMDIsImlhdCI6MTc5NTc5MDEwMiwicm9sZXMiOlsiVVNFUiJdfQ"))) +{"iss":"https://login.example.com","sub":"alice","merchant_id":"merchant-a","exp":1795791002,"iat":1795790102,"roles":["USER"]} +``` + +No key, no library. Everyone who holds a token can read it: the user, their browser extensions, +every proxy and log file it passes through. So a JWT must never hold a password, a secret, an API +key, or personal data you would not print in a log (an email address, a date of birth, an IBAN). +Put an id in it and look the rest up. `TokenServiceTest` pins exactly which claims a login token +carries. (If the content really must be hidden, that is JWE, an encrypted JWT, a different thing.) + +### Step 3: edit it + +```bash +./inspect --edit merchant_id=merchant-b +``` + +``` + {"iss":"https://login.example.com","sub":"alice","merchant_id":"merchant-b","exp":1795791020,"iat":1795790120,"roles":["USER"]} + ... + DOES NOT MATCH. Made with another key, or changed after it was signed. + ... + JwtDecoder: REFUSED. Every request with this token gets a 401. + Reason: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature +``` + +Reading is free, changing is not. To make a new valid signature alice needs the key. This is why +Task 2 could trust `merchant_id` from the token and Task 4 could not trust `?merchantId=`. + +### Step 4: no signature at all + +```bash +./inspect --alg-none +``` + +``` +SIGNATURE (part 3) + EMPTY. The header says alg "none": nothing proves who made this token. + + JwtDecoder: REFUSED. Every request with this token gets a 401. + Reason: Unsupported algorithm of none +``` + +`alg: none` is part of the JWT standard, for tokens whose integrity is guaranteed some other way. +Libraries that let the header choose the algorithm have accepted such tokens in the past, and that +is a whole class of real vulnerabilities. Spring's decoder only accepts the algorithm you +configured. + +### Step 5: where the key lives + +```properties +authz.jwt.secret=${JWT_SECRET:dev-only-not-a-secret-do-not-use-outside-your-laptop} +``` + +- The default is in a public repository on purpose: a placeholder, named so nobody mistakes it for a + real key, and never printed by the tools. `JWT_SECRET` overrides it. A real key comes from a secret + store (Vault, AWS Secrets Manager, a Kubernetes secret) through the environment, never from git. + `JwtProperties` refuses anything shorter than 32 bytes: HS256 needs a 256-bit key. +- **HS256 is symmetric**: the same key signs and checks. Every service that can check a token can + also make one. Fine for one application that issues its own tokens, as here. +- In production the tokens come from an **identity provider** (Keycloak, Auth0, Okta, Cognito, Entra + ID). It signs with **RS256** (or ES256) and a **private key** that never leaves it. Your API only + has the **public key**, which it downloads from the provider's **JWKS** endpoint. In Spring Boot + that is one property, `spring.security.oauth2.resourceserver.jwt.issuer-uri`, and no key in your + configuration at all. A stolen API server cannot mint tokens, and the provider can rotate keys: + the `kid` header says which one signed the token. + +### Step 6: what a 401 tells the client + +`./demo --bodies` prints the `WWW-Authenticate` header of every 401: `Bearer error="invalid_token"` +plus the reason, which tells a client to get a new token rather than retry the same one. Spring +Security 7 also adds `resource_metadata="http://localhost:.../.well-known/oauth-protected-resource"` +(RFC 9728), which points clients at a description of this resource server. + +--- + +## Task 8: Compare, and What JWTs Cannot Do + +### Step 1: before and after + +| Request | Before | After | What fixed it | +|---|---|---|---| +| No token, edited token, `alg: none`, wrong key | 401 | 401 | Spring Security, from the start | +| Expired token, no `merchant_id` | 200 | 401 | Task 6: validators | +| alice `GET /invoices/4` (merchant-b) | 200 | 404 | Task 2: scoped query | +| alice `PUT /invoices/5`, `DELETE /invoices/6` | 200, 204 | 404, 404 | Task 2 | +| alice `GET /invoices?merchantId=merchant-b` | merchant-b's invoices | her own | Task 4: tenant from the token | +| alice `POST /invoices` with `merchantId`, `status`, `id` | obeyed | ignored | Task 4: request DTO | +| bob `GET /admin/invoices` | 200 | 403 | Task 5: `@PreAuthorize` + method security | +| admin `GET /admin/invoices` | 200 | 200 | Task 5: roles mapped to `ROLE_` | + +One row was right from the start, and it is the one people mean when they say "we use JWTs". + +### Step 2: logout, and other things a JWT cannot do + +alice leaves the company at 10:00. Her token was issued at 09:58 with a 15-minute lifetime. Until +10:13 it works, on every server, and nothing in this project can stop it: the API checks the +signature and the time, and never asks anyone. That is what "stateless" means, and it cuts both ways. + +- **Short access tokens and refresh tokens.** Access tokens live 5 to 15 minutes. A refresh token + gets new ones and is stored and checked by the identity provider, so revoking it ends the session + within one access-token lifetime. This is the standard answer. +- **A deny-list.** Give every token a `jti` (token id), and on logout put the `jti` in a shared + store until its `exp`. Instant revocation, at the price of a lookup on every request: the database + call a stateless token was meant to avoid. +- **Changed roles.** Demote the admin and the old token still says `"roles": ["USER","ADMIN"]` until + it expires. Same answers: short lifetimes, or look the roles up instead of trusting the token for + them. + +### Step 3: where each check belongs + +| Check | Where | Why there | +|---|---|---| +| Is the token valid? | The `JwtDecoder`, in the filter chain | Before any of your code runs, the same for every endpoint | +| May this caller use this endpoint? | `@PreAuthorize` or `requestMatchers` | It depends on who you are, not on a row | +| May this caller touch this record? | The query: `WHERE merchant_id = ?` | It depends on the row, so it has to be where the row is read | + +Method security cannot do the third job well: it would have to load the row first, then compare, +and every new query is a new chance to forget. The tenant check belongs in the **data access +layer**, and the safest version is one where the unscoped query does not exist. Teams that want a +net below that use Hibernate's `@TenantId` or filters, which add the tenant to every query, or +Postgres **row-level security**, which makes the database itself refuse the rows. + +### How to say it in an interview + +> "Authentication is who you are; authorisation is what you may do. With JWTs, Spring Security's +> resource server does the first: it checks the signature with an algorithm I configured, the +> expiry, the issuer and the claims I rely on, and I make sure `setJwtValidator` adds to the default +> validators instead of replacing them. A failure there is a 401. Authorisation has two levels. For +> endpoints I use roles, with `@PreAuthorize` and `@EnableMethodSecurity`, and a converter that maps +> the token's roles claim to `ROLE_` authorities. That failure is a 403. For records, the most common +> API vulnerability is an IDOR: a valid token and someone else's id in the URL. I prevent it by +> taking the tenant from the token and putting it in every query, `findByIdAndMerchantId`, never +> trusting a tenant id from the URL or the body, and using request DTOs so a client cannot set the +> tenant, the status or the id. Another tenant's record is a 404, the same as a missing one, so ids +> cannot be probed. And I keep tokens short-lived, because a JWT cannot be revoked before it +> expires." + +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/14-authorisation-and-jwt/solution/.mvn/jvm.config b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/solution/check b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/check new file mode 100755 index 0000000..6825bc5 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/check.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/check.cmd new file mode 100644 index 0000000..10a1d17 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/compose.yaml b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/compose.yaml new file mode 100644 index 0000000..a97708b --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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: authorisation-and-jwt +services: + postgres: + image: postgres:17-alpine + container_name: authorisation-and-jwt-postgres + environment: + POSTGRES_DB: invoices + POSTGRES_USER: invoices + POSTGRES_PASSWORD: invoices + ports: + - "5453:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U invoices -d invoices"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/demo b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/demo new file mode 100755 index 0000000..04d69cd --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/demo.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/demo.cmd new file mode 100644 index 0000000..1b20379 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/inspect b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/inspect new file mode 100755 index 0000000..435bce2 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/inspect.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/inspect.cmd new file mode 100644 index 0000000..c44d2d8 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/mvnw b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/solution/mvnw.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/solution/pom.xml b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/pom.xml new file mode 100644 index 0000000..82d0b97 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/pom.xml @@ -0,0 +1,126 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + authorisation-and-jwt + 0.0.1-SNAPSHOT + authorisation-and-jwt + Authentication vs authorisation with JWTs: watch merchant A read merchant B's invoices, then fix it + + + 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-validation + + + + org.springframework.boot + spring-boot-starter-security-oauth2-resource-server + + + 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.springframework.boot + spring-boot-starter-security-oauth2-resource-server-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/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java new file mode 100644 index 0000000..ab42a4d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java @@ -0,0 +1,38 @@ +package com.amigoscode.authz; + +import com.amigoscode.authz.invoice.InvoiceNotFoundException; +import com.amigoscode.authz.login.BadLoginException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +/** + * Errors from the controllers leave the API as RFC 9457 ProblemDetail (application/problem+json). + * Extending ResponseEntityExceptionHandler gives Spring's own exceptions the right status for free: + * a body that cannot be read or fails validation is a 400. + * + *

There is deliberately no catch-all {@code @ExceptionHandler(Exception.class)} here. An + * AccessDeniedException thrown by {@code @PreAuthorize} has to travel up to Spring Security, which + * turns it into a 403. A catch-all would swallow it and answer 500. + * + *

401 and 403 from the security filters never reach this class: see security/SecurityProblems. + */ +@RestControllerAdvice +public class ApiExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(InvoiceNotFoundException.class) + public ProblemDetail notFound(InvoiceNotFoundException e) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); + problem.setTitle("Invoice not found"); + return problem; + } + + @ExceptionHandler(BadLoginException.class) + public ProblemDetail badLogin(BadLoginException e) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED, e.getMessage()); + problem.setTitle("Login failed"); + return problem; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/AuthzApplication.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/AuthzApplication.java new file mode 100644 index 0000000..e8156f4 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/AuthzApplication.java @@ -0,0 +1,22 @@ +package com.amigoscode.authz; + +import java.time.Clock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class AuthzApplication { + + public static void main(String[] args) { + SpringApplication.run(AuthzApplication.class, args); + } + + /** Everything that needs "now" asks this clock, so a test can pin it. */ + @Bean + Clock clock() { + return Clock.systemUTC(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/admin/AdminController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/admin/AdminController.java new file mode 100644 index 0000000..bd75274 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/admin/AdminController.java @@ -0,0 +1,27 @@ +package com.amigoscode.authz.admin; + +import com.amigoscode.authz.invoice.InvoiceResponse; +import com.amigoscode.authz.invoice.InvoiceService; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** For the platform's support staff: every merchant's invoices. */ +@RestController +@RequestMapping("/admin") +public class AdminController { + + private final InvoiceService invoices; + + public AdminController(InvoiceService invoices) { + this.invoices = invoices; + } + + @GetMapping("/invoices") + @PreAuthorize("hasRole('ADMIN')") + public List allInvoices() { + return invoices.listAll().stream().map(InvoiceResponse::from).toList(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/App.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/App.java new file mode 100644 index 0000000..94ad4ea --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/App.java @@ -0,0 +1,172 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.AuthzApplication; +import com.amigoscode.authz.security.JwtProperties; +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.Map; +import java.util.TreeMap; +import javax.sql.DataSource; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * What ./demo and ./inspect share: the real application on a free port, real HTTP requests with a + * real Authorization header, and a look at the database. + */ +final class App implements AutoCloseable { + + /** What came back from one request. {@code json} is an empty object when the body is not JSON. */ + record Reply(int status, String body, JsonNode json, String wwwAuthenticate) { + } + + /** The demo users. All three have the password "password" (see schema.sql). */ + static final String PASSWORD = "password"; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final ConfigurableApplicationContext context; + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + private App(ConfigurableApplicationContext context) { + this.context = context; + this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + } + + /** Starts the application. Returns null, after printing what to do, when Postgres is not reachable. */ + static App start(boolean sql) { + if (!Db.isUp()) { + return null; + } + List args = new ArrayList<>(List.of( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line in the table instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF")); + if (sql) { + args.add("--logging.level.org.hibernate.SQL=DEBUG"); + // The column list of a select is replaced by "...": the WHERE clause is what matters here. + args.add("--logging.pattern.console= SQL: %replace(%msg){'select [^ ]+ from','select ... from'}%n"); + } + SpringApplication app = new SpringApplication(AuthzApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + return new App(app.run(args.toArray(String[]::new))); + } + + /** Puts the six starting invoices back (src/main/resources/reset.sql). */ + void resetData() { + new ResourceDatabasePopulator(new ClassPathResource("reset.sql")).execute(context.getBean(DataSource.class)); + } + + JdbcTemplate jdbc() { + return context.getBean(JdbcTemplate.class); + } + + T bean(Class type) { + return context.getBean(type); + } + + JwtProperties jwtProperties() { + return context.getBean(JwtProperties.class); + } + + /** POST /login with the demo password. Returns the token. */ + String login(String username) { + Reply reply = post("/login", null, "{\"username\":\"" + username + "\",\"password\":\"" + PASSWORD + "\"}"); + if (reply.status() != 200) { + throw new IllegalStateException("POST /login for " + username + " answered " + reply.status() + ": " + reply.body()); + } + return reply.json().path("token").asString(); + } + + Reply get(String path, String token) { + return send(request(path, token).GET()); + } + + Reply post(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json))); + } + + Reply put(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json))); + } + + Reply delete(String path, String token) { + return send(request(path, token).DELETE()); + } + + /** "3 invoices of merchant-a", "invoice 4 of merchant-b", "7 invoices of merchant-a, merchant-b", "no invoices". */ + static String whose(JsonNode json) { + if (json.isArray()) { + if (json.isEmpty()) { + return "no invoices"; + } + Map perMerchant = new TreeMap<>(); + for (JsonNode invoice : json) { + perMerchant.merge(invoice.path("merchantId").asString("?"), 1, Integer::sum); + } + return json.size() + (json.size() == 1 ? " invoice" : " invoices") + " of " + + String.join(", ", perMerchant.keySet()); + } + if (json.has("merchantId")) { + return "invoice " + json.path("id").asLong() + " of " + json.path("merchantId").asString(); + } + return "nothing"; + } + + /** Terminal output stays ASCII: anything else (from a token someone pasted, say) is escaped. */ + static String ascii(String text) { + StringBuilder out = new StringBuilder(text.length()); + text.codePoints().forEach(c -> { + if (c >= 0x20 && c < 0x7f) { + out.append((char) c); + } else { + out.append(String.format("\\u%04x", c)); + } + }); + return out.toString(); + } + + private HttpRequest.Builder request(String path, String token) { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl + path)); + if (token != null) { + builder.header("Authorization", "Bearer " + token); + } + return builder; + } + + private Reply send(HttpRequest.Builder request) { + try { + HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + JsonNode json; + try { + json = response.body().isBlank() ? JSON.createObjectNode() : JSON.readTree(response.body()); + } catch (RuntimeException notJson) { + json = JSON.createObjectNode(); + } + return new Reply(response.statusCode(), response.body(), json, + response.headers().firstValue("WWW-Authenticate").orElse("")); + } catch (Exception e) { + throw new IllegalStateException("Request failed: " + e, e); + } + } + + @Override + public void close() { + context.close(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Db.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Db.java new file mode 100644 index 0000000..2a28238 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.authz.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:5453/invoices"); + static final String USER = env("DB_USER", "invoices"); + static final String PASSWORD = env("DB_PASSWORD", "invoices"); + + 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/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Demo.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Demo.java new file mode 100644 index 0000000..b316746 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Demo.java @@ -0,0 +1,321 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.demo.App.Reply; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import tools.jackson.databind.JsonNode; + +/** + * Starts the real application, logs in as two merchants and an admin, and sends real HTTP requests + * with real tokens: some fair, some an attacker would send. Prints a table of request, status and + * whose data came back, then one RESULT line per problem found. Every run starts from the same six + * invoices. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final String MERCHANT_A = "merchant-a"; + private static final String MERCHANT_B = "merchant-b"; + + private final App app; + private final boolean bodies; + + // What went wrong, for the RESULT lines. + private final Set invoicesOfBReadByAlice = new TreeSet<>(); + private int changedByAlice; + private int deletedByAlice; + private int takenOverByAlice; + private int createdForBByAlice; + private String statusFromTheBody; + private int adminListSeenByBob = -1; + private boolean adminLockedOut; + private final List badTokensLetIn = new ArrayList<>(); + private final List otherProblems = new ArrayList<>(); + + private Demo(App app, boolean bodies) { + this.app = app; + this.bodies = bodies; + } + + public static void main(String[] args) { + boolean sql = false; + boolean bodies = false; + for (String arg : args) { + switch (arg) { + case "--sql" -> sql = true; + case "--bodies" -> bodies = true; + default -> { + if (!arg.equals("--help") && !arg.equals("-h")) { + System.out.println("Unknown option: " + App.ascii(arg)); + System.out.println(); + } + printHelp(); + return; + } + } + } + try (App app = App.start(sql)) { + if (app != null) { + new Demo(app, bodies).run(); + } + } + } + + private void run() { + app.resetData(); + Forge forge = new Forge(app.jwtProperties()); + + System.out.println(); + System.out.println("Invoices 1-3 belong to merchant-a, invoices 4-6 to merchant-b (fresh data on every run)."); + System.out.println("alice works for merchant-a, bob for merchant-b, admin for the platform and has the ADMIN role."); + + section("AUTHENTICATION: who are you?"); + Reply reply = app.get("/invoices", null); + row("-", "GET /invoices (no token)", reply, App.whose(reply.json()), expect(reply, 401, "WRONG")); + reply = app.post("/login", null, "{\"username\":\"alice\",\"password\":\"guess\"}"); + row("alice", "POST /login (wrong password)", reply, "no token", expect(reply, 401, "WRONG")); + String alice = login("alice"); + String bob = login("bob"); + String admin = login("admin"); + reply = app.get("/invoices", alice); + row("alice", "GET /invoices", alice(reply), App.whose(reply.json()), expectOwn(reply, MERCHANT_A)); + reply = app.get("/invoices", bob); + row("bob", "GET /invoices", reply, App.whose(reply.json()), expectOwn(reply, MERCHANT_B)); + + section("BROKEN TOKENS: alice's claims, but every token here must get a 401"); + badToken("merchant_id edited to merchant-b", Forge.withClaimChanged(alice, "merchant_id", MERCHANT_B)); + badToken("alg none, no signature", forge.unsigned(forge.claims("alice", MERCHANT_A, List.of("USER")))); + badToken("signed with another key", forge.signWithAnotherKey(forge.claims("alice", MERCHANT_A, List.of("USER")))); + badToken("expired an hour ago", forge.expired("alice", MERCHANT_A, List.of("USER"))); + badToken("no merchant_id claim", forge.sign(forge.claims("alice", null, List.of("USER")))); + + section("OBJECT-LEVEL AUTHORISATION: is this invoice yours?"); + reply = app.get("/invoices/1", alice); + row("alice", "GET /invoices/1", alice(reply), App.whose(reply.json()), expectOwn(reply, MERCHANT_A)); + for (long id = 4; id <= 6; id++) { + reply = app.get("/invoices/" + id, alice); + row("alice", "GET /invoices/" + id, alice(reply), App.whose(reply.json()), expect(reply, 404, "LEAK")); + } + reply = app.get("/invoices/999", alice); + row("alice", "GET /invoices/999 (does not exist)", reply, App.whose(reply.json()), expect(reply, 404, "WRONG")); + + reply = app.put("/invoices/5", alice, "{\"customer\":\"Changed by alice\",\"amountCents\":1}"); + boolean changed = amountOf(5) == 1; + changedByAlice += changed ? 1 : 0; + row("alice", "PUT /invoices/5 {amountCents: 1}", reply, + changed ? "CHANGED invoice 5 of merchant-b" : "nothing changed", + changed ? "LEAK, want 404" : expect(reply, 404, "WRONG")); + + reply = app.delete("/invoices/6", alice); + boolean deleted = merchantOf(6) == null; + deletedByAlice += deleted ? 1 : 0; + row("alice", "DELETE /invoices/6", reply, + deleted ? "DELETED invoice 6 of merchant-b" : "nothing deleted", + deleted ? "LEAK, want 404" : expect(reply, 404, "WRONG")); + + section("TENANT FROM THE REQUEST: who decides which merchant you are?"); + reply = app.get("/invoices?merchantId=merchant-b", alice); + row("alice", "GET /invoices?merchantId=merchant-b", alice(reply), App.whose(reply.json()), + expectOwn(reply, MERCHANT_A)); + + reply = app.post("/invoices", alice, "{\"merchantId\":\"merchant-b\",\"status\":\"PAID\"," + + "\"number\":\"X-1\",\"customer\":\"Created by alice\",\"amountCents\":500}"); + row("alice", "POST /invoices {merchantId:merchant-b,status:PAID}", reply, created(reply), createdProblem(reply)); + + reply = app.post("/invoices", alice, "{\"id\":4,\"number\":\"X-2\",\"customer\":\"Created by alice\",\"amountCents\":500}"); + boolean takenOver = MERCHANT_A.equals(merchantOf(4)); + takenOverByAlice += takenOver ? 1 : 0; + row("alice", "POST /invoices {id: 4}", reply, + takenOver ? "invoice 4 moved to merchant-a" : created(reply), + takenOver ? "LEAK, want a new invoice" : expect(reply, 201, "WRONG")); + + section("ROLES: may you call this endpoint at all?"); + reply = app.get("/admin/invoices", bob); + if (reply.status() == 200) { + adminListSeenByBob = reply.json().size(); + } + row("bob", "GET /admin/invoices (bob is a USER)", reply, App.whose(reply.json()), expect(reply, 403, "LEAK")); + reply = app.get("/admin/invoices", admin); + adminLockedOut = reply.status() == 403; + row("admin", "GET /admin/invoices (admin is an ADMIN)", reply, App.whose(reply.json()), + adminLockedOut ? "LOCKED OUT, want 200" : expect(reply, 200, "WRONG")); + + printResult(); + } + + private String login(String username) { + String token = app.login(username); + row(username, "POST /login", 200, "a token, " + token.length() + " characters", null, + bodies ? "{\"token\":\"" + token + "\"}" : null); + return token; + } + + private void badToken(String what, String token) { + Reply reply = app.get("/invoices", token); + String problem = expect(reply, 401, "LET IN"); + if (problem != null) { + badTokensLetIn.add(what); + } + row("alice", "GET /invoices (" + what + ")", reply, App.whose(reply.json()), problem); + } + + /** Remembers every invoice of merchant-b that came back to alice. */ + private Reply alice(Reply reply) { + if (reply.status() == 200) { + JsonNode json = reply.json(); + List invoices = new ArrayList<>(); + if (json.isArray()) { + json.forEach(invoices::add); + } else { + invoices.add(json); + } + for (JsonNode invoice : invoices) { + if (MERCHANT_B.equals(invoice.path("merchantId").asString(""))) { + invoicesOfBReadByAlice.add(invoice.path("id").asLong()); + } + } + } + return reply; + } + + private String expect(Reply reply, int status, String label) { + if (reply.status() == status) { + return null; + } + if (reply.status() >= 500) { + otherProblems.add(reply.status() + " from a request that should have been a " + status); + return "SERVER ERROR, want " + status; + } + return label + ", want " + status; + } + + private String expectOwn(Reply reply, String merchant) { + String problem = expect(reply, 200, "WRONG"); + if (problem != null) { + return problem; + } + String whose = App.whose(reply.json()); + return whose.endsWith(" of " + merchant) ? null : "LEAK, want only " + merchant; + } + + private String created(Reply reply) { + if (reply.status() != 201) { + return "nothing"; + } + return "new invoice " + reply.json().path("id").asLong() + ", " + reply.json().path("merchantId").asString() + + ", " + reply.json().path("status").asString(); + } + + private String createdProblem(Reply reply) { + String problem = expect(reply, 201, "WRONG"); + if (problem != null) { + return problem; + } + String merchant = reply.json().path("merchantId").asString(); + String status = reply.json().path("status").asString(); + if (!MERCHANT_A.equals(merchant)) { + createdForBByAlice++; + } + if (!"DRAFT".equals(status)) { + statusFromTheBody = status; + } + if (!MERCHANT_A.equals(merchant)) { + return "LEAK, want merchant-a"; + } + return "DRAFT".equals(status) ? null : "WRONG, want DRAFT"; + } + + private void printResult() { + System.out.println(); + List results = new ArrayList<>(); + if (!invoicesOfBReadByAlice.isEmpty()) { + results.add("DATA LEAK. alice (merchant-a) read " + invoicesOfBReadByAlice.size() + " invoices of merchant-b: " + + invoicesOfBReadByAlice + "."); + } + List done = new ArrayList<>(); + if (changedByAlice > 0) { + done.add("changed " + changedByAlice); + } + if (deletedByAlice > 0) { + done.add("deleted " + deletedByAlice); + } + if (takenOverByAlice > 0) { + done.add("took over " + takenOverByAlice); + } + if (!done.isEmpty() || createdForBByAlice > 0) { + String text = "DATA CHANGED. alice (merchant-a) "; + if (!done.isEmpty()) { + text += String.join(", ", done.subList(0, done.size() - 1)) + (done.size() > 1 ? " and " : "") + + done.getLast() + " of merchant-b's invoices"; + } + if (createdForBByAlice > 0) { + text += (done.isEmpty() ? "" : ", and ") + "created " + createdForBByAlice + " in merchant-b's name"; + } + results.add(text + "."); + } + if (statusFromTheBody != null) { + results.add("MASS ASSIGNMENT. A new invoice took its status from the request body: " + statusFromTheBody + "."); + } + if (adminListSeenByBob >= 0) { + results.add("NO ROLE CHECK. bob (USER) read the admin list: " + adminListSeenByBob + " invoices of every merchant."); + } + if (adminLockedOut) { + results.add("ADMIN LOCKED OUT. admin has the ADMIN role and got 403 from /admin/invoices."); + } + if (!badTokensLetIn.isEmpty()) { + results.add("BAD TOKENS ACCEPTED. " + badTokensLetIn.size() + " of 5 tokens that must be refused got in: " + + String.join(", ", badTokensLetIn) + "."); + } + otherProblems.forEach(problem -> results.add("SERVER ERROR. " + problem + ".")); + if (results.isEmpty()) { + System.out.println("RESULT: OK. Bad tokens got 401, bob got 403 on /admin, other merchants' invoices got 404." + + " Nobody saw or changed data that was not theirs."); + } else { + results.forEach(result -> System.out.println("RESULT: " + result)); + } + System.out.println(); + } + + private void section(String title) { + System.out.println(); + System.out.println(title); + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", "who", "request", "status", "what came back", "verdict"); + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", "-----", "-".repeat(50), "------", "-".repeat(36), "-------"); + } + + private void row(String who, String request, Reply reply, String cameBack, String problem) { + row(who, request, reply.status(), cameBack, problem, bodies ? reply.body() : null); + if (bodies && !reply.wwwAuthenticate().isEmpty()) { + System.out.println(" WWW-Authenticate: " + App.ascii(reply.wwwAuthenticate())); + } + } + + private static void row(String who, String request, int status, String cameBack, String problem, String body) { + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", who, request, status, cameBack, + problem == null ? "ok" : "<- " + problem); + if (body != null && !body.isBlank()) { + String text = App.ascii(body); + System.out.println(" body: " + (text.length() > 300 ? text.substring(0, 300) + "..." : text)); + } + } + + private long amountOf(long id) { + List amounts = app.jdbc().queryForList("select amount_cents from invoice where id = ?", Long.class, id); + return amounts.isEmpty() ? -1 : amounts.getFirst(); + } + + private String merchantOf(long id) { + List merchants = app.jdbc().queryForList("select merchant_id from invoice where id = ?", String.class, id); + return merchants.isEmpty() ? null : merchants.getFirst(); + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --sql print every SQL statement the application sends, above the row it belongs to"); + System.out.println(" --bodies print the response body under every row"); + System.out.println(); + System.out.println("Every run puts the six starting invoices back first. ./inspect shows a token and what it can see."); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Forge.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Forge.java new file mode 100644 index 0000000..0f659bd --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Forge.java @@ -0,0 +1,89 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.security.JwtProperties; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; +import com.nimbusds.jwt.SignedJWT; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * Makes the tokens a real login never hands out, the way an attacker (or a buggy client) would: + * edited after signing, unsigned, signed with another key, expired, missing a claim. Plain Java + * and the Nimbus library that Spring Security already uses: no other tool needed. + */ +final class Forge { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final JwtProperties properties; + + Forge(JwtProperties properties) { + this.properties = properties; + } + + /** The claims a login gives this user, valid from now for 15 minutes. */ + JWTClaimsSet.Builder claims(String username, String merchantId, List roles) { + Instant now = Instant.now(); + return new JWTClaimsSet.Builder() + .issuer(properties.issuer()) + .subject(username) + .issueTime(Date.from(now)) + .expirationTime(Date.from(now.plus(Duration.ofMinutes(15)))) + .claim("merchant_id", merchantId) + .claim("roles", roles); + } + + /** The same claims, but it expired an hour ago. Signed with the real key. */ + String expired(String username, String merchantId, List roles) { + Instant anHourAgo = Instant.now().minus(Duration.ofHours(1)); + return sign(claims(username, merchantId, roles) + .issueTime(Date.from(anHourAgo.minus(Duration.ofMinutes(15)))) + .expirationTime(Date.from(anHourAgo))); + } + + /** HS256 with the server's real key. */ + String sign(JWTClaimsSet.Builder claims) { + return signWith(claims, properties.secret().getBytes(StandardCharsets.UTF_8)); + } + + /** HS256 with a key the server has never seen. */ + String signWithAnotherKey(JWTClaimsSet.Builder claims) { + return signWith(claims, "an-attackers-own-key-the-server-never-saw".getBytes(StandardCharsets.UTF_8)); + } + + /** {"alg":"none"}: header.payload. with an empty signature. */ + String unsigned(JWTClaimsSet.Builder claims) { + return new PlainJWT(claims.build()).serialize(); + } + + /** Changes one claim in the payload of a real token and keeps its old signature. */ + static String withClaimChanged(String token, String claim, String value) { + String[] parts = token.split("\\.", -1); + ObjectNode payload = (ObjectNode) JSON.readTree(Base64.getUrlDecoder().decode(parts[1])); + payload.put(claim, value); + String edited = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(payload)); + return parts[0] + "." + edited + "." + parts[2]; + } + + private static String signWith(JWTClaimsSet.Builder claims, byte[] key) { + try { + SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build(), + claims.build()); + jwt.sign(new MACSigner(key)); + return jwt.serialize(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Inspect.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Inspect.java new file mode 100644 index 0000000..4a5b896 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/demo/Inspect.java @@ -0,0 +1,351 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.demo.App.Reply; +import com.amigoscode.authz.login.UserAccounts; +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.Caller; +import com.nimbusds.jose.JWSObject; +import com.nimbusds.jose.crypto.MACVerifier; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtException; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Takes one token apart: header, claims, expiry, whether the signature matches, what Spring + * Security makes of it, and which invoices it can see compared with which exist. Only sends GET + * requests, so it changes nothing. Run it with ./inspect (or .\inspect on Windows). + */ +public final class Inspect { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final Map MEANING = Map.of( + "iss", "issuer: who made the token", + "sub", "subject: who the token is about", + "merchant_id", "which merchant this user works for", + "roles", "what this user may do", + "iat", "issued at", + "nbf", "not valid before", + "exp", "expires at"); + + private record Options(String user, String token, boolean expired, boolean algNone, String edit) { + } + + public static void main(String[] args) { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(App.ascii(e.getMessage())); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(false)) { + if (app != null) { + run(app, options); + } + } + } + + private static void run(App app, Options options) { + Integer invoices = app.jdbc().queryForObject("select count(*) from invoice", Integer.class); + if (invoices == null || invoices == 0) { + app.resetData(); + System.out.println(); + System.out.println("(The invoice table was empty, so the six starting invoices were loaded.)"); + } + + printUsers(app); + + String token; + String origin; + if (options.token() != null) { + token = options.token().strip(); + origin = "the token given with --token"; + } else { + UserAccount user = app.bean(UserAccounts.class).find(options.user()) + .orElseThrow(() -> new IllegalArgumentException("No user " + options.user())); + Forge forge = new Forge(app.jwtProperties()); + if (options.expired()) { + token = forge.expired(user.username(), user.merchantId(), user.roles()); + origin = user.username() + "'s claims, signed with the real key, expired an hour ago"; + } else if (options.algNone()) { + token = forge.unsigned(forge.claims(user.username(), user.merchantId(), user.roles())); + origin = user.username() + "'s claims with alg none and no signature"; + } else { + token = app.login(user.username()); + origin = "POST /login as " + user.username(); + } + if (options.edit() != null) { + String[] edit = options.edit().split("=", 2); + token = Forge.withClaimChanged(token, edit[0], edit[1]); + origin += ", then " + edit[0] + " edited to " + edit[1] + " (the signature was not redone)"; + } + } + + System.out.println(); + System.out.println("TOKEN (" + App.ascii(origin) + ")"); + System.out.println(" " + App.ascii(token)); + String[] parts = token.split("\\.", -1); + if (parts.length != 3) { + System.out.println(); + System.out.println(" Not a JWT: a JWT is three base64url parts separated by dots, header.payload.signature."); + System.out.println(" This has " + parts.length + " part" + (parts.length == 1 ? "" : "s") + "."); + } + JsonNode payload = null; + if (parts.length == 3) { + System.out.println(); + System.out.println("HEADER (part 1, base64url-decoded: no key needed, anyone can do this)"); + JsonNode header = decode(parts[0]); + System.out.println(" " + (header == null ? "(not base64url JSON)" : App.ascii(header.toString()))); + + System.out.println(); + System.out.println("PAYLOAD (part 2, base64url-decoded: no key needed, anyone can do this)"); + payload = decode(parts[1]); + if (payload == null) { + System.out.println(" (not base64url JSON)"); + } else { + System.out.println(" " + App.ascii(payload.toString())); + System.out.println(); + printClaims(payload); + } + + System.out.println(); + System.out.println("SIGNATURE (part 3)"); + System.out.println(" " + signature(token, parts, app)); + } + + System.out.println(); + System.out.println("WHAT SPRING SECURITY MAKES OF IT (the application's own JwtDecoder and JwtAuthenticationConverter)"); + Jwt jwt = null; + try { + jwt = app.bean(JwtDecoder.class).decode(token); + Caller caller = Caller.of(jwt); + List authorities = app.bean(JwtAuthenticationConverter.class).convert(jwt).getAuthorities().stream() + .map(GrantedAuthority::getAuthority).toList(); + System.out.println(" JwtDecoder: ACCEPTED. Requests with this token are authenticated."); + System.out.println(" Caller: username " + caller.username() + ", merchant " + caller.merchantId()); + System.out.println(" Authorities: " + (authorities.isEmpty() ? "(none)" : authorities) + + " <- what hasRole(...) and hasAuthority(...) look at"); + } catch (JwtException e) { + System.out.println(" JwtDecoder: REFUSED. Every request with this token gets a 401."); + System.out.println(" Reason: " + App.ascii(String.valueOf(e.getMessage()))); + } + + printWhatItCanSee(app, token, payload, jwt != null); + } + + private static void printUsers(App app) { + System.out.println(); + System.out.println("USERS (table app_user. The password is only ever stored as a bcrypt hash, and never put in a token)"); + List rows = new ArrayList<>(); + rows.add(new String[] {"username", "merchant_id", "roles", "password_hash"}); + app.jdbc().query("select username, merchant_id, roles, password_hash from app_user order by username", + (row, n) -> rows.add(new String[] {row.getString(1), row.getString(2), row.getString(3), + row.getString(4).substring(0, Math.min(24, row.getString(4).length())) + "..."})); + printTable(rows); + } + + private static void printClaims(JsonNode payload) { + List rows = new ArrayList<>(); + rows.add(new String[] {"claim", "value", "meaning"}); + for (Map.Entry claim : payload.properties()) { + JsonNode value = claim.getValue(); + String text = value.isString() ? value.asString() : value.toString(); + String meaning = MEANING.getOrDefault(claim.getKey(), ""); + if (value.isNumber() && List.of("iat", "nbf", "exp").contains(claim.getKey())) { + Instant at = Instant.ofEpochSecond(value.asLong()); + text = at + " (" + value.asLong() + ")"; + if (claim.getKey().equals("exp")) { + Duration left = Duration.between(Instant.now(), at); + meaning += left.isNegative() ? ": EXPIRED " + human(left.negated()) + " ago" : ": in " + human(left); + } + if (claim.getKey().equals("nbf") && at.isAfter(Instant.now())) { + meaning += ": NOT VALID YET, in " + human(Duration.between(Instant.now(), at)); + } + } + rows.add(new String[] {App.ascii(claim.getKey()), App.ascii(text), meaning}); + } + if (!payload.has("exp")) { + rows.add(new String[] {"exp", "(missing)", "this token never expires"}); + } + printTable(rows); + } + + private static String signature(String token, String[] parts, App app) { + if (parts[2].isEmpty()) { + JsonNode header = decode(parts[0]); + String alg = header == null ? "?" : header.path("alg").asString("?"); + return "EMPTY. The header says alg \"" + App.ascii(alg) + "\": nothing proves who made this token."; + } + try { + boolean matches = JWSObject.parse(token) + .verify(new MACVerifier(app.jwtProperties().secret().getBytes(StandardCharsets.UTF_8))); + return "HMAC-SHA256 of part 1 + \".\" + part 2, with the server's key (authz.jwt.secret, not shown):\n " + + (matches ? "MATCHES. This server made this token, and nobody changed it since." + : "DOES NOT MATCH. Made with another key, or changed after it was signed."); + } catch (Exception e) { + return "Cannot be checked: " + App.ascii(String.valueOf(e.getMessage())); + } + } + + private static void printWhatItCanSee(App app, String token, JsonNode payload, boolean accepted) { + String merchant = payload == null ? null : payload.path("merchant_id").asString(null); + System.out.println(); + System.out.println("INVOICES: every row that exists, and what GET /invoices/{id} answers with this token"); + List rows = new ArrayList<>(); + rows.add(new String[] {"id", "merchant_id", "number", "customer", "amount", "status", "updated_by", + "GET /invoices/{id}", ""}); + Map visible = new LinkedHashMap<>(); + List> invoices = app.jdbc().queryForList( + "select id, merchant_id, number, customer, amount_cents, status, updated_by from invoice order by id"); + for (Map invoice : invoices) { + long id = ((Number) invoice.get("id")).longValue(); + long cents = ((Number) invoice.get("amount_cents")).longValue(); + String owner = String.valueOf(invoice.get("merchant_id")); + int status = app.get("/invoices/" + id, token).status(); + String note = ""; + if (status == 200) { + visible.merge(owner, 1, Integer::sum); + note = owner.equals(merchant) ? "visible" : "visible <- NOT this token's merchant"; + } + rows.add(new String[] {String.valueOf(id), owner, String.valueOf(invoice.get("number")), + App.ascii(String.valueOf(invoice.get("customer"))), String.format("%d.%02d", cents / 100, cents % 100), + String.valueOf(invoice.get("status")), App.ascii(String.valueOf(invoice.get("updated_by"))), + String.valueOf(status), note}); + } + printTable(rows); + + int seen = visible.values().stream().mapToInt(Integer::intValue).sum(); + System.out.println(); + System.out.println(" This token can read " + seen + " of the " + invoices.size() + " invoices that exist" + + (visible.isEmpty() ? "." : ": " + visible.entrySet().stream() + .map(entry -> entry.getValue() + " of " + entry.getKey()).reduce((a, b) -> a + ", " + b).orElse("") + ".")); + if (!accepted) { + System.out.println(" (Nothing at all: the token was refused, so every request is a 401.)"); + } + + System.out.println(); + System.out.println("THE LIST ENDPOINTS with this token"); + for (String path : List.of("/invoices", "/invoices?merchantId=merchant-b", "/admin/invoices")) { + Reply reply = app.get(path, token); + System.out.printf(" GET %-34s %d %s%n", path, reply.status(), App.whose(reply.json())); + } + System.out.println(); + } + + private static JsonNode decode(String part) { + try { + return JSON.readTree(new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8)); + } catch (RuntimeException e) { + return null; + } + } + + private static String human(Duration duration) { + long seconds = duration.toSeconds(); + if (seconds < 60) { + return seconds + " s"; + } + if (seconds < 3600) { + return (seconds / 60) + " min " + (seconds % 60) + " s"; + } + return (seconds / 3600) + " h " + (seconds % 3600 / 60) + " min"; + } + + /** Prints rows as a plain text table. The first row is the header. */ + private static void printTable(List rows) { + int[] widths = new int[rows.getFirst().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("%-" + Math.max(1, 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 static Options parse(String[] args) { + String user = "alice"; + String token = null; + boolean expired = false; + boolean algNone = false; + String edit = null; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--user" -> user = value(args, ++i, "--user"); + case "--token" -> token = value(args, ++i, "--token"); + case "--expired" -> expired = true; + case "--alg-none" -> algNone = true; + case "--edit" -> { + edit = value(args, ++i, "--edit"); + if (!edit.matches("[a-z_]+=.*")) { + throw new IllegalArgumentException("--edit needs claim=value, for example --edit merchant_id=merchant-b"); + } + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + if (!List.of("alice", "bob", "admin").contains(user)) { + throw new IllegalArgumentException("--user must be alice, bob or admin, got: " + user); + } + if (token != null && (expired || algNone || edit != null)) { + throw new IllegalArgumentException("--token cannot be combined with --expired, --alg-none or --edit"); + } + return new Options(user, token, expired, algNone, edit); + } + + 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 void printHelp() { + System.out.println("Usage: ./inspect [options] (Windows: .\\inspect [options])"); + System.out.println(); + System.out.println(" --user alice (default), bob or admin: logs in and inspects that token"); + System.out.println(" --expired the same claims, signed with the real key, expired an hour ago"); + System.out.println(" --alg-none the same claims with alg none and no signature"); + System.out.println(" --edit = change one claim after signing, for example --edit merchant_id=merchant-b"); + System.out.println(" --token inspect any token, for example one copied from ./demo --bodies"); + System.out.println(); + System.out.println("Only sends GET requests: it changes nothing. ./demo puts the starting data back."); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/CreateInvoiceRequest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/CreateInvoiceRequest.java new file mode 100644 index 0000000..78a5d9b --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/CreateInvoiceRequest.java @@ -0,0 +1,12 @@ +package com.amigoscode.authz.invoice; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; + +/** + * POST /invoices: only what the client is allowed to choose. No id (the database picks it), no + * merchantId (it comes from the token), no status (a new invoice is always a DRAFT). Whatever else + * the client puts in the JSON is ignored, because there is no field for it to land in. + */ +public record CreateInvoiceRequest(@NotBlank String number, @NotBlank String customer, @Positive long amountCents) { +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/Invoice.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/Invoice.java new file mode 100644 index 0000000..c431176 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/Invoice.java @@ -0,0 +1,79 @@ +package com.amigoscode.authz.invoice; + +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; + +/** One invoice. It belongs to exactly one merchant, for ever: there is no way to change merchantId. */ +@Entity +@Table(name = "invoice") +public class Invoice { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String merchantId; + + private String number; + + private String customer; + + private long amountCents; + + @Enumerated(EnumType.STRING) + private InvoiceStatus status; + + private String updatedBy; + + protected Invoice() { + } + + public Invoice(String merchantId, String number, String customer, long amountCents, InvoiceStatus status, + String updatedBy) { + this.merchantId = merchantId; + this.number = number; + this.customer = customer; + this.amountCents = amountCents; + this.status = status; + this.updatedBy = updatedBy; + } + + public void change(String customer, long amountCents, String updatedBy) { + this.customer = customer; + this.amountCents = amountCents; + this.updatedBy = updatedBy; + } + + public Long getId() { + return id; + } + + public String getMerchantId() { + return merchantId; + } + + public String getNumber() { + return number; + } + + public String getCustomer() { + return customer; + } + + public long getAmountCents() { + return amountCents; + } + + public InvoiceStatus getStatus() { + return status; + } + + public String getUpdatedBy() { + return updatedBy; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java new file mode 100644 index 0000000..d0a4e48 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java @@ -0,0 +1,60 @@ +package com.amigoscode.authz.invoice; + +import com.amigoscode.authz.security.Caller; +import jakarta.validation.Valid; +import java.util.List; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.bind.annotation.DeleteMapping; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * The merchant's own invoices. Every request here has already passed authentication: Spring + * Security checked the token before this class runs, and hands it over as {@code @AuthenticationPrincipal Jwt}. + */ +@RestController +@RequestMapping("/invoices") +public class InvoiceController { + + private final InvoiceService invoices; + + public InvoiceController(InvoiceService invoices) { + this.invoices = invoices; + } + + @GetMapping + public List list(@AuthenticationPrincipal Jwt jwt) { + return invoices.list(Caller.of(jwt)).stream().map(InvoiceResponse::from).toList(); + } + + @GetMapping("/{id}") + public InvoiceResponse get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.get(id, Caller.of(jwt))); + } + + @PutMapping("/{id}") + public InvoiceResponse update(@PathVariable long id, @Valid @RequestBody UpdateInvoiceRequest change, + @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.update(id, change, Caller.of(jwt))); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) { + invoices.delete(id, Caller.of(jwt)); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public InvoiceResponse create(@Valid @RequestBody CreateInvoiceRequest request, @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.create(request, Caller.of(jwt))); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java new file mode 100644 index 0000000..1d1406c --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java @@ -0,0 +1,9 @@ +package com.amigoscode.authz.invoice; + +/** A 404. Thrown for an id that does not exist AND for an id that belongs to another merchant. */ +public class InvoiceNotFoundException extends RuntimeException { + + public InvoiceNotFoundException(long id) { + super("Invoice " + id + " not found"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java new file mode 100644 index 0000000..b55d4e6 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java @@ -0,0 +1,24 @@ +package com.amigoscode.authz.invoice; + +import java.util.List; +import java.util.Optional; +import org.springframework.data.repository.Repository; + +/** + * Every read is scoped to one merchant. This extends Repository, not JpaRepository, on purpose: + * JpaRepository would hand everyone findById, findAll and deleteById, which ignore the merchant. + * The only query without a merchant is the admin list, and it says so in its name. + */ +public interface InvoiceRepository extends Repository { + + List findByMerchantIdOrderById(String merchantId); + + Optional findByIdAndMerchantId(long id, String merchantId); + + /** Every merchant's invoices. Only for /admin, which checks the ADMIN role first. */ + List findAllByOrderById(); + + Invoice save(Invoice invoice); + + void delete(Invoice invoice); +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java new file mode 100644 index 0000000..f4f3a71 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java @@ -0,0 +1,11 @@ +package com.amigoscode.authz.invoice; + +/** What the API returns for an invoice. */ +public record InvoiceResponse(long id, String merchantId, String number, String customer, long amountCents, + InvoiceStatus status, String updatedBy) { + + public static InvoiceResponse from(Invoice invoice) { + return new InvoiceResponse(invoice.getId(), invoice.getMerchantId(), invoice.getNumber(), + invoice.getCustomer(), invoice.getAmountCents(), invoice.getStatus(), invoice.getUpdatedBy()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java new file mode 100644 index 0000000..d32a3ea --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java @@ -0,0 +1,62 @@ +package com.amigoscode.authz.invoice; + +import com.amigoscode.authz.security.Caller; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Every method takes the Caller, and every query includes the caller's merchant id. That is the + * object-level authorisation of this API: not a check that someone might forget, but a WHERE + * clause that is always there. + */ +@Service +@Transactional +public class InvoiceService { + + private final InvoiceRepository invoices; + + public InvoiceService(InvoiceRepository invoices) { + this.invoices = invoices; + } + + @Transactional(readOnly = true) + public List list(Caller caller) { + return invoices.findByMerchantIdOrderById(caller.merchantId()); + } + + @Transactional(readOnly = true) + public Invoice get(long id, Caller caller) { + return find(id, caller); + } + + public Invoice update(long id, UpdateInvoiceRequest change, Caller caller) { + Invoice invoice = find(id, caller); + invoice.change(change.customer(), change.amountCents(), caller.username()); + return invoice; + } + + public void delete(long id, Caller caller) { + invoices.delete(find(id, caller)); + } + + public Invoice create(CreateInvoiceRequest request, Caller caller) { + return invoices.save(new Invoice(caller.merchantId(), request.number(), request.customer(), + request.amountCents(), InvoiceStatus.DRAFT, caller.username())); + } + + /** Every merchant. Only called from AdminController, which requires ROLE_ADMIN. */ + @Transactional(readOnly = true) + public List listAll() { + return invoices.findAllByOrderById(); + } + + /** + * Another merchant's invoice is "not found", exactly like an id that does not exist. A 403 + * would tell the caller "this id exists, it just is not yours". + */ + private Invoice find(long id, Caller caller) { + return invoices.findByIdAndMerchantId(id, caller.merchantId()) + .orElseThrow(() -> new InvoiceNotFoundException(id)); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java new file mode 100644 index 0000000..672e058 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java @@ -0,0 +1,5 @@ +package com.amigoscode.authz.invoice; + +public enum InvoiceStatus { + DRAFT, ISSUED, PAID +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java new file mode 100644 index 0000000..a28175f --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java @@ -0,0 +1,8 @@ +package com.amigoscode.authz.invoice; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; + +/** PUT /invoices/{id}: the two fields a merchant may change. */ +public record UpdateInvoiceRequest(@NotBlank String customer, @Positive long amountCents) { +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/BadLoginException.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/BadLoginException.java new file mode 100644 index 0000000..a72298a --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/BadLoginException.java @@ -0,0 +1,8 @@ +package com.amigoscode.authz.login; + +public class BadLoginException extends RuntimeException { + + public BadLoginException() { + super("Wrong username or password"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/LoginController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/LoginController.java new file mode 100644 index 0000000..ac0637f --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/LoginController.java @@ -0,0 +1,45 @@ +package com.amigoscode.authz.login; + +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.TokenService; +import com.amigoscode.authz.security.TokenService.IssuedToken; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import java.time.Instant; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * POST /login {"username":"alice","password":"password"} returns a token. The only endpoint that + * needs no token. In a real system this is the identity provider's login page, not your API. + */ +@RestController +public class LoginController { + + public record LoginRequest(@NotBlank String username, @NotBlank String password) { + } + + public record LoginResponse(String token, String tokenType, Instant expiresAt) { + } + + private final UserAccounts users; + private final PasswordEncoder passwordEncoder; + private final TokenService tokens; + + public LoginController(UserAccounts users, PasswordEncoder passwordEncoder, TokenService tokens) { + this.users = users; + this.passwordEncoder = passwordEncoder; + this.tokens = tokens; + } + + @PostMapping("/login") + public LoginResponse login(@Valid @RequestBody LoginRequest request) { + UserAccount user = users.find(request.username()) + .filter(account -> passwordEncoder.matches(request.password(), account.passwordHash())) + .orElseThrow(BadLoginException::new); + IssuedToken token = tokens.issue(user.username(), user.merchantId(), user.roles()); + return new LoginResponse(token.value(), "Bearer", token.expiresAt()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/UserAccounts.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/UserAccounts.java new file mode 100644 index 0000000..3307a15 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/login/UserAccounts.java @@ -0,0 +1,29 @@ +package com.amigoscode.authz.login; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +/** The app_user table: username, bcrypt hash, merchant, roles. */ +@Repository +public class UserAccounts { + + public record UserAccount(String username, String passwordHash, String merchantId, List roles) { + } + + private final JdbcTemplate jdbc; + + public UserAccounts(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public Optional find(String username) { + return jdbc.query("select username, password_hash, merchant_id, roles from app_user where username = ?", + (row, n) -> new UserAccount(row.getString(1), row.getString(2), row.getString(3), + Arrays.stream(row.getString(4).split(",")).map(String::strip).toList()), + username) + .stream().findFirst(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/Caller.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/Caller.java new file mode 100644 index 0000000..c873388 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/Caller.java @@ -0,0 +1,15 @@ +package com.amigoscode.authz.security; + +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * Who is calling, taken from the token that Spring Security has already checked. The signature + * guarantees that nobody changed these values after login, which is why the merchant id must come + * from here and from nowhere else: not from the URL, not from a query parameter, not from the body. + */ +public record Caller(String username, String merchantId) { + + public static Caller of(Jwt jwt) { + return new Caller(jwt.getSubject(), jwt.getClaimAsString("merchant_id")); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/JwtProperties.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/JwtProperties.java new file mode 100644 index 0000000..3b51ecb --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/JwtProperties.java @@ -0,0 +1,29 @@ +package com.amigoscode.authz.security; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** authz.jwt.* from application.properties. */ +@ConfigurationProperties("authz.jwt") +public record JwtProperties(String secret, String issuer, Duration timeToLive) { + + public JwtProperties { + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) { + throw new IllegalArgumentException("authz.jwt.secret (or JWT_SECRET) must be at least 32 bytes for HS256"); + } + } + + /** The HMAC-SHA256 key. With HS256 the same key signs and checks, so whoever can check can also sign. */ + public SecretKey key() { + return new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + } + + /** Never print the secret, not even by accident in a log line. */ + @Override + public String toString() { + return "JwtProperties[secret=(hidden), issuer=" + issuer + ", timeToLive=" + timeToLive + "]"; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityConfig.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityConfig.java new file mode 100644 index 0000000..92c09e7 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityConfig.java @@ -0,0 +1,102 @@ +package com.amigoscode.authz.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidator; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; +import org.springframework.security.oauth2.jwt.JwtClaimValidator; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtValidators; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; +import org.springframework.security.web.SecurityFilterChain; + +/** + * Authentication: every request except POST /login must carry a valid bearer token. Spring + * Security checks the token (signature, expiry, issuer, required claims) before any controller + * runs, and answers 401 when it is missing or not trusted. + * + *

Authorisation happens after that, in two places: roles are checked with {@code @PreAuthorize} + * (enabled here by {@code @EnableMethodSecurity}), and which merchant's data you may touch is + * decided by the queries in InvoiceService. + */ +@Configuration +@EnableMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain api(HttpSecurity http, JwtAuthenticationConverter jwtAuthenticationConverter, + SecurityProblems problems) throws Exception { + http + // No cookies and no session: the browser never sends the token on its own, so there is + // nothing for a cross-site request to ride on. That is why CSRF protection can go. + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(requests -> requests + .requestMatchers(HttpMethod.POST, "/login").permitAll() + .requestMatchers("/error").permitAll() + .anyRequest().authenticated()) + .oauth2ResourceServer(resourceServer -> resourceServer + .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)) + .authenticationEntryPoint(problems) + .accessDeniedHandler(problems)) + .exceptionHandling(exceptions -> exceptions + .authenticationEntryPoint(problems) + .accessDeniedHandler(problems)); + return http.build(); + } + + /** + * Checks every token: the HS256 signature with our key, then the validators. Anything that + * fails is a 401 before the request reaches a controller. + */ + @Bean + public JwtDecoder jwtDecoder(JwtProperties properties) { + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(properties.key()) + .macAlgorithm(MacAlgorithm.HS256) + .build(); + // setJwtValidator REPLACES the default validators, so the defaults have to be put back in: + // createDefaultWithIssuer checks exp and nbf (with 60 seconds of clock skew) and iss. + decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>( + JwtValidators.createDefaultWithIssuer(properties.issuer()), + required(JwtClaimNames.SUB), + required("merchant_id"))); + return decoder; + } + + /** + * Turns a checked token into Spring Security authorities. The default reads the "scope" (or + * "scp") claim and prefixes every value with SCOPE_. Our tokens carry "roles": ["USER","ADMIN"], + * and hasRole('ADMIN') looks for the authority ROLE_ADMIN. + */ + @Bean + public JwtAuthenticationConverter jwtAuthenticationConverter() { + JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter(); + roles.setAuthoritiesClaimName("roles"); + roles.setAuthorityPrefix("ROLE_"); + JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); + converter.setJwtGrantedAuthoritiesConverter(roles); + return converter; + } + + /** Checks the passwords in app_user. "{bcrypt}..." hashes, so the algorithm can change later. */ + @Bean + public PasswordEncoder passwordEncoder() { + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } + + private static OAuth2TokenValidator required(String claim) { + return new JwtClaimValidator(claim, value -> value instanceof String text && !text.isBlank()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityProblems.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityProblems.java new file mode 100644 index 0000000..83223a9 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/SecurityProblems.java @@ -0,0 +1,73 @@ +package com.amigoscode.authz.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import java.util.TreeMap; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; +import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * The 401 and the 403. Both are decided by Spring Security's filters, before any controller runs, + * so ApiExceptionHandler never sees them. + * + *

Spring's own bearer-token handlers set the status and the WWW-Authenticate header (RFC 6750), + * and send no body. This class lets them do exactly that, then adds a ProblemDetail body in the + * same shape as every other error of this API. + * + *

401 Unauthorized means "I do not know who you are": no token, or a token I do not trust. + * 403 Forbidden means "I know who you are, and you may not do this". + */ +@Component +public class SecurityProblems implements AuthenticationEntryPoint, AccessDeniedHandler { + + private final AuthenticationEntryPoint bearerEntryPoint = new BearerTokenAuthenticationEntryPoint(); + private final AccessDeniedHandler bearerAccessDenied = new BearerTokenAccessDeniedHandler(); + private final JsonMapper json = JsonMapper.builder().build(); + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) + throws IOException, jakarta.servlet.ServletException { + bearerEntryPoint.commence(request, response, e); + String detail = switch (e) { + case OAuth2AuthenticationException oauth when oauth.getError().getDescription() != null -> + oauth.getError().getDescription(); + case InsufficientAuthenticationException ignored -> "No token. Send the header Authorization: Bearer ."; + default -> e.getMessage(); + }; + write(request, response, HttpStatus.UNAUTHORIZED, "Not authenticated", detail); + } + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) + throws IOException, jakarta.servlet.ServletException { + bearerAccessDenied.handle(request, response, e); + write(request, response, HttpStatus.FORBIDDEN, "Not allowed", + "Your token is valid, but it does not allow this request."); + } + + private void write(HttpServletRequest request, HttpServletResponse response, HttpStatus status, + String title, String detail) throws IOException { + // Same fields, in the same (alphabetical) order, as the ProblemDetail that Spring MVC writes. + Map problem = new TreeMap<>(); + problem.put("title", title); + problem.put("status", status.value()); + problem.put("detail", detail); + problem.put("instance", request.getRequestURI()); + response.setStatus(status.value()); + response.setCharacterEncoding("UTF-8"); + response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); + response.getWriter().write(json.writeValueAsString(problem)); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/TokenService.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/TokenService.java new file mode 100644 index 0000000..8194cc1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/java/com/amigoscode/authz/security/TokenService.java @@ -0,0 +1,55 @@ +package com.amigoscode.authz.security; + +import com.nimbusds.jose.jwk.source.ImmutableSecret; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.JwsHeader; +import org.springframework.security.oauth2.jwt.JwtClaimsSet; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.JwtEncoderParameters; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; +import org.springframework.stereotype.Service; + +/** + * Issues the tokens that POST /login hands out. In a real system this is the identity provider's + * job (Keycloak, Auth0, Cognito, Entra ID...), and it signs with a private key that this + * application never sees. Here it lives in the same application so the project needs nothing else. + */ +@Service +public class TokenService { + + public record IssuedToken(String value, Instant expiresAt) { + } + + private final JwtEncoder encoder; + private final JwtProperties properties; + private final Clock clock; + + public TokenService(JwtProperties properties, Clock clock) { + // One secret key, no key id. (An identity provider has several keys and puts a "kid" header + // in every token, so the checker knows which public key to use. That is how keys rotate.) + this.encoder = new NimbusJwtEncoder(new ImmutableSecret<>(properties.key())); + this.properties = properties; + this.clock = clock; + } + + /** Who you are (sub), which merchant you work for (merchant_id), what you may do (roles). Nothing secret. */ + public IssuedToken issue(String username, String merchantId, List roles) { + Instant now = clock.instant().truncatedTo(ChronoUnit.SECONDS); + Instant expiresAt = now.plus(properties.timeToLive()); + JwtClaimsSet claims = JwtClaimsSet.builder() + .issuer(properties.issuer()) + .subject(username) + .issuedAt(now) + .expiresAt(expiresAt) + .claim("merchant_id", merchantId) + .claim("roles", roles) + .build(); + JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).type("JWT").build(); + String token = encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue(); + return new IssuedToken(token, expiresAt); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/application.properties b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/application.properties new file mode 100644 index 0000000..d6adfc2 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/application.properties @@ -0,0 +1,24 @@ +spring.application.name=authorisation-and-jwt + +# Postgres from compose.yaml. Port 5453 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5453/invoices} +spring.datasource.username=${DB_USER:invoices} +spring.datasource.password=${DB_PASSWORD:invoices} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always + +# The key that signs and checks every token (HMAC-SHA256, so the same key does both). +# This default is a DEV-ONLY value, checked into a public repository on purpose: it is not a +# secret and must never be used anywhere real. Set JWT_SECRET to override it. A real key comes +# from a secret store (Vault, AWS Secrets Manager, a Kubernetes secret), never from a file in git. +# HS256 needs at least 32 bytes. +authz.jwt.secret=${JWT_SECRET:dev-only-not-a-secret-do-not-use-outside-your-laptop} +# Who issues the tokens. Tokens with any other "iss" are refused. +authz.jwt.issuer=https://login.example.com +# How long a token from POST /login stays valid. +authz.jwt.time-to-live=15m + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/reset.sql b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/reset.sql new file mode 100644 index 0000000..16ca8b7 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/reset.sql @@ -0,0 +1,10 @@ +-- The starting data: three invoices for each merchant. ./demo and every test begin from here. +truncate table invoice restart identity; + +insert into invoice (merchant_id, number, customer, amount_cents, status, updated_by) +values ('merchant-a', 'A-1001', 'Hill Road Florist', 12000, 'ISSUED', 'alice'), + ('merchant-a', 'A-1002', 'Garden Cafe', 7550, 'PAID', 'alice'), + ('merchant-a', 'A-1003', 'Bike Repair Shop', 31000, 'DRAFT', 'alice'), + ('merchant-b', 'B-2001', 'Riverside Gym', 99000, 'ISSUED', 'bob'), + ('merchant-b', 'B-2002', 'Book Corner', 4500, 'PAID', 'bob'), + ('merchant-b', 'B-2003', 'Town Dental Clinic', 120000, 'ISSUED', 'bob'); diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..e79442d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/main/resources/schema.sql @@ -0,0 +1,30 @@ +-- Applied on every start. The invoices themselves are reset by reset.sql (./demo and the tests). + +create table if not exists app_user ( + username text primary key, + password_hash text not null, + merchant_id text not null, + roles text not null -- comma separated, for example USER,ADMIN +); + +create table if not exists invoice ( + id bigserial primary key, + merchant_id text not null, + number text not null, + customer text not null, + amount_cents bigint not null check (amount_cents > 0), + status text not null, + updated_by text not null +); + +create index if not exists invoice_merchant_id on invoice (merchant_id); + +-- Three demo users. The password of all three is "password", stored as a bcrypt hash. +insert into app_user (username, password_hash, merchant_id, roles) +values ('alice', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'merchant-a', 'USER'), + ('bob', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'merchant-b', 'USER'), + ('admin', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'platform', 'USER,ADMIN') +on conflict (username) do update + set password_hash = excluded.password_hash, + merchant_id = excluded.merchant_id, + roles = excluded.roles; diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AdminRoleIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AdminRoleIT.java new file mode 100644 index 0000000..aff0284 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AdminRoleIT.java @@ -0,0 +1,71 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +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.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import tools.jackson.databind.JsonNode; + +/** Function-level authorisation: "may you call this endpoint at all?". /admin is for ROLE_ADMIN only. */ +@Tag("task5") +class AdminRoleIT extends IntegrationTest { + + @Autowired + private WebApplicationContext context; + + @Test + @DisplayName("Roles: bob (roles USER) calls GET /admin/invoices: 403 Forbidden, he is known but not allowed") + void userIsForbidden() { + Response response = api.get("/admin/invoices", tokenFor("bob")); + + assertThat(response.status()).as("status").isEqualTo(403); + assertThat(response.body()).as("body").doesNotContain("A-1001"); + } + + @Test + @DisplayName("Roles: admin (roles USER, ADMIN) calls GET /admin/invoices: 200 with the invoices of every merchant") + void adminSeesEveryMerchant() { + Response response = api.get("/admin/invoices", tokenFor("admin")); + + assertThat(response.status()).as("status").isEqualTo(200); + Set merchants = new HashSet<>(); + for (JsonNode invoice : response.json()) { + merchants.add(invoice.path("merchantId").asString()); + } + assertThat(merchants).as("merchants in the admin list").containsExactlyInAnyOrder("merchant-a", "merchant-b"); + } + + @Test + @DisplayName("Roles: GET /admin/invoices without a token is a 401, not a 403: nobody is signed in yet") + void noTokenIsUnauthorizedNotForbidden() { + assertThat(api.get("/admin/invoices", null).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Roles: MockMvc with spring-security-test's jwt(), no real token: a caller with only ROLE_USER gets 403") + void mockMvcJwtWithOnlyRoleUserIsForbidden() throws Exception { + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + + // jwt() puts a ready-made authentication in place: the JwtDecoder never runs, so this kind + // of test cannot catch a decoder that accepts expired tokens (Task 6). It does test the rule. + mvc.perform(get("/admin/invoices").with(jwt() + .jwt(token -> token.subject("bob").claim("merchant_id", "merchant-b").claim("roles", List.of("USER"))) + .authorities(new SimpleGrantedAuthority("ROLE_USER")))) + .andExpect(status().isForbidden()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AuthenticationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AuthenticationIT.java new file mode 100644 index 0000000..bd6d82c --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/AuthenticationIT.java @@ -0,0 +1,79 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import com.amigoscode.authz.support.Tokens; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Authentication: "who are you?". These pass from the start. That is the point of Task 1: every + * request without a trustworthy token is already refused, and the API is still leaking data. + */ +@Tag("task1") +class AuthenticationIT extends IntegrationTest { + + @Test + @DisplayName("Authentication: no token is a 401 with a WWW-Authenticate: Bearer header") + void noTokenIsUnauthorized() { + Response response = api.get("/invoices", null); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").startsWith("Bearer"); + } + + @Test + @DisplayName("Authentication: the right password returns a token that works, a wrong password is a 401 with no token") + void loginGivesATokenOnlyForTheRightPassword() { + Response wrong = api.post("/login", null, "{\"username\":\"alice\",\"password\":\"guess\"}"); + Response right = api.post("/login", null, "{\"username\":\"alice\",\"password\":\"password\"}"); + + assertThat(wrong.status()).as("status for a wrong password").isEqualTo(401); + assertThat(wrong.json().has("token")).as("a token for a wrong password").isFalse(); + assertThat(right.status()).as("status for the right password").isEqualTo(200); + String token = right.json().path("token").asString(); + assertThat(api.get("/invoices", token).status()).as("GET /invoices with that token").isEqualTo(200); + } + + @Test + @DisplayName("Authentication: a token that is not a JWT at all is a 401 invalid_token") + void garbageIsUnauthorized() { + Response response = api.get("/invoices", "this-is-not-a-jwt"); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("error=\"invalid_token\""); + } + + @Test + @DisplayName("Authentication: a token signed with a different key is a 401") + void wrongKeyIsUnauthorized() { + String token = tokens.signWithAnotherKey(tokens.claims("alice", "merchant-a", "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Authentication: a token with alg none (no signature at all) is a 401") + void algNoneIsUnauthorized() { + String token = tokens.unsigned(tokens.claims("alice", "merchant-a", "USER", "ADMIN")); + + Response response = api.get("/invoices", token); + + assertThat(token).as("an alg none token ends with an empty signature").endsWith("."); + assertThat(response.status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Authentication: alice's real token with merchant_id edited to merchant-b afterwards is a 401, the signature no longer matches") + void editedTokenIsUnauthorized() { + String edited = Tokens.withClaimChanged(tokenFor("alice"), "merchant_id", "merchant-b"); + + Response response = api.get("/invoices", edited); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.body()).as("body").doesNotContain("B-200"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/Check.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/Check.java new file mode 100644 index 0000000..2e7f700 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/Check.java @@ -0,0 +1,114 @@ +package com.amigoscode.authz; + +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, 7 and 8 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: how tokens are made (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See it break: authentication already works"); + TASKS.put("2", "Task 2: Fix the IDOR: scope every invoice query to the caller's merchant"); + TASKS.put("4", "Task 4: Fix the tenant that comes from the request"); + TASKS.put("5", "Task 5: Fix the admin endpoint: a role check that really checks"); + TASKS.put("6", "Task 6: Fix token validation: expired tokens and missing claims"); + } + + 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/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java new file mode 100644 index 0000000..302966d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java @@ -0,0 +1,85 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Object-level authorisation: "is this invoice yours?". alice works for merchant-a (invoices 1 to + * 3), bob for merchant-b (invoices 4 to 6). Both have perfectly valid tokens. + */ +@Tag("task2") +class ObjectLevelAuthorisationIT extends IntegrationTest { + + @Test + @DisplayName("IDOR: alice reads her own invoice 1: 200") + void ownInvoiceIsReadable() { + Response response = api.get("/invoices/1", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(response.json().path("number").asString()).as("number").isEqualTo("A-1001"); + } + + @Test + @DisplayName("IDOR: alice asks for invoice 4 of merchant-b (and bob for invoice 1 of merchant-a): 404, and none of its data in the body") + void anotherMerchantsInvoiceIsNotFound() { + Response alice = api.get("/invoices/4", tokenFor("alice")); + Response bob = api.get("/invoices/1", tokenFor("bob")); + + assertThat(alice.status()).as("status of alice -> invoice 4").isEqualTo(404); + assertThat(alice.body()).as("body").doesNotContain("B-2001").doesNotContain("Riverside Gym"); + assertThat(bob.status()).as("status of bob -> invoice 1").isEqualTo(404); + assertThat(bob.body()).as("body").doesNotContain("A-1001").doesNotContain("Hill Road Florist"); + } + + @Test + @DisplayName("IDOR: alice updates invoice 5 of merchant-b: 404, and the invoice is unchanged in the database") + void anotherMerchantsInvoiceCannotBeChanged() { + Response response = api.put("/invoices/5", tokenFor("alice"), "{\"customer\":\"Changed by alice\",\"amountCents\":1}"); + + assertThat(response.status()).as("status").isEqualTo(404); + assertThat(amountOf(5)).as("amount of invoice 5 in the database").isEqualTo(4500); + } + + @Test + @DisplayName("IDOR: alice deletes invoice 6 of merchant-b: 404, and the invoice is still there") + void anotherMerchantsInvoiceCannotBeDeleted() { + Response response = api.delete("/invoices/6", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(404); + assertThat(merchantOf(6)).as("invoice 6 in the database").isEqualTo("merchant-b"); + } + + @Test + @DisplayName("IDOR: another merchant's invoice and an id that does not exist get exactly the same 404, so ids cannot be probed") + void anotherMerchantsInvoiceLooksLikeAnIdThatDoesNotExist() { + String alice = tokenFor("alice"); + + Response someoneElses = api.get("/invoices/4", alice); + Response missing = api.get("/invoices/999", alice); + + assertThat(someoneElses.status()).as("status for invoice 4 (exists, merchant-b)").isEqualTo(404); + assertThat(missing.status()).as("status for invoice 999 (does not exist)").isEqualTo(404); + assertThat(someoneElses.body().replace("/4", "/N").replace(" 4 ", " N ")) + .as("the two bodies, with the id taken out") + .isEqualTo(missing.body().replace("/999", "/N").replace(" 999 ", " N ")); + } + + @Test + @DisplayName("IDOR: alice can still update and delete her own invoices: 200 and 204") + void ownInvoicesCanStillBeChangedAndDeleted() { + String alice = tokenFor("alice"); + + Response updated = api.put("/invoices/2", alice, "{\"customer\":\"Garden Cafe Ltd\",\"amountCents\":8000}"); + Response deleted = api.delete("/invoices/3", alice); + + assertThat(updated.status()).as("PUT /invoices/2").isEqualTo(200); + assertThat(amountOf(2)).as("amount of invoice 2 in the database").isEqualTo(8000); + assertThat(deleted.status()).as("DELETE /invoices/3").isEqualTo(204); + assertThat(merchantOf(3)).as("invoice 3 in the database").isNull(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/RolesConverterTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/RolesConverterTest.java new file mode 100644 index 0000000..2ae9367 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/RolesConverterTest.java @@ -0,0 +1,32 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.security.SecurityConfig; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; + +/** Unit test: no Spring context. What authorities does a checked token turn into? */ +@Tag("task5") +class RolesConverterTest { + + @Test + @DisplayName("Roles: a token with \"roles\": [\"USER\",\"ADMIN\"] becomes the authorities ROLE_USER and ROLE_ADMIN") + void rolesClaimBecomesRoleAuthorities() { + Jwt jwt = Jwt.withTokenValue("token") + .header("alg", "HS256") + .subject("admin") + .claim("merchant_id", "platform") + .claim("roles", List.of("USER", "ADMIN")) + .build(); + + List authorities = new SecurityConfig().jwtAuthenticationConverter().convert(jwt).getAuthorities() + .stream().map(GrantedAuthority::getAuthority).toList(); + + assertThat(authorities).as("authorities").contains("ROLE_USER", "ROLE_ADMIN"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java new file mode 100644 index 0000000..740b007 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java @@ -0,0 +1,94 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.util.ArrayList; +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; + +/** + * The merchant comes from the token, never from the request. Not from a query parameter, not from + * the JSON body, and the body cannot set the id or the status either (mass assignment). + */ +@Tag("task4") +class TenantFromRequestIT extends IntegrationTest { + + private static final String NEW_INVOICE = "\"number\":\"A-1004\",\"customer\":\"Corner Shop\",\"amountCents\":2500"; + + @Test + @DisplayName("Tenant: GET /invoices as alice returns her 3 invoices, all of merchant-a") + void listReturnsOwnInvoices() { + Response response = api.get("/invoices", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(merchants(response.json())).as("merchant of every invoice returned") + .containsExactly("merchant-a", "merchant-a", "merchant-a"); + } + + @Test + @DisplayName("Tenant: GET /invoices?merchantId=merchant-b as alice still returns only merchant-a's invoices") + void merchantIdParameterIsIgnored() { + Response response = api.get("/invoices?merchantId=merchant-b", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(merchants(response.json())).as("merchant of every invoice returned") + .containsExactly("merchant-a", "merchant-a", "merchant-a"); + } + + @Test + @DisplayName("Tenant: POST /invoices with merchantId merchant-b in the body creates the invoice for alice's own merchant-a") + void merchantIdInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{" + NEW_INVOICE + ",\"merchantId\":\"merchant-b\"}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("merchantId").asString()).as("merchantId in the response").isEqualTo("merchant-a"); + assertThat(invoicesOf("merchant-a")).as("invoices of merchant-a in the database").isEqualTo(4); + assertThat(invoicesOf("merchant-b")).as("invoices of merchant-b in the database").isEqualTo(3); + } + + @Test + @DisplayName("Mass assignment: POST /invoices with \"id\":4 in the body creates a new invoice and leaves invoice 4 of merchant-b alone") + void idInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{\"id\":4," + NEW_INVOICE + "}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("id").asLong()).as("id of the new invoice").isEqualTo(7); + assertThat(merchantOf(4)).as("merchant of invoice 4 in the database").isEqualTo("merchant-b"); + assertThat(amountOf(4)).as("amount of invoice 4 in the database").isEqualTo(99000); + } + + @Test + @DisplayName("Mass assignment: POST /invoices with \"status\":\"PAID\" in the body still creates a DRAFT") + void statusInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{" + NEW_INVOICE + ",\"status\":\"PAID\"}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("status").asString()).as("status of the new invoice").isEqualTo("DRAFT"); + } + + @Test + @DisplayName("Validation: POST /invoices without a customer, or with a negative amount, is a 400 (not a 500)") + void invalidInvoiceIsABadRequest() { + String alice = tokenFor("alice"); + + Response noCustomer = api.post("/invoices", alice, "{\"number\":\"A-1005\",\"amountCents\":2500}"); + Response negative = api.post("/invoices", alice, "{\"number\":\"A-1005\",\"customer\":\"Corner Shop\",\"amountCents\":-5}"); + + assertThat(noCustomer.status()).as("status without a customer").isEqualTo(400); + assertThat(negative.status()).as("status with a negative amount").isEqualTo(400); + assertThat(invoicesOf("merchant-a")).as("invoices of merchant-a in the database").isEqualTo(3); + } + + private static List merchants(JsonNode invoices) { + List merchants = new ArrayList<>(); + for (JsonNode invoice : invoices) { + merchants.add(invoice.path("merchantId").asString()); + } + return merchants; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenServiceTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenServiceTest.java new file mode 100644 index 0000000..23ff6b1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenServiceTest.java @@ -0,0 +1,77 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.authz.security.JwtProperties; +import com.amigoscode.authz.security.TokenService; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unit tests: no Spring, no database, a fixed clock. They pin down what a token from POST /login + * looks like. They pass from the start and must keep passing. + */ +@Tag("baseline") +class TokenServiceTest { + + private static final Instant NOW = Instant.parse("2030-01-01T10:00:00Z"); + private static final JwtProperties PROPERTIES = new JwtProperties( + "dev-only-not-a-secret-just-for-this-unit-test", "https://login.example.com", Duration.ofMinutes(15)); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final TokenService tokens = new TokenService(PROPERTIES, Clock.fixed(NOW, ZoneOffset.UTC)); + + @Test + @DisplayName("Tokens: a login token is signed with HS256 and carries iss, sub, merchant_id, roles, iat and exp 15 minutes after iat") + void loginTokenHasTheExpectedHeaderAndClaims() { + String token = tokens.issue("alice", "merchant-a", List.of("USER")).value(); + + JsonNode header = part(token, 0); + JsonNode claims = part(token, 1); + + assertThat(header.path("alg").asString()).as("alg").isEqualTo("HS256"); + assertThat(header.path("typ").asString()).as("typ").isEqualTo("JWT"); + assertThat(claims.path("iss").asString()).as("iss").isEqualTo("https://login.example.com"); + assertThat(claims.path("sub").asString()).as("sub").isEqualTo("alice"); + assertThat(claims.path("merchant_id").asString()).as("merchant_id").isEqualTo("merchant-a"); + assertThat(claims.path("roles").get(0).asString()).as("roles").isEqualTo("USER"); + assertThat(claims.path("iat").asLong()).as("iat").isEqualTo(NOW.getEpochSecond()); + assertThat(claims.path("exp").asLong()).as("exp").isEqualTo(NOW.plus(Duration.ofMinutes(15)).getEpochSecond()); + } + + @Test + @DisplayName("Tokens: anyone can read the claims without the key (signed, not encrypted), so a token holds no password and no personal data") + void claimsAreReadableByAnyoneSoTheyHoldNothingSecret() { + String token = tokens.issue("alice", "merchant-a", List.of("USER")).value(); + + // Plain Base64, no key: this is all an attacker needs to read a token. + String payload = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1])); + + assertThat(payload).contains("\"merchant_id\":\"merchant-a\""); + assertThat(part(token, 1).propertyNames()) + .as("the only claims in a login token") + .containsExactlyInAnyOrder("iss", "sub", "iat", "exp", "merchant_id", "roles"); + } + + @Test + @DisplayName("Tokens: the signing key must be at least 32 bytes, because HS256 needs a 256-bit key") + void shortKeysAreRefused() { + assertThatThrownBy(() -> new JwtProperties("too-short", "https://login.example.com", Duration.ofMinutes(15))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("at least 32 bytes"); + } + + private static JsonNode part(String token, int index) { + return JSON.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[index])); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenValidationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenValidationIT.java new file mode 100644 index 0000000..1c95dff --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/TokenValidationIT.java @@ -0,0 +1,71 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Every token here has a perfectly valid signature. What is wrong with it is inside. Nothing in + * these tests waits for a token to expire: the times are simply written in the past or the future. + */ +@Tag("task6") +class TokenValidationIT extends IntegrationTest { + + @Test + @DisplayName("Validation: a token that expired an hour ago is a 401 invalid_token, 'Jwt expired at ...'") + void expiredTokenIsUnauthorized() { + Instant anHourAgo = Instant.now().minus(Duration.ofHours(1)); + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER") + .issueTime(Date.from(anHourAgo.minus(Duration.ofMinutes(15)))) + .expirationTime(Date.from(anHourAgo))); + + Response response = api.get("/invoices", token); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("Jwt expired at"); + } + + @Test + @DisplayName("Validation: a token that is not valid yet (nbf one hour from now) is a 401") + void notYetValidTokenIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER") + .notBeforeTime(Date.from(Instant.now().plus(Duration.ofHours(1)))) + .expirationTime(Date.from(Instant.now().plus(Duration.ofHours(2))))); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token without merchant_id is a 401, not a 200 with an empty list") + void tokenWithoutMerchantIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", null, "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token without sub (nobody) is a 401") + void tokenWithoutSubjectIsUnauthorized() { + String token = tokens.sign(tokens.claims(null, "merchant-a", "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token from another issuer is a 401, even though it is signed with our key") + void otherIssuerIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER").issuer("https://someone-else.example.com")); + + Response response = api.get("/invoices", token); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("iss"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Api.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Api.java new file mode 100644 index 0000000..de69211 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Api.java @@ -0,0 +1,70 @@ +package com.amigoscode.authz.support; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Real HTTP requests against the running application, with a real "Authorization: Bearer" header. + * Nothing is mocked: the token goes through the same filters as in production. + */ +public final class Api { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + /** What came back. {@code json} is an empty object when the body is not JSON. */ + public record Response(int status, String wwwAuthenticate, String body, JsonNode json) { + } + + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + public Api(int port) { + this.baseUrl = "http://localhost:" + port; + } + + public Response get(String path, String token) { + return send(request(path, token).GET()); + } + + public Response post(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json))); + } + + public Response put(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json))); + } + + public Response delete(String path, String token) { + return send(request(path, token).DELETE()); + } + + private HttpRequest.Builder request(String path, String token) { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl + path)); + if (token != null) { + builder.header("Authorization", "Bearer " + token); + } + return builder; + } + + private Response send(HttpRequest.Builder request) { + try { + HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + JsonNode json; + try { + json = response.body().isBlank() ? JSON.createObjectNode() : JSON.readTree(response.body()); + } catch (RuntimeException notJson) { + json = JSON.createObjectNode(); + } + return new Response(response.statusCode(), + response.headers().firstValue("WWW-Authenticate").orElse(""), response.body(), json); + } catch (Exception e) { + throw new IllegalStateException("Request failed: " + e, e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/IntegrationTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/IntegrationTest.java new file mode 100644 index 0000000..090ec17 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/IntegrationTest.java @@ -0,0 +1,92 @@ +package com.amigoscode.authz.support; + +import com.amigoscode.authz.login.UserAccounts; +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.JwtProperties; +import com.amigoscode.authz.security.TokenService; +import javax.sql.DataSource; +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.core.io.ClassPathResource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They start the real application on a free port, against a real + * Postgres started by Testcontainers (Docker must be running), and send it real HTTP requests with + * real tokens. One container is shared by every test class. + * + *

Every test starts from src/main/resources/reset.sql: invoices 1 to 3 belong to merchant-a + * (alice), invoices 4 to 6 to merchant-b (bob). admin works for "platform" and has the ADMIN role. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private DataSource dataSource; + + @Autowired + private JwtProperties jwtProperties; + + @Autowired + private TokenService tokenService; + + @Autowired + private UserAccounts users; + + @Value("${local.server.port}") + private int port; + + protected Api api; + + protected Tokens tokens; + + @BeforeEach + void startingData() { + new ResourceDatabasePopulator(new ClassPathResource("reset.sql")).execute(dataSource); + api = new Api(port); + tokens = new Tokens(jwtProperties); + } + + /** The token POST /login would give this user, made by the application's own TokenService. */ + protected String tokenFor(String username) { + UserAccount user = users.find(username).orElseThrow(); + return tokenService.issue(user.username(), user.merchantId(), user.roles()).value(); + } + + /** The merchant an invoice belongs to, straight from the database, or null when it does not exist. */ + protected String merchantOf(long invoiceId) { + return jdbc.query("select merchant_id from invoice where id = ?", (row, n) -> row.getString(1), invoiceId) + .stream().findFirst().orElse(null); + } + + protected long amountOf(long invoiceId) { + return jdbc.queryForObject("select amount_cents from invoice where id = ?", Long.class, invoiceId); + } + + protected int invoicesOf(String merchantId) { + return jdbc.queryForObject("select count(*) from invoice where merchant_id = ?", Integer.class, merchantId); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Tokens.java b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Tokens.java new file mode 100644 index 0000000..8f052a8 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/java/com/amigoscode/authz/support/Tokens.java @@ -0,0 +1,82 @@ +package com.amigoscode.authz.support; + +import com.amigoscode.authz.security.JwtProperties; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; +import com.nimbusds.jwt.SignedJWT; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * Makes the tokens a real login never hands out: expired ones, unsigned ones, ones signed with the + * wrong key, ones that were edited after signing. Good tokens come from the application's own + * TokenService (see IntegrationTest.tokenFor). + */ +public final class Tokens { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final JwtProperties properties; + + public Tokens(JwtProperties properties) { + this.properties = properties; + } + + /** The claims a login gives alice: valid from now for 15 minutes. Change what a test needs. */ + public JWTClaimsSet.Builder claims(String username, String merchantId, String... roles) { + Instant now = Instant.now(); + return new JWTClaimsSet.Builder() + .issuer(properties.issuer()) + .subject(username) + .issueTime(Date.from(now)) + .expirationTime(Date.from(now.plus(Duration.ofMinutes(15)))) + .claim("merchant_id", merchantId) + .claim("roles", List.of(roles)); + } + + /** HS256 with the server's own key: the signature is valid. */ + public String sign(JWTClaimsSet.Builder claims) { + return signWith(claims, properties.secret().getBytes(StandardCharsets.UTF_8)); + } + + /** HS256 with a key the server does not know. */ + public String signWithAnotherKey(JWTClaimsSet.Builder claims) { + return signWith(claims, "another-key-that-the-server-has-never-seen".getBytes(StandardCharsets.UTF_8)); + } + + /** {"alg":"none"}: no signature at all. "header.payload." with nothing after the last dot. */ + public String unsigned(JWTClaimsSet.Builder claims) { + return new PlainJWT(claims.build()).serialize(); + } + + /** Changes one claim in the payload and keeps the old signature, like an attacker would. */ + public static String withClaimChanged(String token, String claim, String value) { + String[] parts = token.split("\\."); + ObjectNode payload = (ObjectNode) JSON.readTree(Base64.getUrlDecoder().decode(parts[1])); + payload.put(claim, value); + String edited = Base64.getUrlEncoder().withoutPadding() + .encodeToString(JSON.writeValueAsBytes(payload)); + return parts[0] + "." + edited + "." + parts[2]; + } + + private static String signWith(JWTClaimsSet.Builder claims, byte[] key) { + try { + SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build(), + claims.build()); + jwt.sign(new MACSigner(key)); + return jwt.serialize(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/14-authorisation-and-jwt/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..7fd76f1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/start/.mvn/jvm.config b/java/concepts/junior-mid/14-authorisation-and-jwt/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/14-authorisation-and-jwt/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/start/check b/java/concepts/junior-mid/14-authorisation-and-jwt/start/check new file mode 100755 index 0000000..6825bc5 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/check.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/start/check.cmd new file mode 100644 index 0000000..10a1d17 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/compose.yaml b/java/concepts/junior-mid/14-authorisation-and-jwt/start/compose.yaml new file mode 100644 index 0000000..a97708b --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/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: authorisation-and-jwt +services: + postgres: + image: postgres:17-alpine + container_name: authorisation-and-jwt-postgres + environment: + POSTGRES_DB: invoices + POSTGRES_USER: invoices + POSTGRES_PASSWORD: invoices + ports: + - "5453:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U invoices -d invoices"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/demo b/java/concepts/junior-mid/14-authorisation-and-jwt/start/demo new file mode 100755 index 0000000..04d69cd --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/demo.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/start/demo.cmd new file mode 100644 index 0000000..1b20379 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/inspect b/java/concepts/junior-mid/14-authorisation-and-jwt/start/inspect new file mode 100755 index 0000000..435bce2 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/inspect.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/start/inspect.cmd new file mode 100644 index 0000000..c44d2d8 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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.authz.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/mvnw b/java/concepts/junior-mid/14-authorisation-and-jwt/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/start/mvnw.cmd b/java/concepts/junior-mid/14-authorisation-and-jwt/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/14-authorisation-and-jwt/start/pom.xml b/java/concepts/junior-mid/14-authorisation-and-jwt/start/pom.xml new file mode 100644 index 0000000..82d0b97 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/pom.xml @@ -0,0 +1,126 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + authorisation-and-jwt + 0.0.1-SNAPSHOT + authorisation-and-jwt + Authentication vs authorisation with JWTs: watch merchant A read merchant B's invoices, then fix it + + + 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-validation + + + + org.springframework.boot + spring-boot-starter-security-oauth2-resource-server + + + 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.springframework.boot + spring-boot-starter-security-oauth2-resource-server-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/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java new file mode 100644 index 0000000..ab42a4d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/ApiExceptionHandler.java @@ -0,0 +1,38 @@ +package com.amigoscode.authz; + +import com.amigoscode.authz.invoice.InvoiceNotFoundException; +import com.amigoscode.authz.login.BadLoginException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +/** + * Errors from the controllers leave the API as RFC 9457 ProblemDetail (application/problem+json). + * Extending ResponseEntityExceptionHandler gives Spring's own exceptions the right status for free: + * a body that cannot be read or fails validation is a 400. + * + *

There is deliberately no catch-all {@code @ExceptionHandler(Exception.class)} here. An + * AccessDeniedException thrown by {@code @PreAuthorize} has to travel up to Spring Security, which + * turns it into a 403. A catch-all would swallow it and answer 500. + * + *

401 and 403 from the security filters never reach this class: see security/SecurityProblems. + */ +@RestControllerAdvice +public class ApiExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(InvoiceNotFoundException.class) + public ProblemDetail notFound(InvoiceNotFoundException e) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); + problem.setTitle("Invoice not found"); + return problem; + } + + @ExceptionHandler(BadLoginException.class) + public ProblemDetail badLogin(BadLoginException e) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED, e.getMessage()); + problem.setTitle("Login failed"); + return problem; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/AuthzApplication.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/AuthzApplication.java new file mode 100644 index 0000000..e8156f4 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/AuthzApplication.java @@ -0,0 +1,22 @@ +package com.amigoscode.authz; + +import java.time.Clock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class AuthzApplication { + + public static void main(String[] args) { + SpringApplication.run(AuthzApplication.class, args); + } + + /** Everything that needs "now" asks this clock, so a test can pin it. */ + @Bean + Clock clock() { + return Clock.systemUTC(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/admin/AdminController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/admin/AdminController.java new file mode 100644 index 0000000..7315ed5 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/admin/AdminController.java @@ -0,0 +1,26 @@ +package com.amigoscode.authz.admin; + +import com.amigoscode.authz.invoice.InvoiceResponse; +import com.amigoscode.authz.invoice.InvoiceService; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** For the platform's support staff: every merchant's invoices. */ +@RestController +@RequestMapping("/admin") +public class AdminController { + + private final InvoiceService invoices; + + public AdminController(InvoiceService invoices) { + this.invoices = invoices; + } + + /** TODO Task 5: only callers with the role ADMIN may use this. */ + @GetMapping("/invoices") + public List allInvoices() { + return invoices.listAll().stream().map(InvoiceResponse::from).toList(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/App.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/App.java new file mode 100644 index 0000000..94ad4ea --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/App.java @@ -0,0 +1,172 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.AuthzApplication; +import com.amigoscode.authz.security.JwtProperties; +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.Map; +import java.util.TreeMap; +import javax.sql.DataSource; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * What ./demo and ./inspect share: the real application on a free port, real HTTP requests with a + * real Authorization header, and a look at the database. + */ +final class App implements AutoCloseable { + + /** What came back from one request. {@code json} is an empty object when the body is not JSON. */ + record Reply(int status, String body, JsonNode json, String wwwAuthenticate) { + } + + /** The demo users. All three have the password "password" (see schema.sql). */ + static final String PASSWORD = "password"; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final ConfigurableApplicationContext context; + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + private App(ConfigurableApplicationContext context) { + this.context = context; + this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + } + + /** Starts the application. Returns null, after printing what to do, when Postgres is not reachable. */ + static App start(boolean sql) { + if (!Db.isUp()) { + return null; + } + List args = new ArrayList<>(List.of( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line in the table instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF")); + if (sql) { + args.add("--logging.level.org.hibernate.SQL=DEBUG"); + // The column list of a select is replaced by "...": the WHERE clause is what matters here. + args.add("--logging.pattern.console= SQL: %replace(%msg){'select [^ ]+ from','select ... from'}%n"); + } + SpringApplication app = new SpringApplication(AuthzApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + return new App(app.run(args.toArray(String[]::new))); + } + + /** Puts the six starting invoices back (src/main/resources/reset.sql). */ + void resetData() { + new ResourceDatabasePopulator(new ClassPathResource("reset.sql")).execute(context.getBean(DataSource.class)); + } + + JdbcTemplate jdbc() { + return context.getBean(JdbcTemplate.class); + } + + T bean(Class type) { + return context.getBean(type); + } + + JwtProperties jwtProperties() { + return context.getBean(JwtProperties.class); + } + + /** POST /login with the demo password. Returns the token. */ + String login(String username) { + Reply reply = post("/login", null, "{\"username\":\"" + username + "\",\"password\":\"" + PASSWORD + "\"}"); + if (reply.status() != 200) { + throw new IllegalStateException("POST /login for " + username + " answered " + reply.status() + ": " + reply.body()); + } + return reply.json().path("token").asString(); + } + + Reply get(String path, String token) { + return send(request(path, token).GET()); + } + + Reply post(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json))); + } + + Reply put(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json))); + } + + Reply delete(String path, String token) { + return send(request(path, token).DELETE()); + } + + /** "3 invoices of merchant-a", "invoice 4 of merchant-b", "7 invoices of merchant-a, merchant-b", "no invoices". */ + static String whose(JsonNode json) { + if (json.isArray()) { + if (json.isEmpty()) { + return "no invoices"; + } + Map perMerchant = new TreeMap<>(); + for (JsonNode invoice : json) { + perMerchant.merge(invoice.path("merchantId").asString("?"), 1, Integer::sum); + } + return json.size() + (json.size() == 1 ? " invoice" : " invoices") + " of " + + String.join(", ", perMerchant.keySet()); + } + if (json.has("merchantId")) { + return "invoice " + json.path("id").asLong() + " of " + json.path("merchantId").asString(); + } + return "nothing"; + } + + /** Terminal output stays ASCII: anything else (from a token someone pasted, say) is escaped. */ + static String ascii(String text) { + StringBuilder out = new StringBuilder(text.length()); + text.codePoints().forEach(c -> { + if (c >= 0x20 && c < 0x7f) { + out.append((char) c); + } else { + out.append(String.format("\\u%04x", c)); + } + }); + return out.toString(); + } + + private HttpRequest.Builder request(String path, String token) { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl + path)); + if (token != null) { + builder.header("Authorization", "Bearer " + token); + } + return builder; + } + + private Reply send(HttpRequest.Builder request) { + try { + HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + JsonNode json; + try { + json = response.body().isBlank() ? JSON.createObjectNode() : JSON.readTree(response.body()); + } catch (RuntimeException notJson) { + json = JSON.createObjectNode(); + } + return new Reply(response.statusCode(), response.body(), json, + response.headers().firstValue("WWW-Authenticate").orElse("")); + } catch (Exception e) { + throw new IllegalStateException("Request failed: " + e, e); + } + } + + @Override + public void close() { + context.close(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Db.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Db.java new file mode 100644 index 0000000..2a28238 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.authz.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:5453/invoices"); + static final String USER = env("DB_USER", "invoices"); + static final String PASSWORD = env("DB_PASSWORD", "invoices"); + + 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/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Demo.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Demo.java new file mode 100644 index 0000000..b316746 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Demo.java @@ -0,0 +1,321 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.demo.App.Reply; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import tools.jackson.databind.JsonNode; + +/** + * Starts the real application, logs in as two merchants and an admin, and sends real HTTP requests + * with real tokens: some fair, some an attacker would send. Prints a table of request, status and + * whose data came back, then one RESULT line per problem found. Every run starts from the same six + * invoices. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final String MERCHANT_A = "merchant-a"; + private static final String MERCHANT_B = "merchant-b"; + + private final App app; + private final boolean bodies; + + // What went wrong, for the RESULT lines. + private final Set invoicesOfBReadByAlice = new TreeSet<>(); + private int changedByAlice; + private int deletedByAlice; + private int takenOverByAlice; + private int createdForBByAlice; + private String statusFromTheBody; + private int adminListSeenByBob = -1; + private boolean adminLockedOut; + private final List badTokensLetIn = new ArrayList<>(); + private final List otherProblems = new ArrayList<>(); + + private Demo(App app, boolean bodies) { + this.app = app; + this.bodies = bodies; + } + + public static void main(String[] args) { + boolean sql = false; + boolean bodies = false; + for (String arg : args) { + switch (arg) { + case "--sql" -> sql = true; + case "--bodies" -> bodies = true; + default -> { + if (!arg.equals("--help") && !arg.equals("-h")) { + System.out.println("Unknown option: " + App.ascii(arg)); + System.out.println(); + } + printHelp(); + return; + } + } + } + try (App app = App.start(sql)) { + if (app != null) { + new Demo(app, bodies).run(); + } + } + } + + private void run() { + app.resetData(); + Forge forge = new Forge(app.jwtProperties()); + + System.out.println(); + System.out.println("Invoices 1-3 belong to merchant-a, invoices 4-6 to merchant-b (fresh data on every run)."); + System.out.println("alice works for merchant-a, bob for merchant-b, admin for the platform and has the ADMIN role."); + + section("AUTHENTICATION: who are you?"); + Reply reply = app.get("/invoices", null); + row("-", "GET /invoices (no token)", reply, App.whose(reply.json()), expect(reply, 401, "WRONG")); + reply = app.post("/login", null, "{\"username\":\"alice\",\"password\":\"guess\"}"); + row("alice", "POST /login (wrong password)", reply, "no token", expect(reply, 401, "WRONG")); + String alice = login("alice"); + String bob = login("bob"); + String admin = login("admin"); + reply = app.get("/invoices", alice); + row("alice", "GET /invoices", alice(reply), App.whose(reply.json()), expectOwn(reply, MERCHANT_A)); + reply = app.get("/invoices", bob); + row("bob", "GET /invoices", reply, App.whose(reply.json()), expectOwn(reply, MERCHANT_B)); + + section("BROKEN TOKENS: alice's claims, but every token here must get a 401"); + badToken("merchant_id edited to merchant-b", Forge.withClaimChanged(alice, "merchant_id", MERCHANT_B)); + badToken("alg none, no signature", forge.unsigned(forge.claims("alice", MERCHANT_A, List.of("USER")))); + badToken("signed with another key", forge.signWithAnotherKey(forge.claims("alice", MERCHANT_A, List.of("USER")))); + badToken("expired an hour ago", forge.expired("alice", MERCHANT_A, List.of("USER"))); + badToken("no merchant_id claim", forge.sign(forge.claims("alice", null, List.of("USER")))); + + section("OBJECT-LEVEL AUTHORISATION: is this invoice yours?"); + reply = app.get("/invoices/1", alice); + row("alice", "GET /invoices/1", alice(reply), App.whose(reply.json()), expectOwn(reply, MERCHANT_A)); + for (long id = 4; id <= 6; id++) { + reply = app.get("/invoices/" + id, alice); + row("alice", "GET /invoices/" + id, alice(reply), App.whose(reply.json()), expect(reply, 404, "LEAK")); + } + reply = app.get("/invoices/999", alice); + row("alice", "GET /invoices/999 (does not exist)", reply, App.whose(reply.json()), expect(reply, 404, "WRONG")); + + reply = app.put("/invoices/5", alice, "{\"customer\":\"Changed by alice\",\"amountCents\":1}"); + boolean changed = amountOf(5) == 1; + changedByAlice += changed ? 1 : 0; + row("alice", "PUT /invoices/5 {amountCents: 1}", reply, + changed ? "CHANGED invoice 5 of merchant-b" : "nothing changed", + changed ? "LEAK, want 404" : expect(reply, 404, "WRONG")); + + reply = app.delete("/invoices/6", alice); + boolean deleted = merchantOf(6) == null; + deletedByAlice += deleted ? 1 : 0; + row("alice", "DELETE /invoices/6", reply, + deleted ? "DELETED invoice 6 of merchant-b" : "nothing deleted", + deleted ? "LEAK, want 404" : expect(reply, 404, "WRONG")); + + section("TENANT FROM THE REQUEST: who decides which merchant you are?"); + reply = app.get("/invoices?merchantId=merchant-b", alice); + row("alice", "GET /invoices?merchantId=merchant-b", alice(reply), App.whose(reply.json()), + expectOwn(reply, MERCHANT_A)); + + reply = app.post("/invoices", alice, "{\"merchantId\":\"merchant-b\",\"status\":\"PAID\"," + + "\"number\":\"X-1\",\"customer\":\"Created by alice\",\"amountCents\":500}"); + row("alice", "POST /invoices {merchantId:merchant-b,status:PAID}", reply, created(reply), createdProblem(reply)); + + reply = app.post("/invoices", alice, "{\"id\":4,\"number\":\"X-2\",\"customer\":\"Created by alice\",\"amountCents\":500}"); + boolean takenOver = MERCHANT_A.equals(merchantOf(4)); + takenOverByAlice += takenOver ? 1 : 0; + row("alice", "POST /invoices {id: 4}", reply, + takenOver ? "invoice 4 moved to merchant-a" : created(reply), + takenOver ? "LEAK, want a new invoice" : expect(reply, 201, "WRONG")); + + section("ROLES: may you call this endpoint at all?"); + reply = app.get("/admin/invoices", bob); + if (reply.status() == 200) { + adminListSeenByBob = reply.json().size(); + } + row("bob", "GET /admin/invoices (bob is a USER)", reply, App.whose(reply.json()), expect(reply, 403, "LEAK")); + reply = app.get("/admin/invoices", admin); + adminLockedOut = reply.status() == 403; + row("admin", "GET /admin/invoices (admin is an ADMIN)", reply, App.whose(reply.json()), + adminLockedOut ? "LOCKED OUT, want 200" : expect(reply, 200, "WRONG")); + + printResult(); + } + + private String login(String username) { + String token = app.login(username); + row(username, "POST /login", 200, "a token, " + token.length() + " characters", null, + bodies ? "{\"token\":\"" + token + "\"}" : null); + return token; + } + + private void badToken(String what, String token) { + Reply reply = app.get("/invoices", token); + String problem = expect(reply, 401, "LET IN"); + if (problem != null) { + badTokensLetIn.add(what); + } + row("alice", "GET /invoices (" + what + ")", reply, App.whose(reply.json()), problem); + } + + /** Remembers every invoice of merchant-b that came back to alice. */ + private Reply alice(Reply reply) { + if (reply.status() == 200) { + JsonNode json = reply.json(); + List invoices = new ArrayList<>(); + if (json.isArray()) { + json.forEach(invoices::add); + } else { + invoices.add(json); + } + for (JsonNode invoice : invoices) { + if (MERCHANT_B.equals(invoice.path("merchantId").asString(""))) { + invoicesOfBReadByAlice.add(invoice.path("id").asLong()); + } + } + } + return reply; + } + + private String expect(Reply reply, int status, String label) { + if (reply.status() == status) { + return null; + } + if (reply.status() >= 500) { + otherProblems.add(reply.status() + " from a request that should have been a " + status); + return "SERVER ERROR, want " + status; + } + return label + ", want " + status; + } + + private String expectOwn(Reply reply, String merchant) { + String problem = expect(reply, 200, "WRONG"); + if (problem != null) { + return problem; + } + String whose = App.whose(reply.json()); + return whose.endsWith(" of " + merchant) ? null : "LEAK, want only " + merchant; + } + + private String created(Reply reply) { + if (reply.status() != 201) { + return "nothing"; + } + return "new invoice " + reply.json().path("id").asLong() + ", " + reply.json().path("merchantId").asString() + + ", " + reply.json().path("status").asString(); + } + + private String createdProblem(Reply reply) { + String problem = expect(reply, 201, "WRONG"); + if (problem != null) { + return problem; + } + String merchant = reply.json().path("merchantId").asString(); + String status = reply.json().path("status").asString(); + if (!MERCHANT_A.equals(merchant)) { + createdForBByAlice++; + } + if (!"DRAFT".equals(status)) { + statusFromTheBody = status; + } + if (!MERCHANT_A.equals(merchant)) { + return "LEAK, want merchant-a"; + } + return "DRAFT".equals(status) ? null : "WRONG, want DRAFT"; + } + + private void printResult() { + System.out.println(); + List results = new ArrayList<>(); + if (!invoicesOfBReadByAlice.isEmpty()) { + results.add("DATA LEAK. alice (merchant-a) read " + invoicesOfBReadByAlice.size() + " invoices of merchant-b: " + + invoicesOfBReadByAlice + "."); + } + List done = new ArrayList<>(); + if (changedByAlice > 0) { + done.add("changed " + changedByAlice); + } + if (deletedByAlice > 0) { + done.add("deleted " + deletedByAlice); + } + if (takenOverByAlice > 0) { + done.add("took over " + takenOverByAlice); + } + if (!done.isEmpty() || createdForBByAlice > 0) { + String text = "DATA CHANGED. alice (merchant-a) "; + if (!done.isEmpty()) { + text += String.join(", ", done.subList(0, done.size() - 1)) + (done.size() > 1 ? " and " : "") + + done.getLast() + " of merchant-b's invoices"; + } + if (createdForBByAlice > 0) { + text += (done.isEmpty() ? "" : ", and ") + "created " + createdForBByAlice + " in merchant-b's name"; + } + results.add(text + "."); + } + if (statusFromTheBody != null) { + results.add("MASS ASSIGNMENT. A new invoice took its status from the request body: " + statusFromTheBody + "."); + } + if (adminListSeenByBob >= 0) { + results.add("NO ROLE CHECK. bob (USER) read the admin list: " + adminListSeenByBob + " invoices of every merchant."); + } + if (adminLockedOut) { + results.add("ADMIN LOCKED OUT. admin has the ADMIN role and got 403 from /admin/invoices."); + } + if (!badTokensLetIn.isEmpty()) { + results.add("BAD TOKENS ACCEPTED. " + badTokensLetIn.size() + " of 5 tokens that must be refused got in: " + + String.join(", ", badTokensLetIn) + "."); + } + otherProblems.forEach(problem -> results.add("SERVER ERROR. " + problem + ".")); + if (results.isEmpty()) { + System.out.println("RESULT: OK. Bad tokens got 401, bob got 403 on /admin, other merchants' invoices got 404." + + " Nobody saw or changed data that was not theirs."); + } else { + results.forEach(result -> System.out.println("RESULT: " + result)); + } + System.out.println(); + } + + private void section(String title) { + System.out.println(); + System.out.println(title); + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", "who", "request", "status", "what came back", "verdict"); + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", "-----", "-".repeat(50), "------", "-".repeat(36), "-------"); + } + + private void row(String who, String request, Reply reply, String cameBack, String problem) { + row(who, request, reply.status(), cameBack, problem, bodies ? reply.body() : null); + if (bodies && !reply.wwwAuthenticate().isEmpty()) { + System.out.println(" WWW-Authenticate: " + App.ascii(reply.wwwAuthenticate())); + } + } + + private static void row(String who, String request, int status, String cameBack, String problem, String body) { + System.out.printf(" %-5s %-50s %-6s %-36s %s%n", who, request, status, cameBack, + problem == null ? "ok" : "<- " + problem); + if (body != null && !body.isBlank()) { + String text = App.ascii(body); + System.out.println(" body: " + (text.length() > 300 ? text.substring(0, 300) + "..." : text)); + } + } + + private long amountOf(long id) { + List amounts = app.jdbc().queryForList("select amount_cents from invoice where id = ?", Long.class, id); + return amounts.isEmpty() ? -1 : amounts.getFirst(); + } + + private String merchantOf(long id) { + List merchants = app.jdbc().queryForList("select merchant_id from invoice where id = ?", String.class, id); + return merchants.isEmpty() ? null : merchants.getFirst(); + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --sql print every SQL statement the application sends, above the row it belongs to"); + System.out.println(" --bodies print the response body under every row"); + System.out.println(); + System.out.println("Every run puts the six starting invoices back first. ./inspect shows a token and what it can see."); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Forge.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Forge.java new file mode 100644 index 0000000..0f659bd --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Forge.java @@ -0,0 +1,89 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.security.JwtProperties; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; +import com.nimbusds.jwt.SignedJWT; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * Makes the tokens a real login never hands out, the way an attacker (or a buggy client) would: + * edited after signing, unsigned, signed with another key, expired, missing a claim. Plain Java + * and the Nimbus library that Spring Security already uses: no other tool needed. + */ +final class Forge { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final JwtProperties properties; + + Forge(JwtProperties properties) { + this.properties = properties; + } + + /** The claims a login gives this user, valid from now for 15 minutes. */ + JWTClaimsSet.Builder claims(String username, String merchantId, List roles) { + Instant now = Instant.now(); + return new JWTClaimsSet.Builder() + .issuer(properties.issuer()) + .subject(username) + .issueTime(Date.from(now)) + .expirationTime(Date.from(now.plus(Duration.ofMinutes(15)))) + .claim("merchant_id", merchantId) + .claim("roles", roles); + } + + /** The same claims, but it expired an hour ago. Signed with the real key. */ + String expired(String username, String merchantId, List roles) { + Instant anHourAgo = Instant.now().minus(Duration.ofHours(1)); + return sign(claims(username, merchantId, roles) + .issueTime(Date.from(anHourAgo.minus(Duration.ofMinutes(15)))) + .expirationTime(Date.from(anHourAgo))); + } + + /** HS256 with the server's real key. */ + String sign(JWTClaimsSet.Builder claims) { + return signWith(claims, properties.secret().getBytes(StandardCharsets.UTF_8)); + } + + /** HS256 with a key the server has never seen. */ + String signWithAnotherKey(JWTClaimsSet.Builder claims) { + return signWith(claims, "an-attackers-own-key-the-server-never-saw".getBytes(StandardCharsets.UTF_8)); + } + + /** {"alg":"none"}: header.payload. with an empty signature. */ + String unsigned(JWTClaimsSet.Builder claims) { + return new PlainJWT(claims.build()).serialize(); + } + + /** Changes one claim in the payload of a real token and keeps its old signature. */ + static String withClaimChanged(String token, String claim, String value) { + String[] parts = token.split("\\.", -1); + ObjectNode payload = (ObjectNode) JSON.readTree(Base64.getUrlDecoder().decode(parts[1])); + payload.put(claim, value); + String edited = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(payload)); + return parts[0] + "." + edited + "." + parts[2]; + } + + private static String signWith(JWTClaimsSet.Builder claims, byte[] key) { + try { + SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build(), + claims.build()); + jwt.sign(new MACSigner(key)); + return jwt.serialize(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Inspect.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Inspect.java new file mode 100644 index 0000000..4a5b896 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/demo/Inspect.java @@ -0,0 +1,351 @@ +package com.amigoscode.authz.demo; + +import com.amigoscode.authz.demo.App.Reply; +import com.amigoscode.authz.login.UserAccounts; +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.Caller; +import com.nimbusds.jose.JWSObject; +import com.nimbusds.jose.crypto.MACVerifier; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtException; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Takes one token apart: header, claims, expiry, whether the signature matches, what Spring + * Security makes of it, and which invoices it can see compared with which exist. Only sends GET + * requests, so it changes nothing. Run it with ./inspect (or .\inspect on Windows). + */ +public final class Inspect { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final Map MEANING = Map.of( + "iss", "issuer: who made the token", + "sub", "subject: who the token is about", + "merchant_id", "which merchant this user works for", + "roles", "what this user may do", + "iat", "issued at", + "nbf", "not valid before", + "exp", "expires at"); + + private record Options(String user, String token, boolean expired, boolean algNone, String edit) { + } + + public static void main(String[] args) { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(App.ascii(e.getMessage())); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(false)) { + if (app != null) { + run(app, options); + } + } + } + + private static void run(App app, Options options) { + Integer invoices = app.jdbc().queryForObject("select count(*) from invoice", Integer.class); + if (invoices == null || invoices == 0) { + app.resetData(); + System.out.println(); + System.out.println("(The invoice table was empty, so the six starting invoices were loaded.)"); + } + + printUsers(app); + + String token; + String origin; + if (options.token() != null) { + token = options.token().strip(); + origin = "the token given with --token"; + } else { + UserAccount user = app.bean(UserAccounts.class).find(options.user()) + .orElseThrow(() -> new IllegalArgumentException("No user " + options.user())); + Forge forge = new Forge(app.jwtProperties()); + if (options.expired()) { + token = forge.expired(user.username(), user.merchantId(), user.roles()); + origin = user.username() + "'s claims, signed with the real key, expired an hour ago"; + } else if (options.algNone()) { + token = forge.unsigned(forge.claims(user.username(), user.merchantId(), user.roles())); + origin = user.username() + "'s claims with alg none and no signature"; + } else { + token = app.login(user.username()); + origin = "POST /login as " + user.username(); + } + if (options.edit() != null) { + String[] edit = options.edit().split("=", 2); + token = Forge.withClaimChanged(token, edit[0], edit[1]); + origin += ", then " + edit[0] + " edited to " + edit[1] + " (the signature was not redone)"; + } + } + + System.out.println(); + System.out.println("TOKEN (" + App.ascii(origin) + ")"); + System.out.println(" " + App.ascii(token)); + String[] parts = token.split("\\.", -1); + if (parts.length != 3) { + System.out.println(); + System.out.println(" Not a JWT: a JWT is three base64url parts separated by dots, header.payload.signature."); + System.out.println(" This has " + parts.length + " part" + (parts.length == 1 ? "" : "s") + "."); + } + JsonNode payload = null; + if (parts.length == 3) { + System.out.println(); + System.out.println("HEADER (part 1, base64url-decoded: no key needed, anyone can do this)"); + JsonNode header = decode(parts[0]); + System.out.println(" " + (header == null ? "(not base64url JSON)" : App.ascii(header.toString()))); + + System.out.println(); + System.out.println("PAYLOAD (part 2, base64url-decoded: no key needed, anyone can do this)"); + payload = decode(parts[1]); + if (payload == null) { + System.out.println(" (not base64url JSON)"); + } else { + System.out.println(" " + App.ascii(payload.toString())); + System.out.println(); + printClaims(payload); + } + + System.out.println(); + System.out.println("SIGNATURE (part 3)"); + System.out.println(" " + signature(token, parts, app)); + } + + System.out.println(); + System.out.println("WHAT SPRING SECURITY MAKES OF IT (the application's own JwtDecoder and JwtAuthenticationConverter)"); + Jwt jwt = null; + try { + jwt = app.bean(JwtDecoder.class).decode(token); + Caller caller = Caller.of(jwt); + List authorities = app.bean(JwtAuthenticationConverter.class).convert(jwt).getAuthorities().stream() + .map(GrantedAuthority::getAuthority).toList(); + System.out.println(" JwtDecoder: ACCEPTED. Requests with this token are authenticated."); + System.out.println(" Caller: username " + caller.username() + ", merchant " + caller.merchantId()); + System.out.println(" Authorities: " + (authorities.isEmpty() ? "(none)" : authorities) + + " <- what hasRole(...) and hasAuthority(...) look at"); + } catch (JwtException e) { + System.out.println(" JwtDecoder: REFUSED. Every request with this token gets a 401."); + System.out.println(" Reason: " + App.ascii(String.valueOf(e.getMessage()))); + } + + printWhatItCanSee(app, token, payload, jwt != null); + } + + private static void printUsers(App app) { + System.out.println(); + System.out.println("USERS (table app_user. The password is only ever stored as a bcrypt hash, and never put in a token)"); + List rows = new ArrayList<>(); + rows.add(new String[] {"username", "merchant_id", "roles", "password_hash"}); + app.jdbc().query("select username, merchant_id, roles, password_hash from app_user order by username", + (row, n) -> rows.add(new String[] {row.getString(1), row.getString(2), row.getString(3), + row.getString(4).substring(0, Math.min(24, row.getString(4).length())) + "..."})); + printTable(rows); + } + + private static void printClaims(JsonNode payload) { + List rows = new ArrayList<>(); + rows.add(new String[] {"claim", "value", "meaning"}); + for (Map.Entry claim : payload.properties()) { + JsonNode value = claim.getValue(); + String text = value.isString() ? value.asString() : value.toString(); + String meaning = MEANING.getOrDefault(claim.getKey(), ""); + if (value.isNumber() && List.of("iat", "nbf", "exp").contains(claim.getKey())) { + Instant at = Instant.ofEpochSecond(value.asLong()); + text = at + " (" + value.asLong() + ")"; + if (claim.getKey().equals("exp")) { + Duration left = Duration.between(Instant.now(), at); + meaning += left.isNegative() ? ": EXPIRED " + human(left.negated()) + " ago" : ": in " + human(left); + } + if (claim.getKey().equals("nbf") && at.isAfter(Instant.now())) { + meaning += ": NOT VALID YET, in " + human(Duration.between(Instant.now(), at)); + } + } + rows.add(new String[] {App.ascii(claim.getKey()), App.ascii(text), meaning}); + } + if (!payload.has("exp")) { + rows.add(new String[] {"exp", "(missing)", "this token never expires"}); + } + printTable(rows); + } + + private static String signature(String token, String[] parts, App app) { + if (parts[2].isEmpty()) { + JsonNode header = decode(parts[0]); + String alg = header == null ? "?" : header.path("alg").asString("?"); + return "EMPTY. The header says alg \"" + App.ascii(alg) + "\": nothing proves who made this token."; + } + try { + boolean matches = JWSObject.parse(token) + .verify(new MACVerifier(app.jwtProperties().secret().getBytes(StandardCharsets.UTF_8))); + return "HMAC-SHA256 of part 1 + \".\" + part 2, with the server's key (authz.jwt.secret, not shown):\n " + + (matches ? "MATCHES. This server made this token, and nobody changed it since." + : "DOES NOT MATCH. Made with another key, or changed after it was signed."); + } catch (Exception e) { + return "Cannot be checked: " + App.ascii(String.valueOf(e.getMessage())); + } + } + + private static void printWhatItCanSee(App app, String token, JsonNode payload, boolean accepted) { + String merchant = payload == null ? null : payload.path("merchant_id").asString(null); + System.out.println(); + System.out.println("INVOICES: every row that exists, and what GET /invoices/{id} answers with this token"); + List rows = new ArrayList<>(); + rows.add(new String[] {"id", "merchant_id", "number", "customer", "amount", "status", "updated_by", + "GET /invoices/{id}", ""}); + Map visible = new LinkedHashMap<>(); + List> invoices = app.jdbc().queryForList( + "select id, merchant_id, number, customer, amount_cents, status, updated_by from invoice order by id"); + for (Map invoice : invoices) { + long id = ((Number) invoice.get("id")).longValue(); + long cents = ((Number) invoice.get("amount_cents")).longValue(); + String owner = String.valueOf(invoice.get("merchant_id")); + int status = app.get("/invoices/" + id, token).status(); + String note = ""; + if (status == 200) { + visible.merge(owner, 1, Integer::sum); + note = owner.equals(merchant) ? "visible" : "visible <- NOT this token's merchant"; + } + rows.add(new String[] {String.valueOf(id), owner, String.valueOf(invoice.get("number")), + App.ascii(String.valueOf(invoice.get("customer"))), String.format("%d.%02d", cents / 100, cents % 100), + String.valueOf(invoice.get("status")), App.ascii(String.valueOf(invoice.get("updated_by"))), + String.valueOf(status), note}); + } + printTable(rows); + + int seen = visible.values().stream().mapToInt(Integer::intValue).sum(); + System.out.println(); + System.out.println(" This token can read " + seen + " of the " + invoices.size() + " invoices that exist" + + (visible.isEmpty() ? "." : ": " + visible.entrySet().stream() + .map(entry -> entry.getValue() + " of " + entry.getKey()).reduce((a, b) -> a + ", " + b).orElse("") + ".")); + if (!accepted) { + System.out.println(" (Nothing at all: the token was refused, so every request is a 401.)"); + } + + System.out.println(); + System.out.println("THE LIST ENDPOINTS with this token"); + for (String path : List.of("/invoices", "/invoices?merchantId=merchant-b", "/admin/invoices")) { + Reply reply = app.get(path, token); + System.out.printf(" GET %-34s %d %s%n", path, reply.status(), App.whose(reply.json())); + } + System.out.println(); + } + + private static JsonNode decode(String part) { + try { + return JSON.readTree(new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8)); + } catch (RuntimeException e) { + return null; + } + } + + private static String human(Duration duration) { + long seconds = duration.toSeconds(); + if (seconds < 60) { + return seconds + " s"; + } + if (seconds < 3600) { + return (seconds / 60) + " min " + (seconds % 60) + " s"; + } + return (seconds / 3600) + " h " + (seconds % 3600 / 60) + " min"; + } + + /** Prints rows as a plain text table. The first row is the header. */ + private static void printTable(List rows) { + int[] widths = new int[rows.getFirst().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("%-" + Math.max(1, 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 static Options parse(String[] args) { + String user = "alice"; + String token = null; + boolean expired = false; + boolean algNone = false; + String edit = null; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--user" -> user = value(args, ++i, "--user"); + case "--token" -> token = value(args, ++i, "--token"); + case "--expired" -> expired = true; + case "--alg-none" -> algNone = true; + case "--edit" -> { + edit = value(args, ++i, "--edit"); + if (!edit.matches("[a-z_]+=.*")) { + throw new IllegalArgumentException("--edit needs claim=value, for example --edit merchant_id=merchant-b"); + } + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + if (!List.of("alice", "bob", "admin").contains(user)) { + throw new IllegalArgumentException("--user must be alice, bob or admin, got: " + user); + } + if (token != null && (expired || algNone || edit != null)) { + throw new IllegalArgumentException("--token cannot be combined with --expired, --alg-none or --edit"); + } + return new Options(user, token, expired, algNone, edit); + } + + 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 void printHelp() { + System.out.println("Usage: ./inspect [options] (Windows: .\\inspect [options])"); + System.out.println(); + System.out.println(" --user alice (default), bob or admin: logs in and inspects that token"); + System.out.println(" --expired the same claims, signed with the real key, expired an hour ago"); + System.out.println(" --alg-none the same claims with alg none and no signature"); + System.out.println(" --edit = change one claim after signing, for example --edit merchant_id=merchant-b"); + System.out.println(" --token inspect any token, for example one copied from ./demo --bodies"); + System.out.println(); + System.out.println("Only sends GET requests: it changes nothing. ./demo puts the starting data back."); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/Invoice.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/Invoice.java new file mode 100644 index 0000000..e01cc86 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/Invoice.java @@ -0,0 +1,91 @@ +package com.amigoscode.authz.invoice; + +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; + +/** One invoice. It belongs to exactly one merchant. */ +@Entity +@Table(name = "invoice") +public class Invoice { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String merchantId; + + private String number; + + private String customer; + + private long amountCents; + + @Enumerated(EnumType.STRING) + private InvoiceStatus status; + + private String updatedBy; + + protected Invoice() { + } + + public Invoice(String merchantId, String number, String customer, long amountCents, InvoiceStatus status, + String updatedBy) { + this.merchantId = merchantId; + this.number = number; + this.customer = customer; + this.amountCents = amountCents; + this.status = status; + this.updatedBy = updatedBy; + } + + public void change(String customer, long amountCents, String updatedBy) { + this.customer = customer; + this.amountCents = amountCents; + this.updatedBy = updatedBy; + } + + public void setMerchantId(String merchantId) { + this.merchantId = merchantId; + } + + public void setStatus(InvoiceStatus status) { + this.status = status; + } + + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } + + public Long getId() { + return id; + } + + public String getMerchantId() { + return merchantId; + } + + public String getNumber() { + return number; + } + + public String getCustomer() { + return customer; + } + + public long getAmountCents() { + return amountCents; + } + + public InvoiceStatus getStatus() { + return status; + } + + public String getUpdatedBy() { + return updatedBy; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java new file mode 100644 index 0000000..52c4085 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceController.java @@ -0,0 +1,74 @@ +package com.amigoscode.authz.invoice; + +import com.amigoscode.authz.security.Caller; +import jakarta.validation.Valid; +import java.util.List; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.bind.annotation.DeleteMapping; +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.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.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * The merchant's own invoices. Every request here has already passed authentication: Spring + * Security checked the token before this class runs, and hands it over as {@code @AuthenticationPrincipal Jwt}. + */ +@RestController +@RequestMapping("/invoices") +public class InvoiceController { + + private final InvoiceService invoices; + + public InvoiceController(InvoiceService invoices) { + this.invoices = invoices; + } + + /** + * The web app calls GET /invoices. The support team's tool adds ?merchantId= to look at one + * merchant's invoices. + * + *

TODO Task 4: whose invoices these are must not be up to the caller. + */ + @GetMapping + public List list(@RequestParam(required = false) String merchantId, @AuthenticationPrincipal Jwt jwt) { + String merchant = merchantId != null ? merchantId : Caller.of(jwt).merchantId(); + return invoices.list(merchant).stream().map(InvoiceResponse::from).toList(); + } + + @GetMapping("/{id}") + public InvoiceResponse get(@PathVariable long id) { + return InvoiceResponse.from(invoices.get(id)); + } + + @PutMapping("/{id}") + public InvoiceResponse update(@PathVariable long id, @Valid @RequestBody UpdateInvoiceRequest change, + @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.update(id, change, Caller.of(jwt))); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(@PathVariable long id) { + invoices.delete(id); + } + + /** + * The JSON body is read straight into the entity. The support tool sends merchantId to create + * an invoice for a merchant; the web app leaves it out and gets the caller's own merchant. + * + *

TODO Task 4: the client decides far more here than it should. + */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public InvoiceResponse create(@RequestBody Invoice invoice, @AuthenticationPrincipal Jwt jwt) { + return InvoiceResponse.from(invoices.create(invoice, Caller.of(jwt))); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java new file mode 100644 index 0000000..1d1406c --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceNotFoundException.java @@ -0,0 +1,9 @@ +package com.amigoscode.authz.invoice; + +/** A 404. Thrown for an id that does not exist AND for an id that belongs to another merchant. */ +public class InvoiceNotFoundException extends RuntimeException { + + public InvoiceNotFoundException(long id) { + super("Invoice " + id + " not found"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java new file mode 100644 index 0000000..2d8dad8 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceRepository.java @@ -0,0 +1,12 @@ +package com.amigoscode.authz.invoice; + +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface InvoiceRepository extends JpaRepository { + + List findByMerchantIdOrderById(String merchantId); + + /** Every merchant's invoices. For /admin. */ + List findAllByOrderById(); +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java new file mode 100644 index 0000000..f4f3a71 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceResponse.java @@ -0,0 +1,11 @@ +package com.amigoscode.authz.invoice; + +/** What the API returns for an invoice. */ +public record InvoiceResponse(long id, String merchantId, String number, String customer, long amountCents, + InvoiceStatus status, String updatedBy) { + + public static InvoiceResponse from(Invoice invoice) { + return new InvoiceResponse(invoice.getId(), invoice.getMerchantId(), invoice.getNumber(), + invoice.getCustomer(), invoice.getAmountCents(), invoice.getStatus(), invoice.getUpdatedBy()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java new file mode 100644 index 0000000..354eca3 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceService.java @@ -0,0 +1,61 @@ +package com.amigoscode.authz.invoice; + +import com.amigoscode.authz.security.Caller; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * The invoices. Every request that reaches this class has a valid token: Spring Security has + * already checked who the caller is. + * + *

TODO Task 2: a valid token is not the same as "this invoice is yours". + */ +@Service +@Transactional +public class InvoiceService { + + private final InvoiceRepository invoices; + + public InvoiceService(InvoiceRepository invoices) { + this.invoices = invoices; + } + + @Transactional(readOnly = true) + public List list(String merchantId) { + return invoices.findByMerchantIdOrderById(merchantId); + } + + @Transactional(readOnly = true) + public Invoice get(long id) { + return invoices.findById(id).orElseThrow(() -> new InvoiceNotFoundException(id)); + } + + public Invoice update(long id, UpdateInvoiceRequest change, Caller caller) { + Invoice invoice = get(id); + invoice.change(change.customer(), change.amountCents(), caller.username()); + return invoice; + } + + public void delete(long id) { + invoices.delete(get(id)); + } + + /** Fills in what the client left out, and saves. */ + public Invoice create(Invoice invoice, Caller caller) { + if (invoice.getMerchantId() == null) { + invoice.setMerchantId(caller.merchantId()); + } + if (invoice.getStatus() == null) { + invoice.setStatus(InvoiceStatus.DRAFT); + } + invoice.setUpdatedBy(caller.username()); + return invoices.save(invoice); + } + + /** Every merchant. Only called from AdminController. */ + @Transactional(readOnly = true) + public List listAll() { + return invoices.findAllByOrderById(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java new file mode 100644 index 0000000..672e058 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/InvoiceStatus.java @@ -0,0 +1,5 @@ +package com.amigoscode.authz.invoice; + +public enum InvoiceStatus { + DRAFT, ISSUED, PAID +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java new file mode 100644 index 0000000..a28175f --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/invoice/UpdateInvoiceRequest.java @@ -0,0 +1,8 @@ +package com.amigoscode.authz.invoice; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; + +/** PUT /invoices/{id}: the two fields a merchant may change. */ +public record UpdateInvoiceRequest(@NotBlank String customer, @Positive long amountCents) { +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/BadLoginException.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/BadLoginException.java new file mode 100644 index 0000000..a72298a --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/BadLoginException.java @@ -0,0 +1,8 @@ +package com.amigoscode.authz.login; + +public class BadLoginException extends RuntimeException { + + public BadLoginException() { + super("Wrong username or password"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/LoginController.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/LoginController.java new file mode 100644 index 0000000..ac0637f --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/LoginController.java @@ -0,0 +1,45 @@ +package com.amigoscode.authz.login; + +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.TokenService; +import com.amigoscode.authz.security.TokenService.IssuedToken; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import java.time.Instant; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * POST /login {"username":"alice","password":"password"} returns a token. The only endpoint that + * needs no token. In a real system this is the identity provider's login page, not your API. + */ +@RestController +public class LoginController { + + public record LoginRequest(@NotBlank String username, @NotBlank String password) { + } + + public record LoginResponse(String token, String tokenType, Instant expiresAt) { + } + + private final UserAccounts users; + private final PasswordEncoder passwordEncoder; + private final TokenService tokens; + + public LoginController(UserAccounts users, PasswordEncoder passwordEncoder, TokenService tokens) { + this.users = users; + this.passwordEncoder = passwordEncoder; + this.tokens = tokens; + } + + @PostMapping("/login") + public LoginResponse login(@Valid @RequestBody LoginRequest request) { + UserAccount user = users.find(request.username()) + .filter(account -> passwordEncoder.matches(request.password(), account.passwordHash())) + .orElseThrow(BadLoginException::new); + IssuedToken token = tokens.issue(user.username(), user.merchantId(), user.roles()); + return new LoginResponse(token.value(), "Bearer", token.expiresAt()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/UserAccounts.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/UserAccounts.java new file mode 100644 index 0000000..3307a15 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/login/UserAccounts.java @@ -0,0 +1,29 @@ +package com.amigoscode.authz.login; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +/** The app_user table: username, bcrypt hash, merchant, roles. */ +@Repository +public class UserAccounts { + + public record UserAccount(String username, String passwordHash, String merchantId, List roles) { + } + + private final JdbcTemplate jdbc; + + public UserAccounts(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public Optional find(String username) { + return jdbc.query("select username, password_hash, merchant_id, roles from app_user where username = ?", + (row, n) -> new UserAccount(row.getString(1), row.getString(2), row.getString(3), + Arrays.stream(row.getString(4).split(",")).map(String::strip).toList()), + username) + .stream().findFirst(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/Caller.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/Caller.java new file mode 100644 index 0000000..c873388 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/Caller.java @@ -0,0 +1,15 @@ +package com.amigoscode.authz.security; + +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * Who is calling, taken from the token that Spring Security has already checked. The signature + * guarantees that nobody changed these values after login, which is why the merchant id must come + * from here and from nowhere else: not from the URL, not from a query parameter, not from the body. + */ +public record Caller(String username, String merchantId) { + + public static Caller of(Jwt jwt) { + return new Caller(jwt.getSubject(), jwt.getClaimAsString("merchant_id")); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/JwtProperties.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/JwtProperties.java new file mode 100644 index 0000000..3b51ecb --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/JwtProperties.java @@ -0,0 +1,29 @@ +package com.amigoscode.authz.security; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** authz.jwt.* from application.properties. */ +@ConfigurationProperties("authz.jwt") +public record JwtProperties(String secret, String issuer, Duration timeToLive) { + + public JwtProperties { + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) { + throw new IllegalArgumentException("authz.jwt.secret (or JWT_SECRET) must be at least 32 bytes for HS256"); + } + } + + /** The HMAC-SHA256 key. With HS256 the same key signs and checks, so whoever can check can also sign. */ + public SecretKey key() { + return new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + } + + /** Never print the secret, not even by accident in a log line. */ + @Override + public String toString() { + return "JwtProperties[secret=(hidden), issuer=" + issuer + ", timeToLive=" + timeToLive + "]"; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityConfig.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityConfig.java new file mode 100644 index 0000000..bd0d9c9 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityConfig.java @@ -0,0 +1,75 @@ +package com.amigoscode.authz.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtIssuerValidator; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import org.springframework.security.web.SecurityFilterChain; + +/** + * Authentication: every request except POST /login must carry a valid bearer token. Spring + * Security checks the token before any controller runs, and answers 401 when it is missing or not + * trusted. + */ +@Configuration +public class SecurityConfig { + + @Bean + public SecurityFilterChain api(HttpSecurity http, JwtAuthenticationConverter jwtAuthenticationConverter, + SecurityProblems problems) throws Exception { + http + // No cookies and no session: the browser never sends the token on its own, so there is + // nothing for a cross-site request to ride on. That is why CSRF protection can go. + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(requests -> requests + .requestMatchers(HttpMethod.POST, "/login").permitAll() + .requestMatchers("/error").permitAll() + .anyRequest().authenticated()) + .oauth2ResourceServer(resourceServer -> resourceServer + .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)) + .authenticationEntryPoint(problems) + .accessDeniedHandler(problems)) + .exceptionHandling(exceptions -> exceptions + .authenticationEntryPoint(problems) + .accessDeniedHandler(problems)); + return http.build(); + } + + /** + * Checks every token: the HS256 signature with our key, then the validators. Anything that + * fails is a 401 before the request reaches a controller. + * + *

TODO Task 6: an expired token still gets in, and so does a token without merchant_id. + */ + @Bean + public JwtDecoder jwtDecoder(JwtProperties properties) { + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(properties.key()) + .macAlgorithm(MacAlgorithm.HS256) + .build(); + // Only accept tokens that we issued ourselves. + decoder.setJwtValidator(new JwtIssuerValidator(properties.issuer())); + return decoder; + } + + /** Turns a checked token into Spring Security authorities. Spring's default. */ + @Bean + public JwtAuthenticationConverter jwtAuthenticationConverter() { + return new JwtAuthenticationConverter(); + } + + /** Checks the passwords in app_user. "{bcrypt}..." hashes, so the algorithm can change later. */ + @Bean + public PasswordEncoder passwordEncoder() { + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityProblems.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityProblems.java new file mode 100644 index 0000000..83223a9 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/SecurityProblems.java @@ -0,0 +1,73 @@ +package com.amigoscode.authz.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import java.util.TreeMap; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; +import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * The 401 and the 403. Both are decided by Spring Security's filters, before any controller runs, + * so ApiExceptionHandler never sees them. + * + *

Spring's own bearer-token handlers set the status and the WWW-Authenticate header (RFC 6750), + * and send no body. This class lets them do exactly that, then adds a ProblemDetail body in the + * same shape as every other error of this API. + * + *

401 Unauthorized means "I do not know who you are": no token, or a token I do not trust. + * 403 Forbidden means "I know who you are, and you may not do this". + */ +@Component +public class SecurityProblems implements AuthenticationEntryPoint, AccessDeniedHandler { + + private final AuthenticationEntryPoint bearerEntryPoint = new BearerTokenAuthenticationEntryPoint(); + private final AccessDeniedHandler bearerAccessDenied = new BearerTokenAccessDeniedHandler(); + private final JsonMapper json = JsonMapper.builder().build(); + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) + throws IOException, jakarta.servlet.ServletException { + bearerEntryPoint.commence(request, response, e); + String detail = switch (e) { + case OAuth2AuthenticationException oauth when oauth.getError().getDescription() != null -> + oauth.getError().getDescription(); + case InsufficientAuthenticationException ignored -> "No token. Send the header Authorization: Bearer ."; + default -> e.getMessage(); + }; + write(request, response, HttpStatus.UNAUTHORIZED, "Not authenticated", detail); + } + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) + throws IOException, jakarta.servlet.ServletException { + bearerAccessDenied.handle(request, response, e); + write(request, response, HttpStatus.FORBIDDEN, "Not allowed", + "Your token is valid, but it does not allow this request."); + } + + private void write(HttpServletRequest request, HttpServletResponse response, HttpStatus status, + String title, String detail) throws IOException { + // Same fields, in the same (alphabetical) order, as the ProblemDetail that Spring MVC writes. + Map problem = new TreeMap<>(); + problem.put("title", title); + problem.put("status", status.value()); + problem.put("detail", detail); + problem.put("instance", request.getRequestURI()); + response.setStatus(status.value()); + response.setCharacterEncoding("UTF-8"); + response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); + response.getWriter().write(json.writeValueAsString(problem)); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/TokenService.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/TokenService.java new file mode 100644 index 0000000..8194cc1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/java/com/amigoscode/authz/security/TokenService.java @@ -0,0 +1,55 @@ +package com.amigoscode.authz.security; + +import com.nimbusds.jose.jwk.source.ImmutableSecret; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.JwsHeader; +import org.springframework.security.oauth2.jwt.JwtClaimsSet; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.JwtEncoderParameters; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; +import org.springframework.stereotype.Service; + +/** + * Issues the tokens that POST /login hands out. In a real system this is the identity provider's + * job (Keycloak, Auth0, Cognito, Entra ID...), and it signs with a private key that this + * application never sees. Here it lives in the same application so the project needs nothing else. + */ +@Service +public class TokenService { + + public record IssuedToken(String value, Instant expiresAt) { + } + + private final JwtEncoder encoder; + private final JwtProperties properties; + private final Clock clock; + + public TokenService(JwtProperties properties, Clock clock) { + // One secret key, no key id. (An identity provider has several keys and puts a "kid" header + // in every token, so the checker knows which public key to use. That is how keys rotate.) + this.encoder = new NimbusJwtEncoder(new ImmutableSecret<>(properties.key())); + this.properties = properties; + this.clock = clock; + } + + /** Who you are (sub), which merchant you work for (merchant_id), what you may do (roles). Nothing secret. */ + public IssuedToken issue(String username, String merchantId, List roles) { + Instant now = clock.instant().truncatedTo(ChronoUnit.SECONDS); + Instant expiresAt = now.plus(properties.timeToLive()); + JwtClaimsSet claims = JwtClaimsSet.builder() + .issuer(properties.issuer()) + .subject(username) + .issuedAt(now) + .expiresAt(expiresAt) + .claim("merchant_id", merchantId) + .claim("roles", roles) + .build(); + JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).type("JWT").build(); + String token = encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue(); + return new IssuedToken(token, expiresAt); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/application.properties b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/application.properties new file mode 100644 index 0000000..d6adfc2 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/application.properties @@ -0,0 +1,24 @@ +spring.application.name=authorisation-and-jwt + +# Postgres from compose.yaml. Port 5453 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5453/invoices} +spring.datasource.username=${DB_USER:invoices} +spring.datasource.password=${DB_PASSWORD:invoices} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always + +# The key that signs and checks every token (HMAC-SHA256, so the same key does both). +# This default is a DEV-ONLY value, checked into a public repository on purpose: it is not a +# secret and must never be used anywhere real. Set JWT_SECRET to override it. A real key comes +# from a secret store (Vault, AWS Secrets Manager, a Kubernetes secret), never from a file in git. +# HS256 needs at least 32 bytes. +authz.jwt.secret=${JWT_SECRET:dev-only-not-a-secret-do-not-use-outside-your-laptop} +# Who issues the tokens. Tokens with any other "iss" are refused. +authz.jwt.issuer=https://login.example.com +# How long a token from POST /login stays valid. +authz.jwt.time-to-live=15m + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/reset.sql b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/reset.sql new file mode 100644 index 0000000..16ca8b7 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/reset.sql @@ -0,0 +1,10 @@ +-- The starting data: three invoices for each merchant. ./demo and every test begin from here. +truncate table invoice restart identity; + +insert into invoice (merchant_id, number, customer, amount_cents, status, updated_by) +values ('merchant-a', 'A-1001', 'Hill Road Florist', 12000, 'ISSUED', 'alice'), + ('merchant-a', 'A-1002', 'Garden Cafe', 7550, 'PAID', 'alice'), + ('merchant-a', 'A-1003', 'Bike Repair Shop', 31000, 'DRAFT', 'alice'), + ('merchant-b', 'B-2001', 'Riverside Gym', 99000, 'ISSUED', 'bob'), + ('merchant-b', 'B-2002', 'Book Corner', 4500, 'PAID', 'bob'), + ('merchant-b', 'B-2003', 'Town Dental Clinic', 120000, 'ISSUED', 'bob'); diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/schema.sql b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/schema.sql new file mode 100644 index 0000000..e79442d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/main/resources/schema.sql @@ -0,0 +1,30 @@ +-- Applied on every start. The invoices themselves are reset by reset.sql (./demo and the tests). + +create table if not exists app_user ( + username text primary key, + password_hash text not null, + merchant_id text not null, + roles text not null -- comma separated, for example USER,ADMIN +); + +create table if not exists invoice ( + id bigserial primary key, + merchant_id text not null, + number text not null, + customer text not null, + amount_cents bigint not null check (amount_cents > 0), + status text not null, + updated_by text not null +); + +create index if not exists invoice_merchant_id on invoice (merchant_id); + +-- Three demo users. The password of all three is "password", stored as a bcrypt hash. +insert into app_user (username, password_hash, merchant_id, roles) +values ('alice', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'merchant-a', 'USER'), + ('bob', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'merchant-b', 'USER'), + ('admin', '{bcrypt}$2a$10$s7qs9DawgqfWIUDQ99m6iOzLZ5pyxOLgYOf9SUx0JMCktcLeXMkaa', 'platform', 'USER,ADMIN') +on conflict (username) do update + set password_hash = excluded.password_hash, + merchant_id = excluded.merchant_id, + roles = excluded.roles; diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AdminRoleIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AdminRoleIT.java new file mode 100644 index 0000000..aff0284 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AdminRoleIT.java @@ -0,0 +1,71 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +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.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import tools.jackson.databind.JsonNode; + +/** Function-level authorisation: "may you call this endpoint at all?". /admin is for ROLE_ADMIN only. */ +@Tag("task5") +class AdminRoleIT extends IntegrationTest { + + @Autowired + private WebApplicationContext context; + + @Test + @DisplayName("Roles: bob (roles USER) calls GET /admin/invoices: 403 Forbidden, he is known but not allowed") + void userIsForbidden() { + Response response = api.get("/admin/invoices", tokenFor("bob")); + + assertThat(response.status()).as("status").isEqualTo(403); + assertThat(response.body()).as("body").doesNotContain("A-1001"); + } + + @Test + @DisplayName("Roles: admin (roles USER, ADMIN) calls GET /admin/invoices: 200 with the invoices of every merchant") + void adminSeesEveryMerchant() { + Response response = api.get("/admin/invoices", tokenFor("admin")); + + assertThat(response.status()).as("status").isEqualTo(200); + Set merchants = new HashSet<>(); + for (JsonNode invoice : response.json()) { + merchants.add(invoice.path("merchantId").asString()); + } + assertThat(merchants).as("merchants in the admin list").containsExactlyInAnyOrder("merchant-a", "merchant-b"); + } + + @Test + @DisplayName("Roles: GET /admin/invoices without a token is a 401, not a 403: nobody is signed in yet") + void noTokenIsUnauthorizedNotForbidden() { + assertThat(api.get("/admin/invoices", null).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Roles: MockMvc with spring-security-test's jwt(), no real token: a caller with only ROLE_USER gets 403") + void mockMvcJwtWithOnlyRoleUserIsForbidden() throws Exception { + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + + // jwt() puts a ready-made authentication in place: the JwtDecoder never runs, so this kind + // of test cannot catch a decoder that accepts expired tokens (Task 6). It does test the rule. + mvc.perform(get("/admin/invoices").with(jwt() + .jwt(token -> token.subject("bob").claim("merchant_id", "merchant-b").claim("roles", List.of("USER"))) + .authorities(new SimpleGrantedAuthority("ROLE_USER")))) + .andExpect(status().isForbidden()); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AuthenticationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AuthenticationIT.java new file mode 100644 index 0000000..bd6d82c --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/AuthenticationIT.java @@ -0,0 +1,79 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import com.amigoscode.authz.support.Tokens; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Authentication: "who are you?". These pass from the start. That is the point of Task 1: every + * request without a trustworthy token is already refused, and the API is still leaking data. + */ +@Tag("task1") +class AuthenticationIT extends IntegrationTest { + + @Test + @DisplayName("Authentication: no token is a 401 with a WWW-Authenticate: Bearer header") + void noTokenIsUnauthorized() { + Response response = api.get("/invoices", null); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").startsWith("Bearer"); + } + + @Test + @DisplayName("Authentication: the right password returns a token that works, a wrong password is a 401 with no token") + void loginGivesATokenOnlyForTheRightPassword() { + Response wrong = api.post("/login", null, "{\"username\":\"alice\",\"password\":\"guess\"}"); + Response right = api.post("/login", null, "{\"username\":\"alice\",\"password\":\"password\"}"); + + assertThat(wrong.status()).as("status for a wrong password").isEqualTo(401); + assertThat(wrong.json().has("token")).as("a token for a wrong password").isFalse(); + assertThat(right.status()).as("status for the right password").isEqualTo(200); + String token = right.json().path("token").asString(); + assertThat(api.get("/invoices", token).status()).as("GET /invoices with that token").isEqualTo(200); + } + + @Test + @DisplayName("Authentication: a token that is not a JWT at all is a 401 invalid_token") + void garbageIsUnauthorized() { + Response response = api.get("/invoices", "this-is-not-a-jwt"); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("error=\"invalid_token\""); + } + + @Test + @DisplayName("Authentication: a token signed with a different key is a 401") + void wrongKeyIsUnauthorized() { + String token = tokens.signWithAnotherKey(tokens.claims("alice", "merchant-a", "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Authentication: a token with alg none (no signature at all) is a 401") + void algNoneIsUnauthorized() { + String token = tokens.unsigned(tokens.claims("alice", "merchant-a", "USER", "ADMIN")); + + Response response = api.get("/invoices", token); + + assertThat(token).as("an alg none token ends with an empty signature").endsWith("."); + assertThat(response.status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Authentication: alice's real token with merchant_id edited to merchant-b afterwards is a 401, the signature no longer matches") + void editedTokenIsUnauthorized() { + String edited = Tokens.withClaimChanged(tokenFor("alice"), "merchant_id", "merchant-b"); + + Response response = api.get("/invoices", edited); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.body()).as("body").doesNotContain("B-200"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/Check.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/Check.java new file mode 100644 index 0000000..2e7f700 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/Check.java @@ -0,0 +1,114 @@ +package com.amigoscode.authz; + +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, 7 and 8 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: how tokens are made (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See it break: authentication already works"); + TASKS.put("2", "Task 2: Fix the IDOR: scope every invoice query to the caller's merchant"); + TASKS.put("4", "Task 4: Fix the tenant that comes from the request"); + TASKS.put("5", "Task 5: Fix the admin endpoint: a role check that really checks"); + TASKS.put("6", "Task 6: Fix token validation: expired tokens and missing claims"); + } + + 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/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java new file mode 100644 index 0000000..302966d --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/ObjectLevelAuthorisationIT.java @@ -0,0 +1,85 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Object-level authorisation: "is this invoice yours?". alice works for merchant-a (invoices 1 to + * 3), bob for merchant-b (invoices 4 to 6). Both have perfectly valid tokens. + */ +@Tag("task2") +class ObjectLevelAuthorisationIT extends IntegrationTest { + + @Test + @DisplayName("IDOR: alice reads her own invoice 1: 200") + void ownInvoiceIsReadable() { + Response response = api.get("/invoices/1", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(response.json().path("number").asString()).as("number").isEqualTo("A-1001"); + } + + @Test + @DisplayName("IDOR: alice asks for invoice 4 of merchant-b (and bob for invoice 1 of merchant-a): 404, and none of its data in the body") + void anotherMerchantsInvoiceIsNotFound() { + Response alice = api.get("/invoices/4", tokenFor("alice")); + Response bob = api.get("/invoices/1", tokenFor("bob")); + + assertThat(alice.status()).as("status of alice -> invoice 4").isEqualTo(404); + assertThat(alice.body()).as("body").doesNotContain("B-2001").doesNotContain("Riverside Gym"); + assertThat(bob.status()).as("status of bob -> invoice 1").isEqualTo(404); + assertThat(bob.body()).as("body").doesNotContain("A-1001").doesNotContain("Hill Road Florist"); + } + + @Test + @DisplayName("IDOR: alice updates invoice 5 of merchant-b: 404, and the invoice is unchanged in the database") + void anotherMerchantsInvoiceCannotBeChanged() { + Response response = api.put("/invoices/5", tokenFor("alice"), "{\"customer\":\"Changed by alice\",\"amountCents\":1}"); + + assertThat(response.status()).as("status").isEqualTo(404); + assertThat(amountOf(5)).as("amount of invoice 5 in the database").isEqualTo(4500); + } + + @Test + @DisplayName("IDOR: alice deletes invoice 6 of merchant-b: 404, and the invoice is still there") + void anotherMerchantsInvoiceCannotBeDeleted() { + Response response = api.delete("/invoices/6", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(404); + assertThat(merchantOf(6)).as("invoice 6 in the database").isEqualTo("merchant-b"); + } + + @Test + @DisplayName("IDOR: another merchant's invoice and an id that does not exist get exactly the same 404, so ids cannot be probed") + void anotherMerchantsInvoiceLooksLikeAnIdThatDoesNotExist() { + String alice = tokenFor("alice"); + + Response someoneElses = api.get("/invoices/4", alice); + Response missing = api.get("/invoices/999", alice); + + assertThat(someoneElses.status()).as("status for invoice 4 (exists, merchant-b)").isEqualTo(404); + assertThat(missing.status()).as("status for invoice 999 (does not exist)").isEqualTo(404); + assertThat(someoneElses.body().replace("/4", "/N").replace(" 4 ", " N ")) + .as("the two bodies, with the id taken out") + .isEqualTo(missing.body().replace("/999", "/N").replace(" 999 ", " N ")); + } + + @Test + @DisplayName("IDOR: alice can still update and delete her own invoices: 200 and 204") + void ownInvoicesCanStillBeChangedAndDeleted() { + String alice = tokenFor("alice"); + + Response updated = api.put("/invoices/2", alice, "{\"customer\":\"Garden Cafe Ltd\",\"amountCents\":8000}"); + Response deleted = api.delete("/invoices/3", alice); + + assertThat(updated.status()).as("PUT /invoices/2").isEqualTo(200); + assertThat(amountOf(2)).as("amount of invoice 2 in the database").isEqualTo(8000); + assertThat(deleted.status()).as("DELETE /invoices/3").isEqualTo(204); + assertThat(merchantOf(3)).as("invoice 3 in the database").isNull(); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/RolesConverterTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/RolesConverterTest.java new file mode 100644 index 0000000..2ae9367 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/RolesConverterTest.java @@ -0,0 +1,32 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.security.SecurityConfig; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; + +/** Unit test: no Spring context. What authorities does a checked token turn into? */ +@Tag("task5") +class RolesConverterTest { + + @Test + @DisplayName("Roles: a token with \"roles\": [\"USER\",\"ADMIN\"] becomes the authorities ROLE_USER and ROLE_ADMIN") + void rolesClaimBecomesRoleAuthorities() { + Jwt jwt = Jwt.withTokenValue("token") + .header("alg", "HS256") + .subject("admin") + .claim("merchant_id", "platform") + .claim("roles", List.of("USER", "ADMIN")) + .build(); + + List authorities = new SecurityConfig().jwtAuthenticationConverter().convert(jwt).getAuthorities() + .stream().map(GrantedAuthority::getAuthority).toList(); + + assertThat(authorities).as("authorities").contains("ROLE_USER", "ROLE_ADMIN"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java new file mode 100644 index 0000000..740b007 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TenantFromRequestIT.java @@ -0,0 +1,94 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.util.ArrayList; +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; + +/** + * The merchant comes from the token, never from the request. Not from a query parameter, not from + * the JSON body, and the body cannot set the id or the status either (mass assignment). + */ +@Tag("task4") +class TenantFromRequestIT extends IntegrationTest { + + private static final String NEW_INVOICE = "\"number\":\"A-1004\",\"customer\":\"Corner Shop\",\"amountCents\":2500"; + + @Test + @DisplayName("Tenant: GET /invoices as alice returns her 3 invoices, all of merchant-a") + void listReturnsOwnInvoices() { + Response response = api.get("/invoices", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(merchants(response.json())).as("merchant of every invoice returned") + .containsExactly("merchant-a", "merchant-a", "merchant-a"); + } + + @Test + @DisplayName("Tenant: GET /invoices?merchantId=merchant-b as alice still returns only merchant-a's invoices") + void merchantIdParameterIsIgnored() { + Response response = api.get("/invoices?merchantId=merchant-b", tokenFor("alice")); + + assertThat(response.status()).as("status").isEqualTo(200); + assertThat(merchants(response.json())).as("merchant of every invoice returned") + .containsExactly("merchant-a", "merchant-a", "merchant-a"); + } + + @Test + @DisplayName("Tenant: POST /invoices with merchantId merchant-b in the body creates the invoice for alice's own merchant-a") + void merchantIdInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{" + NEW_INVOICE + ",\"merchantId\":\"merchant-b\"}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("merchantId").asString()).as("merchantId in the response").isEqualTo("merchant-a"); + assertThat(invoicesOf("merchant-a")).as("invoices of merchant-a in the database").isEqualTo(4); + assertThat(invoicesOf("merchant-b")).as("invoices of merchant-b in the database").isEqualTo(3); + } + + @Test + @DisplayName("Mass assignment: POST /invoices with \"id\":4 in the body creates a new invoice and leaves invoice 4 of merchant-b alone") + void idInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{\"id\":4," + NEW_INVOICE + "}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("id").asLong()).as("id of the new invoice").isEqualTo(7); + assertThat(merchantOf(4)).as("merchant of invoice 4 in the database").isEqualTo("merchant-b"); + assertThat(amountOf(4)).as("amount of invoice 4 in the database").isEqualTo(99000); + } + + @Test + @DisplayName("Mass assignment: POST /invoices with \"status\":\"PAID\" in the body still creates a DRAFT") + void statusInTheBodyIsIgnored() { + Response response = api.post("/invoices", tokenFor("alice"), "{" + NEW_INVOICE + ",\"status\":\"PAID\"}"); + + assertThat(response.status()).as("status").isEqualTo(201); + assertThat(response.json().path("status").asString()).as("status of the new invoice").isEqualTo("DRAFT"); + } + + @Test + @DisplayName("Validation: POST /invoices without a customer, or with a negative amount, is a 400 (not a 500)") + void invalidInvoiceIsABadRequest() { + String alice = tokenFor("alice"); + + Response noCustomer = api.post("/invoices", alice, "{\"number\":\"A-1005\",\"amountCents\":2500}"); + Response negative = api.post("/invoices", alice, "{\"number\":\"A-1005\",\"customer\":\"Corner Shop\",\"amountCents\":-5}"); + + assertThat(noCustomer.status()).as("status without a customer").isEqualTo(400); + assertThat(negative.status()).as("status with a negative amount").isEqualTo(400); + assertThat(invoicesOf("merchant-a")).as("invoices of merchant-a in the database").isEqualTo(3); + } + + private static List merchants(JsonNode invoices) { + List merchants = new ArrayList<>(); + for (JsonNode invoice : invoices) { + merchants.add(invoice.path("merchantId").asString()); + } + return merchants; + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenServiceTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenServiceTest.java new file mode 100644 index 0000000..23ff6b1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenServiceTest.java @@ -0,0 +1,77 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.authz.security.JwtProperties; +import com.amigoscode.authz.security.TokenService; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unit tests: no Spring, no database, a fixed clock. They pin down what a token from POST /login + * looks like. They pass from the start and must keep passing. + */ +@Tag("baseline") +class TokenServiceTest { + + private static final Instant NOW = Instant.parse("2030-01-01T10:00:00Z"); + private static final JwtProperties PROPERTIES = new JwtProperties( + "dev-only-not-a-secret-just-for-this-unit-test", "https://login.example.com", Duration.ofMinutes(15)); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final TokenService tokens = new TokenService(PROPERTIES, Clock.fixed(NOW, ZoneOffset.UTC)); + + @Test + @DisplayName("Tokens: a login token is signed with HS256 and carries iss, sub, merchant_id, roles, iat and exp 15 minutes after iat") + void loginTokenHasTheExpectedHeaderAndClaims() { + String token = tokens.issue("alice", "merchant-a", List.of("USER")).value(); + + JsonNode header = part(token, 0); + JsonNode claims = part(token, 1); + + assertThat(header.path("alg").asString()).as("alg").isEqualTo("HS256"); + assertThat(header.path("typ").asString()).as("typ").isEqualTo("JWT"); + assertThat(claims.path("iss").asString()).as("iss").isEqualTo("https://login.example.com"); + assertThat(claims.path("sub").asString()).as("sub").isEqualTo("alice"); + assertThat(claims.path("merchant_id").asString()).as("merchant_id").isEqualTo("merchant-a"); + assertThat(claims.path("roles").get(0).asString()).as("roles").isEqualTo("USER"); + assertThat(claims.path("iat").asLong()).as("iat").isEqualTo(NOW.getEpochSecond()); + assertThat(claims.path("exp").asLong()).as("exp").isEqualTo(NOW.plus(Duration.ofMinutes(15)).getEpochSecond()); + } + + @Test + @DisplayName("Tokens: anyone can read the claims without the key (signed, not encrypted), so a token holds no password and no personal data") + void claimsAreReadableByAnyoneSoTheyHoldNothingSecret() { + String token = tokens.issue("alice", "merchant-a", List.of("USER")).value(); + + // Plain Base64, no key: this is all an attacker needs to read a token. + String payload = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1])); + + assertThat(payload).contains("\"merchant_id\":\"merchant-a\""); + assertThat(part(token, 1).propertyNames()) + .as("the only claims in a login token") + .containsExactlyInAnyOrder("iss", "sub", "iat", "exp", "merchant_id", "roles"); + } + + @Test + @DisplayName("Tokens: the signing key must be at least 32 bytes, because HS256 needs a 256-bit key") + void shortKeysAreRefused() { + assertThatThrownBy(() -> new JwtProperties("too-short", "https://login.example.com", Duration.ofMinutes(15))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("at least 32 bytes"); + } + + private static JsonNode part(String token, int index) { + return JSON.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[index])); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenValidationIT.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenValidationIT.java new file mode 100644 index 0000000..1c95dff --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/TokenValidationIT.java @@ -0,0 +1,71 @@ +package com.amigoscode.authz; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.authz.support.Api.Response; +import com.amigoscode.authz.support.IntegrationTest; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Every token here has a perfectly valid signature. What is wrong with it is inside. Nothing in + * these tests waits for a token to expire: the times are simply written in the past or the future. + */ +@Tag("task6") +class TokenValidationIT extends IntegrationTest { + + @Test + @DisplayName("Validation: a token that expired an hour ago is a 401 invalid_token, 'Jwt expired at ...'") + void expiredTokenIsUnauthorized() { + Instant anHourAgo = Instant.now().minus(Duration.ofHours(1)); + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER") + .issueTime(Date.from(anHourAgo.minus(Duration.ofMinutes(15)))) + .expirationTime(Date.from(anHourAgo))); + + Response response = api.get("/invoices", token); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("Jwt expired at"); + } + + @Test + @DisplayName("Validation: a token that is not valid yet (nbf one hour from now) is a 401") + void notYetValidTokenIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER") + .notBeforeTime(Date.from(Instant.now().plus(Duration.ofHours(1)))) + .expirationTime(Date.from(Instant.now().plus(Duration.ofHours(2))))); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token without merchant_id is a 401, not a 200 with an empty list") + void tokenWithoutMerchantIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", null, "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token without sub (nobody) is a 401") + void tokenWithoutSubjectIsUnauthorized() { + String token = tokens.sign(tokens.claims(null, "merchant-a", "USER")); + + assertThat(api.get("/invoices", token).status()).as("status").isEqualTo(401); + } + + @Test + @DisplayName("Validation: a token from another issuer is a 401, even though it is signed with our key") + void otherIssuerIsUnauthorized() { + String token = tokens.sign(tokens.claims("alice", "merchant-a", "USER").issuer("https://someone-else.example.com")); + + Response response = api.get("/invoices", token); + + assertThat(response.status()).as("status").isEqualTo(401); + assertThat(response.wwwAuthenticate()).as("WWW-Authenticate").contains("iss"); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Api.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Api.java new file mode 100644 index 0000000..de69211 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Api.java @@ -0,0 +1,70 @@ +package com.amigoscode.authz.support; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Real HTTP requests against the running application, with a real "Authorization: Bearer" header. + * Nothing is mocked: the token goes through the same filters as in production. + */ +public final class Api { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + /** What came back. {@code json} is an empty object when the body is not JSON. */ + public record Response(int status, String wwwAuthenticate, String body, JsonNode json) { + } + + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + public Api(int port) { + this.baseUrl = "http://localhost:" + port; + } + + public Response get(String path, String token) { + return send(request(path, token).GET()); + } + + public Response post(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json))); + } + + public Response put(String path, String token, String json) { + return send(request(path, token).header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json))); + } + + public Response delete(String path, String token) { + return send(request(path, token).DELETE()); + } + + private HttpRequest.Builder request(String path, String token) { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl + path)); + if (token != null) { + builder.header("Authorization", "Bearer " + token); + } + return builder; + } + + private Response send(HttpRequest.Builder request) { + try { + HttpResponse response = http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + JsonNode json; + try { + json = response.body().isBlank() ? JSON.createObjectNode() : JSON.readTree(response.body()); + } catch (RuntimeException notJson) { + json = JSON.createObjectNode(); + } + return new Response(response.statusCode(), + response.headers().firstValue("WWW-Authenticate").orElse(""), response.body(), json); + } catch (Exception e) { + throw new IllegalStateException("Request failed: " + e, e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/IntegrationTest.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/IntegrationTest.java new file mode 100644 index 0000000..090ec17 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/IntegrationTest.java @@ -0,0 +1,92 @@ +package com.amigoscode.authz.support; + +import com.amigoscode.authz.login.UserAccounts; +import com.amigoscode.authz.login.UserAccounts.UserAccount; +import com.amigoscode.authz.security.JwtProperties; +import com.amigoscode.authz.security.TokenService; +import javax.sql.DataSource; +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.core.io.ClassPathResource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They start the real application on a free port, against a real + * Postgres started by Testcontainers (Docker must be running), and send it real HTTP requests with + * real tokens. One container is shared by every test class. + * + *

Every test starts from src/main/resources/reset.sql: invoices 1 to 3 belong to merchant-a + * (alice), invoices 4 to 6 to merchant-b (bob). admin works for "platform" and has the ADMIN role. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private DataSource dataSource; + + @Autowired + private JwtProperties jwtProperties; + + @Autowired + private TokenService tokenService; + + @Autowired + private UserAccounts users; + + @Value("${local.server.port}") + private int port; + + protected Api api; + + protected Tokens tokens; + + @BeforeEach + void startingData() { + new ResourceDatabasePopulator(new ClassPathResource("reset.sql")).execute(dataSource); + api = new Api(port); + tokens = new Tokens(jwtProperties); + } + + /** The token POST /login would give this user, made by the application's own TokenService. */ + protected String tokenFor(String username) { + UserAccount user = users.find(username).orElseThrow(); + return tokenService.issue(user.username(), user.merchantId(), user.roles()).value(); + } + + /** The merchant an invoice belongs to, straight from the database, or null when it does not exist. */ + protected String merchantOf(long invoiceId) { + return jdbc.query("select merchant_id from invoice where id = ?", (row, n) -> row.getString(1), invoiceId) + .stream().findFirst().orElse(null); + } + + protected long amountOf(long invoiceId) { + return jdbc.queryForObject("select amount_cents from invoice where id = ?", Long.class, invoiceId); + } + + protected int invoicesOf(String merchantId) { + return jdbc.queryForObject("select count(*) from invoice where merchant_id = ?", Integer.class, merchantId); + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Tokens.java b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Tokens.java new file mode 100644 index 0000000..8f052a8 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/java/com/amigoscode/authz/support/Tokens.java @@ -0,0 +1,82 @@ +package com.amigoscode.authz.support; + +import com.amigoscode.authz.security.JwtProperties; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; +import com.nimbusds.jwt.SignedJWT; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * Makes the tokens a real login never hands out: expired ones, unsigned ones, ones signed with the + * wrong key, ones that were edited after signing. Good tokens come from the application's own + * TokenService (see IntegrationTest.tokenFor). + */ +public final class Tokens { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final JwtProperties properties; + + public Tokens(JwtProperties properties) { + this.properties = properties; + } + + /** The claims a login gives alice: valid from now for 15 minutes. Change what a test needs. */ + public JWTClaimsSet.Builder claims(String username, String merchantId, String... roles) { + Instant now = Instant.now(); + return new JWTClaimsSet.Builder() + .issuer(properties.issuer()) + .subject(username) + .issueTime(Date.from(now)) + .expirationTime(Date.from(now.plus(Duration.ofMinutes(15)))) + .claim("merchant_id", merchantId) + .claim("roles", List.of(roles)); + } + + /** HS256 with the server's own key: the signature is valid. */ + public String sign(JWTClaimsSet.Builder claims) { + return signWith(claims, properties.secret().getBytes(StandardCharsets.UTF_8)); + } + + /** HS256 with a key the server does not know. */ + public String signWithAnotherKey(JWTClaimsSet.Builder claims) { + return signWith(claims, "another-key-that-the-server-has-never-seen".getBytes(StandardCharsets.UTF_8)); + } + + /** {"alg":"none"}: no signature at all. "header.payload." with nothing after the last dot. */ + public String unsigned(JWTClaimsSet.Builder claims) { + return new PlainJWT(claims.build()).serialize(); + } + + /** Changes one claim in the payload and keeps the old signature, like an attacker would. */ + public static String withClaimChanged(String token, String claim, String value) { + String[] parts = token.split("\\."); + ObjectNode payload = (ObjectNode) JSON.readTree(Base64.getUrlDecoder().decode(parts[1])); + payload.put(claim, value); + String edited = Base64.getUrlEncoder().withoutPadding() + .encodeToString(JSON.writeValueAsBytes(payload)); + return parts[0] + "." + edited + "." + parts[2]; + } + + private static String signWith(JWTClaimsSet.Builder claims, byte[] key) { + try { + SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build(), + claims.build()); + jwt.sign(new MACSigner(key)); + return jwt.serialize(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/14-authorisation-and-jwt/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..7fd76f1 --- /dev/null +++ b/java/concepts/junior-mid/14-authorisation-and-jwt/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/15-equals-and-hashcode/INTERVIEW_TASKS.md b/java/concepts/junior-mid/15-equals-and-hashcode/INTERVIEW_TASKS.md new file mode 100644 index 0000000..8b1f75e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/INTERVIEW_TASKS.md @@ -0,0 +1,312 @@ +# Interview Tasks — equals and hashCode + +> **In `start/`, `./check` FAILS on purpose: 14 of 34 checks pass.** Tasks 2, 4, 5 and 7 turn the +> other 20 green. Tasks 1, 3, 6 and 8 are inspection tasks: you run things, look, and answer +> questions. + +Do the tasks in order. Every fix is followed by an inspection task: 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`. + +Tasks 1 to 4 are plain Java and need no Docker. Before Task 5: `docker compose up -d`. + +**Rules:** work in `start/`. Never edit, delete or disable a test. Do not add Lombok: write every +`equals` and `hashCode` by hand, so you know what Lombok would have written. Do not fix `Tag`: it +stays on `Object.equals` so you can compare against it. + +--- + +## Task 1: See It Break (10 min) + +**Story:** *The price service cannot find the price of `KEYBOARD-01`, although it is in the map. +The basket shows the same amount twice. And a customer cannot remove a keyboard from the cart after +changing its quantity. Before you change anything, reproduce all three.* + +**Steps:** +1. `./demo`. Two `Sku`s with the same code: what does `equals` say? What does `prices.get(b)` + return, and why is `List.contains` no better? +2. `./demo --scenario equals-only`. `Money` has an `equals`. Which calls work and which do not? + What does `List.contains` know that `HashSet` does not? +3. `./demo --scenario mutable`. Write down the `hashCode` before and after `changeQuantity(3)`. + Is the line in the cart or not? How can the same object be in a `HashSet` twice? +4. Open `Sku`, `Money` and `CartLine`. For each one, say which methods it inherits from `Object` + and which it overrides. +5. `./inspect` and `./inspect --scenario mutable`. Keep the output (copy it into a file): Task 3 + compares it with what the same commands print after your fixes. + +**Acceptance Criteria** (`./check 1`, already passing: these tests document the cause) +- [ ] You can say what `Object.equals` and `Object.hashCode` do +- [ ] You can explain why `List.contains` works for `Money` and `HashSet.add` does not +- [ ] You can explain how one object ends up in a `HashSet` twice +- [ ] `ObjectIdentityTest` passes + +**Hints:** +- A `List` only calls `equals`. A `HashSet` calls `hashCode` first, and `equals` only sometimes +- `./check 1` contains a test that counts the `equals` calls a `HashSet` makes + +--- + +## Task 2: Fix the Value Objects (15 min) + +**Story:** *A SKU is a value: `KEYBOARD-01` is `KEYBOARD-01`, whichever object holds it. The same +goes for 89.00 EUR. Make `Sku` and `Money` behave like values in every collection.* + +**Acceptance Criteria** (`./check 2`) +- [ ] Two Skus with the same code are equal and have the same `hashCode` — `SkuTest.sameCodeIsEqual` +- [ ] `list.contains` and `map.get` find an equal Sku — `SkuTest.lookupsFindAnEqualSku` +- [ ] A `HashSet` keeps one of two equal Skus — `SkuTest.setKeepsOne` +- [ ] A Sku is not equal to another code, to `null` or to a `String` — `SkuTest.notEqualToOtherThings` + (already passing: keep it that way) +- [ ] Equal `Money` has equal hash codes, also `10.5` and `10.50` — `MoneyTest.equalMoneyHasEqualHashCodes` +- [ ] `HashSet` and `HashMap` agree with `Money.equals` — `MoneyTest.hashCollectionsAgreeWithEquals` +- [ ] `./demo` and `./demo --scenario equals-only` print `RESULT: OK` + +**Hints:** +- One of the two classes can stop being a class +- `hashCode` must use the same fields as `equals`, no more +- Why does the `Money` constructor call `setScale(2)`? What would `new BigDecimal("10.5").equals(new BigDecimal("10.50"))` say? + +--- + +## Task 3: Inspect the Hash Table (15 min) + +**Story:** *The tests are green. Now show what a `HashSet` really does with your objects.* + +**Steps:** +1. Take the `./inspect` output you kept in Task 1. In which buckets are the two `Money` objects? + When `contains(c)` runs, which bucket does it look in, and is `equals` called at all? +2. Run `./inspect` again, with your fix. How many elements now? Which line of the lookup calls + `equals`? +3. `./inspect --scenario collision`. `"Aa"` and `"BB"` have the same hash. Where are they? What + happens during `contains("BB")`? +4. In the `./inspect --scenario mutable` output from Task 1, compare "hash when added" with + "hashCode() now" for the keyboard. Where does the lookup go, and what does it find there? +5. A table has 16 buckets. Your hash codes are 32-bit numbers. How does `HashMap` get from one to + the other? (Read `Buckets.bucketOf`.) + +**Acceptance Criteria** (`./check 3`, already passing: these tests document the contract) +- [ ] You can state the contract in two sentences: what equal objects must have, and what the same + hash does not mean +- [ ] You can explain why a lookup with the wrong hash never even calls `equals` +- [ ] You can explain why a constant `hashCode` is legal and still a bad idea for a big set +- [ ] You can say why a `HashSet` does not notice that an element's hash changed + +--- + +## Task 4: Fix the Keys That Change (20 min) + +**Story:** *Two more ways to lose a key. A cart line's quantity changes while it is in the cart. +And the bundle price table loses "Desk set" after somebody reuses a list. Fix `CartLine` and +`Bundle` so that nothing a caller does can change their hash while they are in a set or a map.* + +**Acceptance Criteria** (`./check 4`) +- [ ] After the quantity changes the cart still contains the line, and remove takes it out + — `CartLineTest.stillFoundAfterTheQuantityChanges` +- [ ] Adding the same line again does not put it in the cart twice — `CartLineTest.notAddedTwice` +- [ ] `hashCode` does not change with the quantity — `CartLineTest.hashCodeDoesNotChange` +- [ ] Two bundles with the same name and SKUs are equal — `BundleTest.recordsWriteEqualsAndHashCode` + (already passing: the record writes it) +- [ ] Changing the caller's list does not change the bundle, and its price is still found + — `BundleTest.theCallersListCannotChangeTheBundle` +- [ ] `skus()` cannot be changed — `BundleTest.skusCannotBeChanged` +- [ ] A record with an array is compared by identity — `BundleTest.arraysInRecordsCompareByIdentity` + (already passing: it documents the trap) +- [ ] `./demo --scenario mutable` and `./demo --scenario record` print `RESULT: OK` +- [ ] `./inspect --scenario mutable` shows no `WRONG BUCKET` + +**Hints:** +- What makes a cart line *this* line? Could the cart hold two lines for the same SKU? +- A record's fields are `final`. A `final` field that points at an `ArrayList` is not immutable +- A record can have a compact constructor: `public Bundle { ... }` + +--- + +## Task 5: Fix the Line Items (20 min) + +**Story:** *Two bug reports from production. "I ordered a keyboard and a mouse, the confirmation +shows only the keyboard." And "the headset was out of stock and removed from my order, and I was +still charged for it." Both orders were placed by `OrderService.placeOrder`. Fix `LineItem`. +Leave `OrderService` as it is.* + +`docker compose up -d` first. + +**Acceptance Criteria** (`./check 5`) +- [ ] Two new items added before the save are both saved — `LineItemIT.twoNewItemsAreBothSaved` +- [ ] An out-of-stock line removed after the save is deleted — `LineItemIT.removedAfterTheSave` +- [ ] An item is still found in `order.getItems()` after the save gave it an id + — `LineItemIT.stillFoundAfterTheIdIsAssigned` +- [ ] The same row loaded in two transactions gives two equal objects + — `LineItemIT.sameRowInTwoTransactionsIsEqual` (already passing: keep it that way) +- [ ] An item is equal to a Hibernate proxy of the same row, without loading the row + — `LineItemIT.equalToItsProxyWithoutLoadingIt` +- [ ] `./demo --scenario new-items` and `./demo --scenario remove-item` print `RESULT: OK` + +**Hints:** +- Run both demo scenarios first, and `./inspect --scenario remove-item`: keep that output for + Task 6. What is the id of a `LineItem` before the save? And after? +- `Objects.equals(null, null)` is `true` +- A line item has no business key: the same product can be ordered twice in two lines. What is + left that never changes while the item is in the `Set`? +- `getClass()` of a Hibernate proxy is not `LineItem.class` + +--- + +## Task 6: Inspect the Persistence Context (15 min) + +**Story:** *Why do so many entities get away with no `equals` at all? And where does that stop?* + +**Steps:** +1. Take the `./inspect --scenario remove-item` output you kept in Task 5, from before your fix. + Read step 2: which bucket is the item in, and which bucket does `remove` look in? Read step 3: + which SQL did the flush send? Which rows are left? +2. The same in your fixed version. What changed in the bucket table? Which SQL did the flush send? +3. `./inspect --scenario new-items`. Which hash do the two items have, before and after the save? + (In `start/` the same command shows one element before the save, and after it one item with an + id and one with `null`, and only one of them in the persistence context.) +4. Open `PersistenceContextIT`. `Tag` has no `equals`. Why does + `keyboard.getTags().contains(gamingNow)` work and `contains(gamingFromEarlier)` not? +5. `./inspect --scenario proxy`. Which entity is a proxy? Which calls send SQL, which do not? Why is + the field `proxy.sku` still `null` after the row is loaded? + +**Acceptance Criteria** (`./check 6`, already passing: these tests document the guarantee) +- [ ] You can say what Hibernate guarantees about Java objects and rows inside one transaction +- [ ] You can name two ways an entity reaches you from outside that guarantee (another transaction, + a cache, a detached object, an HTTP session, a test) +- [ ] You can explain why `Object.equals` is enough for `Tag`, and when it would stop being enough +- [ ] You can say what a Hibernate proxy is, and which methods on it load the row + +--- + +## Task 7: Fix the Product (20 min) + +**Story:** *Somebody generated `equals` and `hashCode` for `Product` with every field ticked "to be +safe": the same fields Lombok's `@Data` would use. Since then, a report that puts products in a +`Set` sends hundreds of extra queries, a batch job dies with `LazyInitializationException`, and the +"is the featured product in this order?" check is always false. Fix `Product`.* + +**Acceptance Criteria** (`./check 7`) +- [ ] Putting loaded products in a `HashSet` sends no SQL — `ProductIT.hashingSendsNoSql` +- [ ] Products from a finished transaction can be put in a `HashSet` — `ProductIT.hashingWorksAfterTheTransaction` +- [ ] A product equals a proxy of the same row, both ways — `ProductIT.equalToItsProxyBothWays` +- [ ] The products of an order (proxies) contain the catalogue's product — `ProductIT.foundAmongTheProductsOfAnOrder` +- [ ] A new product is still found in its `HashSet` after the save — `ProductIT.stillFoundAfterTheIdIsAssigned` +- [ ] A price change does not change `hashCode` — `ProductTest.priceChangeDoesNotLoseIt` +- [ ] `./demo --scenario lazy` and `./demo --scenario proxy` print `RESULT: OK` +- [ ] All earlier checks still pass (`./check`) + +**Hints:** +- Run both demo scenarios. Which field makes the extra queries? Which line makes `equals` false + before it compares anything? +- A product has something a line item does not: a key the business already uses, unique, known + before the save, never changed +- On a proxy, `other.sku` and `other.getSku()` are not the same thing. Try both +- Hibernate has an annotation that says "this column is the business key and it never changes" + +--- + +## Task 8: Compare the Patterns (15 min) + +**Story:** *"How do you write `equals` and `hashCode` for an entity?" is the interview question. +There are three good answers and the right one depends on the class. Collect the evidence, then +answer for every class in this project.* + +**Steps:** +1. For each of `Sku`, `Money`, `CartLine`, `Bundle`, `Order`, `LineItem`, `Product` and `Tag`, write + down: which fields `equals` uses, and why it is safe for that class. +2. `./inspect --scenario new-items` in your fixed version. Where do the two line items sit? What + would a `HashSet` of 100,000 line items cost on every `contains`? +3. Change `LineItem.equals` to use `other.id` instead of `other.getId()` and run `./check 5`. Which + test fails, and why? Put it back. +4. Change `Product.equals` to `getClass() != o.getClass()` (keep the rest). Run `./check 7`. Then try + `Hibernate.getClass(this) != Hibernate.getClass(o)`. Which tests pass now, and what does + `./inspect --scenario proxy` say `Hibernate.getClass` costs? Put `instanceof` back. +5. Why does `Order` not override `equals` at all, and is that a problem? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can give the three ways to write `equals` for an entity, and when each is right +- [ ] You can explain the cost of the constant `hashCode`, and why it is usually acceptable +- [ ] You can explain why entity `equals` must use getters and `instanceof` (or `Hibernate.getClass`) +- [ ] You can say why a business key must be immutable, and how Hibernate enforces it + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- What is the contract between `equals` and `hashCode`? (If two objects are equal according to + `equals`, they must return the same `hashCode`. The reverse is not required: two different + objects may have the same hash. Also, `hashCode` must return the same value as long as the fields + `equals` uses do not change.) +- What happens if you override `equals` but not `hashCode`? (Equal objects get different identity + hash codes, so they land in different buckets. A `HashSet` keeps both, and `HashMap.get` with an + equal key returns `null`. A `List` still works, because it only calls `equals`. That is why the + bug often survives the first tests.) +- And `hashCode` without `equals`? (Equal objects land in the same bucket, then `Object.equals` + compares them with `==` and says no. Same result: duplicates and missed lookups.) +- Can two different objects have the same `hashCode`? (Yes. `"Aa"` and `"BB"` both hash to 2112. + The set puts both in the same bucket and tells them apart with `equals`. Collisions only cost + speed.) +- Why must a field in `hashCode` not change while the object is in a `HashSet`? (The set picks the + bucket once, when the element is added, and never moves it. After the change, `contains` and + `remove` compute a different hash, look in a different bucket, and do not find it. The object is + still in the set, unreachable. Adding it again puts the same object in twice.) +- Do records solve this? (For value objects, mostly: a record writes `equals`, `hashCode` and + `toString` from its components, and its fields are final. But it compares each component with + that component's own `equals`. A `List` component can still be changed by whoever passed it in, + so copy it with `List.copyOf`. An array component is compared with `==`, so two records with + equal arrays are not equal: use a `List`, or override `equals` and `hashCode` with + `Arrays.equals` and `Arrays.hashCode`.) +- Why is an `equals` on the generated id wrong for a JPA entity? (Before the save the id is + `null`. With `Objects.equals(id, other.id)` every new entity is equal to every other new entity, + so a `Set` keeps only one. And the id is assigned during the save, so `Objects.hash(id)` changes + while the entity is in a `Set`, and it is lost there: `remove` returns `false` and + `orphanRemoval` never deletes the row.) +- How do you write it then? (If the entity has a business key that is unique, always set and never + changed, like a SKU or an ISBN: use only that, and mark it `@NaturalId`. If it has none: equal + only when both ids are non-null and the same, and a `hashCode` that is the same for every + instance, so it cannot change when the id is assigned. Or do not override at all, if objects + from different transactions are never compared.) +- What is the cost of a constant `hashCode`? (Every instance lands in the same bucket, so a lookup + compares with every element: O(n). For the dozens of items in one association that does not + matter. For a `Set` of a million entities it does, and that is a sign you wanted a business key + or a `Map` by id.) +- Why not Lombok's `@Data` or `@EqualsAndHashCode` on an entity? (It uses every field. That + includes the generated id, so the hash changes on save; mutable fields like a price, so the hash + changes on update; and lazy associations, so `hashCode` runs a query per entity, or throws + `LazyInitializationException` outside a transaction. On a bidirectional association the two + sides call each other's `hashCode` until `StackOverflowError`. If you use Lombok on entities, use + `@Getter` and `@Setter` and write `equals` by hand, or `@EqualsAndHashCode(onlyExplicitlyIncluded = true)` + with `@EqualsAndHashCode.Include` on the business key.) +- Why `instanceof` and not `getClass()`? (Hibernate returns a lazy reference as a proxy, a + generated subclass such as `Product$HibernateProxy`. `getClass()` of the proxy is not + `Product.class`, so a `getClass()` check says the same row is a different object. + `instanceof Product` is true for the proxy. `Hibernate.getClass(o)` also works, but it loads the + row to find the real class.) +- Why `other.getSku()` and not `other.sku`? (A proxy is an empty subclass instance: its own fields + are never filled in, not even after the row is loaded. Only method calls are forwarded to the + real object behind it. `other.sku` on a proxy is `null`.) +- Is `Object.equals` ever enough for an entity? (Yes, inside one persistence context: Hibernate + guarantees one Java object per row there, so `==` and identity are correct. It stops working + when objects from two transactions meet: a cached product, a detached entity merged back, an + object kept in the HTTP session, an object from a test's setup transaction.) + +## Tips for Interviewers + +- The most common answer is the contract recited correctly and nothing else. Ask what a `HashSet` + does on `contains`, in order. A candidate who knows the hash picks the bucket can derive every + bug in this project from that. +- Ask the candidate to predict `./demo --scenario mutable` before running it, especially the last + line: the same object in a `HashSet` twice surprises almost everyone. +- In Task 5, the usual first attempt is `id != null && id.equals(other.id)` with + `hashCode = Objects.hash(id)`. It fixes the missing item and keeps the lost one. Ask what + `hashCode` returns before and after the save. +- Ask why `LineItem` and `Product` use different patterns. "Because one has a business key and the + other does not" is the answer that separates levels. +- For senior candidates: what does a constant `hashCode` cost, why is it acceptable here, and what + would you do for an entity that is put in very large sets? What does `@NaturalId` give you beyond + documentation (immutability checks, `bySimpleNaturalId`, the natural-id cache)? diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/README.md b/java/concepts/junior-mid/15-equals-and-hashcode/README.md new file mode 100644 index 0000000..197cf66 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/README.md @@ -0,0 +1,191 @@ +# equals and hashCode — Value Objects and JPA Entities + +> **In `start/`, `./check` FAILS on purpose: 14 of 34 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5 and 7 turn the other 20 green. + +A customer puts a keyboard in the cart, changes the quantity to 3, and clicks "remove". The cart +says it removed nothing, and the keyboard stays. An order with two lines is saved with one. An +out-of-stock headset is removed from an order and is still in the database. Nothing throws, nothing +is logged. Every one of these is an `equals` or a `hashCode` that breaks a rule `HashSet` relies on. + +This project lets you watch each one happen, first in plain Java and then on JPA entities with real +Hibernate and Postgres, fix it, and look inside the `HashSet` to see where the object went. + +It answers the interview questions students most often get wrong: + +- "What is the contract between `equals` and `hashCode`? What happens if you override only one?" +- "Can two objects with the same `hashCode` be different? Can two equal objects have different ones?" +- "Why should a field that can change not be part of `hashCode`?" +- "Do records solve this?" +- "How do you write `equals` and `hashCode` for a JPA entity? Why not use the id? Why not + Lombok's `@Data`?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (**Hibernate 7**) +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers + +## What you need + +- JDK 25 +- Docker, running. **Only for Tasks 5 to 7** (the JPA part). Tasks 1 to 4 are plain Java: their + `./demo` and `./inspect` scenarios and their checks run without Docker. + +## 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 +./demo # two Skus with the same code are not equal +./check # 14 of 34 pass: that is your starting point +docker compose up -d # Postgres on port 5454, for the JPA scenarios (Tasks 5 to 7) +./demo --scenario new-items +``` + +The first run downloads Maven and the dependencies, so it takes a minute or two. + +`./check 1` to `./check 4` need no Docker. The other checks start their own Postgres with +Testcontainers, so Docker must be running for them. When you are finished: `docker compose down`. + +## The three tools + +### `./demo` — see what happens + +Runs one scenario and prints every call it makes and what that call returned, then a `RESULT:` +line. The database scenarios start the real application against the Postgres from `compose.yaml` +and put the data back to the same three products first, so every run starts from the same state. +If Postgres is not running, they say so and tell you how to start it. + +``` +./demo no-equals: two equal-looking Skus +./demo --scenario mutable one scenario per problem, see the list below +./demo --help +``` + +| Scenario | Needs Docker | What goes wrong | Tasks | +|---|---|---|---| +| `no-equals` | no | `Sku` has no `equals`: two Skus with the same code are two keys | 1, 2 | +| `equals-only` | no | `Money` has `equals` but no `hashCode`: a `HashSet` keeps both of two equal amounts | 1, 2, 3 | +| `mutable` | no | a `CartLine` changes while it is in a `HashSet`: `contains` and `remove` cannot find it | 1, 4 | +| `record` | no | a record keeps the caller's list: the caller changes it and the `Map` key is lost | 4 | +| `new-items` | yes | two new line items, both with id `null`, are "equal": one is never saved | 5, 6 | +| `remove-item` | yes | the save assigns the id, the `hashCode` changes, and `remove` cannot find the item | 5, 6 | +| `lazy` | yes | an all-fields `hashCode` reads a lazy collection: a query per product, or `LazyInitializationException` | 7 | +| `proxy` | yes | a product and a Hibernate proxy of the same row are not equal | 7 | + +### `./inspect` — look inside the `HashSet` + +A `HashSet` is a table of buckets. `./inspect` reads the real table (with reflection) and prints, +for every element, the bucket it sits in, the hash it had **when it was added**, the hash it has +**now**, and the bucket a lookup would go to today. Then it walks one lookup step by step: which +bucket, which hashes were compared, when `equals` was called. + +For the database scenarios it also prints the rows in `line_item` next to the objects in the +order's `Set`, and the persistence context: every entity Hibernate holds for the transaction, and +whether it is a real object or a proxy. + +``` +./inspect equals-only: two equal amounts in two buckets +./inspect --scenario collision "Aa" and "BB": same hash, not equal +./inspect --scenario mutable the same list of scenarios as ./demo, plus collision +./inspect --scenario remove-item +./inspect --scenario proxy +``` + +### `./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 (`*Test` are unit tests in plain Java, +`*IT` are integration tests against a Postgres started by Testcontainers). + +The tests are the acceptance criteria. **Never edit, delete or disable a test.** None of them +measures time: they check what `equals`, `hashCode`, the `Set` and the database say. + +## The code + +``` +start/src/main/java/com/amigoscode/equality/ +├── value/ +│ ├── Sku.java a product code. No equals, no hashCode (Task 2) +│ ├── Money.java amount + currency. equals, no hashCode (Task 2) +│ └── Bundle.java a record used as a Map key (Task 4) +├── cart/ +│ ├── CartLine.java SKU + quantity, quantity in hashCode (Task 4) +│ └── Cart.java a HashSet of lines. Nothing to change here +├── order/ +│ ├── Order.java @OneToMany Set, orphanRemoval. Nothing to change here +│ ├── LineItem.java equals and hashCode on the generated id (Task 5) +│ └── OrderService.java placeOrder: save, then drop out-of-stock lines. Nothing to change here +├── product/ +│ ├── Product.java all-fields equals and hashCode, lazy tags (Task 7) +│ └── Tag.java no equals: Object identity. Exhibit, do not fix +├── db/ resetting the data, recording SQL. Nothing to change here +└── demo/ the demo and inspect tools. Nothing to change here +``` + +Every class you change has a `TODO Task N` comment at the line that matters. + +The data: three products (`KEYBOARD-01`, `MOUSE-01`, and `HEADSET-01`, which is out of stock), +three tags, and no orders. `./demo`, `./inspect` and every integration test put it back first. + +## 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 it break: equal-looking objects that are not equal, and an object lost in a `HashSet` | `./check 1` (passes: it documents the cause) | +| 2 | Fix the value objects: `Sku` and `Money` | `./check 2` | +| 3 | Inspect the hash table: buckets, the contract, collisions | `./check 3` (passes: it documents the contract) | +| 4 | Fix the keys that change: `CartLine` and the `Bundle` record | `./check 4` | +| 5 | Fix the line items: an entity whose id the database assigns | `./check 5` (Docker) | +| 6 | Inspect the persistence context: one object per row, and where that stops | `./check 6` (passes: it documents the guarantee) | +| 7 | Fix the product: all-fields equals, lazy loading and proxies | `./check 7` (Docker) | +| 8 | Compare the patterns, and pick one for each class | you answer questions | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 34 of 34. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +

+Spoiler: the bugs and the fixes + +**The contract.** If `a.equals(b)`, then `a.hashCode() == b.hashCode()`. The reverse is not +required: different objects may share a hash. A `HashSet` uses the hash to pick a bucket and calls +`equals` only on what it finds there. And the hash of an object must not change while it is in the +set, because the set never moves it. + +| Class | Bug | Fix | Task | +|---|---|---|---| +| `Sku` | no `equals`: `Object.equals` is `==` | a record (`record Sku(String code)`), or `equals` and `hashCode` on `code` | 2 | +| `Money` | `equals` without `hashCode`: equal objects in different buckets | `hashCode` on the same fields as `equals` | 2 | +| `CartLine` | the quantity is in `hashCode` and changes while the line is in the set | `equals` and `hashCode` on the SKU only | 4 | +| `Bundle` | a record holding the caller's `ArrayList`: the caller changes it | `skus = List.copyOf(skus)` in the compact constructor | 4 | +| `LineItem` | `Objects.hash(id)`: every new item is "equal", and the hash changes when the id is assigned | equal only if both ids are non-null and the same; a constant `hashCode`; `instanceof` and `getId()` | 5 | +| `Product` | every field: loads the lazy tags, fails when detached, changes with the price, `getClass()` fails on a proxy | the business key: `@NaturalId sku`, `instanceof`, `other.getSku()` | 7 | + +**Two patterns for entities, and when to use which.** + +| | Business key (`Product.sku`) | Generated id + constant `hashCode` (`LineItem`) | +|---|---|---| +| Needs | A unique, immutable, always-set field | Nothing | +| New object (no id yet) | Equal to the saved one with the same key | Equal only to itself | +| Big `HashSet` | Normal speed | One bucket: every lookup walks all of them | +| On a proxy | `getSku()` loads the row | `getId()` does not | +| Use it when | The entity has a natural key: SKU, ISBN, email, IBAN | It does not: order lines, events, log entries | + +Not overriding at all (`Object.equals`, like `Tag`) is also correct, as long as you never compare +objects from two different transactions: inside one persistence context Hibernate gives you one +Java object per row. + +
diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/TASKS_GUIDED.md b/java/concepts/junior-mid/15-equals-and-hashcode/TASKS_GUIDED.md new file mode 100644 index 0000000..4d6177c --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/TASKS_GUIDED.md @@ -0,0 +1,899 @@ +# Guided Tasks — equals and hashCode + +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`. + +Hash codes and object names like `Money@7dfc4d58` change on every run, and so do the bucket numbers +that come from them. The `true` and `false` values, the counts and the `RESULT` line should match. + +**Before you start** + +```bash +cd start +``` + +Tasks 1 to 4 are plain Java: no Docker. Task 5 starts the database. + +--- + +## Task 1: See It Break + +No code in this task. You are collecting evidence. + +### Two Skus with the same code + +```bash +./demo +``` + +``` + Sku a = new Sku("KEYBOARD-01") + Sku b = new Sku("KEYBOARD-01") + prices.put(a, 89.00 EUR) + + a.equals(b) false + a.hashCode() 446017128 + b.hashCode() 728799689 + List.of(a).contains(b) false + prices.get(b) null + set.add(a); set.add(b); size 2 [KEYBOARD-01, KEYBOARD-01] + +RESULT: NOT EQUAL. Two Skus with the same code are two different keys: the price of KEYBOARD-01 was not found. +``` + +`Sku` does not write `equals` or `hashCode`, so it inherits both from `Object`: + +- `Object.equals(o)` is `this == o`: equal only to itself. Two objects with the same code are two + different objects, so they are not equal. +- `Object.hashCode()` is the **identity hash**: a number the JVM picks for each object, unrelated to + its fields. Two objects, two numbers. + +Every collection asks one of these two questions, so every collection fails: the list, the map and +the set. In a real application `a` and `b` are the Sku from the request and the Sku from the +database. They are never the same object. + +### equals without hashCode + +```bash +./demo --scenario equals-only +``` + +``` + a.equals(b) true + a.hashCode() 190771853 + b.hashCode() 44588997 + List.of(a).contains(b) true a List only calls equals + set.add(a); set.add(b); size 2 [89.00 EUR, 89.00 EUR] + labels.get(b) null + +RESULT: DUPLICATE ITEM. a.equals(b) is true, and the HashSet holds both: equal objects need equal hash codes. +``` + +`Money` has an `equals`, so `a.equals(b)` is `true` and the `List` works. The `HashSet` and the +`HashMap` do not, because they ask `hashCode` **first**, and `Money` still has the identity hash. +That is why this bug survives the first tests: someone checks with a `List`, sees it work, and the +`HashSet` breaks in production. + +### A key that changes + +```bash +./demo --scenario mutable +``` + +``` + CartLine line = new CartLine(KEYBOARD-01, 1) + + cart.add(line) true hashCode 1675349407 + line.changeQuantity(3) hashCode 1675349409 (was 1675349407) + cart.contains(line) false + cart.remove(line) false the customer clicked "remove" + cart.size() 1 [3 x KEYBOARD-01] + cart.add(line) again true size 2: the same object is in the set twice + +RESULT: LOST IN SET. The line is still in the cart, and contains and remove cannot find it. ./inspect --scenario mutable shows why. +``` + +`CartLine` has both methods, generated by the IDE with every field ticked: `Objects.hash(sku, +quantity)`. The line went into the set with one hash. Changing the quantity gave it another. The +set still holds it (`size()` is 1 and printing shows it), but `contains` and `remove` cannot find +the **very same object**. Adding it again works, and now one object is in the set twice. + +### Keep two outputs for Task 3 + +```bash +./inspect +./inspect --scenario mutable +``` + +Copy both outputs into a file: Task 3 reads them after you have fixed the code. + +**Check.** `./check 1` prints 2 of 2. Both tests pass on purpose: one pins down that +`Object.equals` is identity, the other counts how often a `HashSet` calls `equals` (not at all when +the hash differs). + +--- + +## Task 2: Fix the Value Objects + +**The idea:** a value object is equal to another one when its values are equal. Then `hashCode` +must follow `equals`: computed from the same fields, and nothing else. + +### Before + +`./check 2` prints 2 of 7. + +### Step 1: make Sku a record + +Replace the whole class in `value/Sku.java`: + +```java +package com.amigoscode.equality.value; + +import java.util.Objects; + +/** A stock keeping unit, for example KEYBOARD-01. Two Skus with the same code are the same Sku. */ +public record Sku(String code) { + + public Sku { + Objects.requireNonNull(code, "code"); + if (code.isBlank()) { + throw new IllegalArgumentException("A SKU code cannot be blank"); + } + } + + @Override + public String toString() { + return code; + } +} +``` + +A record writes the constructor, a final field and the accessor `code()` for each component, and +`equals`, `hashCode` and `toString` from all components. The callers do not change: they already +called `new Sku(...)` and `code()`. The compact constructor `public Sku { ... }` keeps the +validation. `toString` is overridden only so the demo prints `KEYBOARD-01` instead of +`Sku[code=KEYBOARD-01]`. + +Writing `equals` and `hashCode` by hand on `code` is just as correct: `CartLine` in Task 4 has +that shape. + +### Step 2: give Money its hashCode + +In `value/Money.java`, replace the `TODO Task 2` comment: + +```java +@Override +public int hashCode() { + return Objects.hash(amount, currency); +} +``` + +The same two fields as `equals`. `Objects.hash(a, b)` is `31 * (31 + a.hashCode()) + b.hashCode()`: +equal fields give an equal result. + +**Why the constructor calls `setScale(2)`.** `BigDecimal.equals` compares the scale too: +`new BigDecimal("10.5").equals(new BigDecimal("10.50"))` is `false`, and their hash codes differ. +`Money` normalises every amount to two decimals once, in the constructor, so `equals` and +`hashCode` only ever see `10.50`. (`compareTo` ignores the scale. If you compare with `compareTo` +in `equals`, you need a `hashCode` that ignores the scale too, for example of +`amount.stripTrailingZeros()`.) + +### After + +`./demo` now prints `a.equals(b) true`, the same `hashCode` twice (`-1858179673`), the price, and a +set of size 1: + +``` +RESULT: OK. Two Skus with the same code are one key: the price was found and the set holds one. +``` + +`./demo --scenario equals-only`: + +``` +RESULT: OK. Equal amounts have equal hash codes: the set holds one and the label was found. +``` + +That `hashCode` is now the same on every run and every machine: it is computed from +`"KEYBOARD-01"`, not chosen by the JVM. `./check 2` prints 7 of 7. + +--- + +## Task 3: Inspect the Hash Table + +### Step 1: where the two Money objects were + +This is the `./inspect` output you kept in Task 1, before the fix: + +``` +BUCKETS after set.add(a); set.add(b) + 2 elements in a table of 16 buckets (empty buckets not shown) + bucket element Java object hash when added hashCode() now a lookup goes to + ------ ------- -------------- --------------- -------------- ---------------- + 4 a Money@7dfc4d58 2113686872 2113686872 4 + 11 b Money@6191bd7a 1636941178 1636941178 11 + +LOOKUP set.contains(c), where c is one more object made from the same values + hashCode() is 408519720, so look in bucket 1 + bucket 1 is empty: equals is never called + contains returns false +``` + +A `HashSet` is a `HashMap` whose keys are the elements, and a `HashMap` is a table of buckets (16 +to start with). To add or find an object it does this, in this order: + +1. call `hashCode()`, and turn the number into a bucket index +2. go to that one bucket. Every other bucket is ignored +3. for each element in the bucket, compare the **stored hash** with the new one. Only if they are + the same, call `equals` + +`a` and `b` had different identity hashes, so they went to buckets 4 and 11. The lookup for `c` +went to bucket 1, found nothing, and **never called `equals`**. A perfect `equals` is useless if +`hashCode` sends the lookup to the wrong bucket. + +### Step 2: after the fix + +```bash +./inspect +``` + +``` +BUCKETS after set.add(a); set.add(b) + 1 element in a table of 16 buckets (empty buckets not shown) + bucket element Java object hash when added hashCode() now a lookup goes to + ------ ------- -------------- --------------- -------------- ---------------- + 6 a Money@71cfc47d 8622949 8622949 6 + +LOOKUP set.contains(c), where c is one more object made from the same values + hashCode() is 8622949, so look in bucket 6 + bucket 6 holds 89.00 EUR with the same hash: equals() says true + contains returns true +``` + +`b` went to bucket 6, found `a` with the same hash, `equals` said `true`, so `add` returned `false` +and the set kept one. The lookup for `c` does the same. + +### Step 3: the same hash is not "equal" + +```bash +./inspect --scenario collision +``` + +``` + "Aa".hashCode() is 2112 and "BB".hashCode() is 2112. "Aa".equals("BB") is false. + +BUCKETS after set.add("Aa"); set.add("BB"); set.add("KEYBOARD-01") + bucket element Java object hash when added hashCode() now a lookup goes to + ------ ----------- --------------- --------------- -------------- ---------------- + 0 Aa String@700870f1 2112 2112 0 + 0 BB String@1503eb93 2112 2112 0 + 9 KEYBOARD-01 String@7b4a5543 -1858179673 -1858179673 9 + +LOOKUP set.contains("BB") + hashCode() is 2112, so look in bucket 0 + bucket 0 holds Aa with the same hash: equals() says false + bucket 0 holds BB with the same hash: the same object, found + contains returns true +``` + +Two different strings, one hash, one bucket. That is a **collision**, and it is allowed: the set +keeps both and tells them apart with `equals`. Collisions cost speed, never correctness. +`HashContractTest` takes it to the extreme: a `hashCode` that returns 42 for everything is legal, +and every lookup walks one long chain. + +### Step 4: the line that got lost + +The `./inspect --scenario mutable` output you kept in Task 1: + +``` +BUCKETS after keyboard.changeQuantity(3). Nothing in the table moves by itself + bucket element Java object hash when added hashCode() now a lookup goes to + ------ --------------- ----------------- --------------- -------------- ------------------ + 0 2 x MOUSE-01 CartLine@2c24925b -72131709 -72131709 0 + 14 3 x KEYBOARD-01 CartLine@544c4887 -1738614032 -1738614030 12 <- WRONG BUCKET + +LOOKUP cart.contains(keyboard), the very same object + hashCode() is -1738614030, so look in bucket 12 + bucket 12 is empty: equals is never called + contains returns false +``` + +The keyboard line still sits in bucket 14 with the hash it had when it was added. The set has no +idea that the quantity changed: nobody tells it. `contains` computes the new hash, goes to +bucket 12, and finds nothing. (Even if the new hash had landed in bucket 14 by chance, the stored +hash would not match, and `equals` would still not be called.) + +### Step 5: from a hash to a bucket + +`Buckets.bucketOf` in `demo/` is what `HashMap` does: `(h ^ (h >>> 16)) & (tableSize - 1)`, the +lowest 4 bits for 16 buckets, after mixing in the high bits. When the table grows, `HashMap` moves +every element using the hash it **stored**. It never calls `hashCode` again. + +**The contract:** if `a.equals(b)`, then `a.hashCode() == b.hashCode()`; the same hash does not +mean equal. And the hash of an element must not change while it is in the set: the set never looks +again. + +`./check 3` prints 2 of 2: both tests document the contract. + +--- + +## Task 4: Fix the Keys That Change + +### Before + +`./check 4` prints 2 of 7. And: + +```bash +./demo --scenario record +``` + +``` + desk.hashCode() 2036529967 + skus.add(HEADSET-01) true the caller reuses its list for the next bundle + desk.skus() [KEYBOARD-01, MOUSE-01, HEADSET-01] + desk.hashCode() 671280788 (was 2036529967) + prices.get(desk) null + prices.size() 1 [Desk set] + +RESULT: LOST IN MAP. The price of the desk set is in the Map, and the desk set cannot find it. +``` + +`Bundle` is a record, and its fields are final. But `skus` is a final reference to **the caller's +`ArrayList`**. The caller added to its list, the bundle changed with it, and so did its hash: the +same bug as the cart line, inside a record. + +### Step 1: CartLine, only what never changes + +In `cart/CartLine.java`, replace both methods: + +```java +@Override +public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CartLine other)) { + return false; + } + return sku.equals(other.sku); +} + +@Override +public int hashCode() { + return sku.hashCode(); +} +``` + +What makes a cart line *this* line? Its SKU: a cart has one line per product, and the quantity is +how many of it. `sku` is `final`, so the hash cannot change. + +`hashCode` may use fewer fields than `equals` (equal objects still get equal hashes), never more. +So why take `quantity` out of `equals` as well? Because equality must not change while the object +is in a set either: with the quantity in `equals`, a cart could hold `1 x KEYBOARD-01` and +`3 x KEYBOARD-01`, and after one `changeQuantity` it would hold two equal elements, which a `Set` +promises never to do. Two lines for the same SKU are now equal, which is exactly what a cart wants. + +### Step 2: Bundle, a copy of the list + +In `value/Bundle.java`, add one line to the compact constructor: + +```java +public Bundle { + Objects.requireNonNull(name, "name"); + skus = List.copyOf(skus); +} +``` + +`List.copyOf` makes an unmodifiable copy. The caller can do what it likes with its own list; the +bundle has its own, and `desk.skus().add(...)` throws `UnsupportedOperationException`. (It also +rejects `null` elements, which is fine for SKUs.) In a compact constructor, assigning to the +parameter `skus` changes the value the record stores. + +**Records and arrays.** A record compares each component with that component's own `equals`. For a +`List` that is "same elements in the same order". For an **array** it is `==`, because arrays do not +override `equals`. `BundleTest.arraysInRecordsCompareByIdentity` documents it: two +`record Barcode(byte[] digits)` with the same digits are not equal. Use a `List`, or override +`equals` and `hashCode` with `Arrays.equals` and `Arrays.hashCode` (and copy the array in and out). + +### After + +`./demo --scenario mutable` and `./demo --scenario record` both end in `RESULT: OK`. The record +scenario now shows the bundle untouched by the caller's change: + +``` + skus.add(HEADSET-01) true the caller reuses its list for the next bundle + desk.skus() [KEYBOARD-01, MOUSE-01] + desk.hashCode() -1743535064 (unchanged) + prices.get(desk) 119.00 EUR +``` + +`./inspect --scenario mutable`: + +``` +BUCKETS after keyboard.changeQuantity(3). Nothing in the table moves by itself + bucket element Java object hash when added hashCode() now a lookup goes to + ------ --------------- ----------------- --------------- -------------- ---------------- + 9 3 x KEYBOARD-01 CartLine@287cf78d -1858179673 -1858179673 9 + 13 2 x MOUSE-01 CartLine@74e2d62f 662986825 662986825 13 +``` + +No `WRONG BUCKET`. `./check 4` prints 7 of 7. + +--- + +## Task 5: Fix the Line Items + +From here on it is JPA entities with real Hibernate and Postgres. + +```bash +docker compose up -d +``` + +### Before + +```bash +./demo --scenario new-items +``` + +``` +First, in memory: two new line items, before anything is saved. + + a.getId(), b.getId() null, null + a.equals(b) true + order.getItems().size() 1 after order.add(keyboard), order.add(mouse) + +Now the real thing, saved to Postgres: + + orderService.placeOrder("ana", [1 x KEYBOARD-01, 2 x MOUSE-01]) + +SQL SENT + select p1_0.id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from product p1_0 where p1_0.sku=? + select p1_0.id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from product p1_0 where p1_0.sku=? + insert into orders (customer) values (?) + insert into line_item (order_id,product_id,quantity) values (?,?,?) + +ROWS IN line_item + id order_id sku quantity + -- -------- ----------- -------- + 1 1 KEYBOARD-01 1 + +RESULT: MISSING ITEM. 2 lines were ordered and 1 was saved. The second new item was equal to the first (both ids null), so the Set never took it. +``` + +```bash +./demo --scenario remove-item +``` + +``` +SQL SENT + select p1_0.id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from product p1_0 where p1_0.sku=? + insert into orders (customer) values (?) + insert into line_item (order_id,product_id,quantity) values (?,?,?) + + order.getItems() [LineItem#1 (1 x product 3)] + +ROWS IN line_item + id order_id sku quantity + -- -------- ---------- -------- + 1 1 HEADSET-01 1 + +RESULT: LOST IN SET. The out-of-stock headset was removed from the order, the Set did not find it, and its row is still in line_item. ./inspect --scenario remove-item shows why. +``` + +Also run `./inspect --scenario remove-item` now and keep its output for Task 6. + +### What just happened + +`LineItem` uses only its id, the way an IDE generates it when you tick `id`: + +```java +return Objects.equals(id, other.id); // equals +return Objects.hash(id); // hashCode +``` + +The id is `@GeneratedValue`: the database picks it when the row is inserted. Before the save it is +`null`. + +- **Missing item.** `Objects.equals(null, null)` is `true`, so every new line item is equal to + every other new line item. The mouse was "already in" the set, `items.add` returned `false`, and + Hibernate never saw it: no INSERT. Nothing threw, and the confirmation showed one line. +- **Lost item.** `placeOrder` saves first (that is when the INSERT runs and the id is filled in), + then removes the out-of-stock headset. `Objects.hash(null)` is 31 and `Objects.hash(1L)` is 32, + so the item now has a different hash than the one it was added with. `remove` looks in the wrong + bucket, returns `false`, the item never leaves the `Set`, and `orphanRemoval` has nothing to + delete. No DELETE in the SQL. + +### Step 1: the fix + +In `order/LineItem.java`, replace both methods: + +```java +@Override +public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof LineItem other)) { + return false; + } + return id != null && id.equals(other.getId()); +} + +@Override +public int hashCode() { + return LineItem.class.hashCode(); +} +``` + +Remove the `java.util.Objects` import. Line by line: + +- **`this == o`**: an object is always equal to itself, also a new one. That is what keeps a new + item findable in its own `Set`. +- **`id != null &&`**: two different new items are not equal. Only a saved row has an identity. +- **A constant `hashCode`**: every `LineItem` returns the same number, before and after the save, + so an item never changes bucket. This is legal (Task 3) and costs speed: all the items of a set + share one bucket. For the lines of one order that does not matter. +- **`instanceof` and `getId()`**: Hibernate may hand you a proxy, a generated subclass. `getClass()` + of a proxy is not `LineItem.class`, and its fields are empty. Task 6 shows it. + +Why not keep `Objects.hash(id)` with `id != null && ...`? Try it: `./check 5` prints 3 of 5. The +missing item is fixed (two new items are no longer equal) and the lost item is not: the hash still +changes during the save. + +### After + +`./demo --scenario new-items` shows two rows in `line_item` (`KEYBOARD-01` and `MOUSE-01`) and +`RESULT: OK. 2 lines were ordered and 2 were saved.` `./demo --scenario remove-item` now ends its +SQL with the DELETE that was missing: + +``` + insert into line_item (order_id,product_id,quantity) values (?,?,?) + delete from line_item where id=? + +RESULT: OK. The out-of-stock line was removed from the Set, and orphanRemoval deleted its row. +``` + +`./check 5` prints 5 of 5. + +--- + +## Task 6: Inspect the Persistence Context + +### Step 1: the lost item, from the inside + +The `./inspect --scenario remove-item` output you kept in Task 5: + +``` +BUCKETS of order.items, after the save + 1 element in a table of 16 buckets (empty buckets not shown); the HashSet inside Hibernate's PersistentSet + bucket element Java object hash when added hashCode() now a lookup goes to + ------ -------------- ----------------- --------------- -------------- ------------------ + 15 item (headset) LineItem@21a1b9dc 31 32 0 <- WRONG BUCKET + +LOOKUP order.remove(item) first looks for it + hashCode() is 32, so look in bucket 0 + bucket 0 is empty: equals is never called + contains returns false + +Step 3. order.remove(item) returned false; em.flush() + +SQL SENT BY THE FLUSH + (none) + +ROWS IN line_item (this transaction's view) + id order_id sku quantity + -- -------- ---------- -------- + 1 1 HEADSET-01 1 +``` + +31 when it was added, 32 now. The row is still there, and the persistence context still lists +`LineItem#1`. Note "the HashSet inside Hibernate's PersistentSet": during `persist`, Hibernate +replaced the `items` field with its own `PersistentSet`, which wraps your `HashSet` **as it is**. +Nobody rehashes anything. + +### Step 2: the same, fixed + +```bash +./inspect --scenario remove-item +``` + +``` +BUCKETS of order.items, after the save + bucket element Java object hash when added hashCode() now a lookup goes to + ------ -------------- ----------------- --------------- -------------- ---------------- + 15 item (headset) LineItem@3e3450c6 1566093815 1566093815 15 + +LOOKUP order.remove(item) first looks for it + hashCode() is 1566093815, so look in bucket 15 + bucket 15 holds LineItem#1 (1 x product 3) with the same hash: the same object, found + contains returns true + +Step 3. order.remove(item) returned true; em.flush() + +SQL SENT BY THE FLUSH + delete from line_item where id=? +``` + +The hash did not change, `remove` found the item, the flush sent the DELETE, and `LineItem#1` left +the persistence context. + +### Step 3: all line items share a bucket + +```bash +./inspect --scenario new-items +``` + +``` +Step 1. LineItem first = order.add(keyboard, 1); LineItem second = order.add(mouse, 2) + first.equals(second) is false (ids: null, null) + +BUCKETS of order.items, before the save + bucket element Java object hash when added hashCode() now a lookup goes to + ------ ---------------- ----------------- --------------- -------------- ---------------- + 9 first (keyboard) LineItem@3e3d4c40 1784789000 1784789000 9 + 9 second (mouse) LineItem@56907545 1784789000 1784789000 9 +``` + +That is the price of the constant `hashCode`: one bucket, and a lookup compares with each element. +(In `start/` the same command shows one element before the save, and after the save one item with +id 1 and one with id `null` that never reached the persistence context.) + +### Step 4: one Java object per row + +Open `PersistenceContextIT`. Its three tests pass in `start/` and in `solution/`: + +- In **one** transaction, `em.find` and `findBySku` return **the same Java object**: the + persistence context keeps one object per row. So `==` works, and so does `Object.equals`. +- In **two** transactions you get two objects for the same row. +- `Tag` has no `equals`. `keyboard.getTags().contains(gamingNow)` is `true`: the very object in the + collection. `contains(gamingFromEarlier)` is `false`: same row, other transaction, other object. + +So **not overriding `equals` is a valid choice** for an entity, as long as objects from different +transactions never meet. They meet more often than you think: a product cached at startup, an +entity kept in the HTTP session and merged later, an object a test created in its own transaction. + +### Step 5: what a proxy is + +```bash +./inspect --scenario proxy +``` + +``` +PERSISTENCE CONTEXT + entity Java object state + ---------- ----------------------------- --------------------- + LineItem#1 LineItem@1829812b loaded + Order#1 Order@17dcb97d loaded + Product#1 Product$HibernateProxy@d51862 proxy, row not loaded + +Step 2. Product proxy = item.getProduct(). Each line shows the SQL it sent, if any. + + proxy.getClass() Product$HibernateProxy no SQL + proxy.getClass().getSuperclass() Product no SQL + Hibernate.isInitialized(proxy) false no SQL + proxy.getId() 1 no SQL + the field proxy.sku, read directly null no SQL + Hibernate.getClass(proxy) Product SQL: select p1_0.id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from product p1_0 where p1_0.id=? + Hibernate.isInitialized(proxy) true no SQL + the field proxy.sku, read directly null no SQL + proxy.getSku() KEYBOARD-01 no SQL + Hibernate.unproxy(proxy) Product@59037272 no SQL +``` + +`LineItem.product` is `LAZY`, so Hibernate did not load the product. It put a **proxy** there: an +instance of a generated subclass, `Product$HibernateProxy`, that knows only the id. + +- `getClass()` is the subclass, not `Product`. A `getClass() != o.getClass()` check in `equals` + says the proxy and the real product are different. +- `getId()` answers without SQL: the proxy knows its id. +- `Hibernate.getClass(proxy)` returns `Product`, and **loads the row** to find out. +- The proxy's own field `sku` stays `null`, even after the row is loaded. The data lives in a + second object, the real `Product@59037272`, and only method calls are forwarded to it. `other.sku` + in an `equals` reads the empty field. `other.getSku()` goes through. + +`./check 6` prints 3 of 3. + +--- + +## Task 7: Fix the Product + +### Before + +```bash +./demo --scenario lazy +``` + +``` +SQL SENT WHILE ADDING 3 PRODUCTS TO A HashSet + select t1_0.product_id,t1_1.id,t1_1.name from product_tag t1_0 join tag t1_1 on t1_1.id=t1_0.tag_id where t1_0.product_id=? + select t1_0.product_id,t1_1.id,t1_1.name from product_tag t1_0 join tag t1_1 on t1_1.id=t1_0.tag_id where t1_0.product_id=? + select t1_0.product_id,t1_1.id,t1_1.name from product_tag t1_0 join tag t1_1 on t1_1.id=t1_0.tag_id where t1_0.product_id=? + +2. The same, with products from a transaction that has already ended (a cache, a DTO mapper, + a test, anything that runs after the @Transactional method returned): + + new HashSet<>(all) threw + LazyInitializationException: Cannot lazily initialize collection of role 'com.amigoscode.equality.product.Product.tags' with key '1' (no session) + +RESULT: EXTRA QUERIES. Putting 3 products in a HashSet sent 3 SELECTs: hashCode loaded each product's tags. +RESULT: LAZY INITIALIZATION EXCEPTION. A product loaded earlier cannot even be put in a HashSet. +``` + +```bash +./demo --scenario proxy +``` + +``` + keyboard.equals(proxy) false + proxy.equals(keyboard) false + productsInOrder.contains(keyboard) false + +RESULT: NOT EQUAL. KEYBOARD-01 and KEYBOARD-01, one row, and equals says they are different products. +``` + +`./check 7` prints 0 of 6. + +### What just happened + +`Product` compares every field, the same fields Lombok's `@Data` would use. Each one is a problem: + +| Field | Problem | +|---|---| +| `tags` (a lazy `@ManyToMany`) | `hashCode` calls `tags.hashCode()`, which loads the collection: one SELECT per product. With no open session: `LazyInitializationException` | +| `id` | `null` before the save, so the hash changes when it is assigned (Task 5) | +| `name`, `price`, `stock` | they change, and with them the hash (Task 4) | +| `getClass()` | false for a proxy of the same row, before any field is compared | + +`proxy.equals(keyboard)` is false for a second reason: the call is forwarded to the real object, +which compares the tags. Each transaction loaded its own `Tag` objects, and `Tag` has no `equals`. + +### Step 1: the business key + +A product has what a line item lacks: the **SKU**. It is unique (the column has a unique +constraint), it is set before the save, and it never changes. Replace both methods in +`product/Product.java`: + +```java +@Override +public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Product other)) { + return false; + } + return sku.equals(other.getSku()); +} + +@Override +public int hashCode() { + return sku.hashCode(); +} +``` + +Remove the `java.util.Objects` import. `instanceof`, because a proxy is a subclass. `getSku()`, +because a proxy's fields are empty. + +### Step 2: make Hibernate guard the key + +The pattern is only safe if the SKU really never changes. Say so on the field: + +```java +@NaturalId +@Column(nullable = false, unique = true, updatable = false) +private String sku; +``` + +Import `org.hibernate.annotations.NaturalId`. `@NaturalId` marks the business key, and it is +immutable by default. If code changes the SKU of a managed product, the flush fails: + +``` +HibernateException: An immutable natural identifier of entity com.amigoscode.equality.product.Product was altered from `MOUSE-01` to `MOUSE-02` +``` + +It also gives you `session.bySimpleNaturalId(Product.class).load("KEYBOARD-01")`. + +### After + +`./demo --scenario lazy` sends no SQL and throws nothing: +`RESULT: OK. No SQL and no exception: hashCode does not touch the tags.` +`./demo --scenario proxy` prints `true` three times: +`RESULT: OK. The catalogue's keyboard and the order's proxy are equal, both ways, and found in the Set.` + +`./check` prints 34 passes and no failures. + +One honest cost: `keyboard.equals(proxy)` calls `proxy.getSku()`, and that loads the row (one +SELECT), because the SKU is not the id. Inside a transaction that is fine. On a detached, +never-loaded proxy it would throw `LazyInitializationException`, and so would the id pattern's +`proxy.equals(...)` or `proxy.hashCode()`: every method you override is forwarded to the real +object, which needs a session to be loaded. Only `getId()` is answered by the proxy itself. + +--- + +## Task 8: Compare the Patterns + +### Step 1: every class in this project + +| Class | `equals` uses | Why that is safe | +|---|---|---| +| `Sku` | `code` (record) | a value, immutable | +| `Money` | `amount`, `currency` | a value, immutable, scale normalised | +| `CartLine` | `sku` | the one field that never changes | +| `Bundle` | `name`, `skus` (record) | immutable once the list is copied | +| `Order` | nothing: `Object.equals` | never put in a `Set`, never compared across transactions | +| `LineItem` | `id` if both have one, constant `hashCode` | no business key; the hash never changes | +| `Product` | `sku` (`@NaturalId`) | unique, set before the save, immutable | +| `Tag` | nothing: `Object.equals` | only correct inside one transaction (Task 6) | + +### Step 2: the cost of one bucket + +Task 6 step 3 showed both line items in bucket 9. With 100,000 items in one `HashSet`, every +`contains` would compare up to 100,000 objects (a crowded bucket becomes a tree, but with one hash +for all and no `compareTo` the tree still has to look at every element). For one order's items: no +problem. For a huge set: a business key, or a `Map` by id. + +### Step 3: field or getter + +Change `id.equals(other.getId())` to `id.equals(other.id)` in `LineItem` and run `./check 5`: + +``` + [FAIL] LineItem: an item is equal to a Hibernate proxy of the same row, and comparing them does not load the row + [loaded.equals(proxy), proxy class LineItem$HibernateProxy] + Expecting value to be true but was false + 4 of 5 pass +``` + +`other.id` on a proxy is the proxy's own empty field. Put the getter back. + +### Step 4: getClass, Hibernate.getClass, instanceof + +Replace the `instanceof` check in `Product.equals` with `getClass() != o.getClass()` (and a cast). +`./check 7` prints 4 of 6: both proxy tests fail. With +`Hibernate.getClass(this) != Hibernate.getClass(o)` it prints 6 of 6, and Task 6 step 5 showed +what that costs: a SELECT to load each proxy. `instanceof` is free. Its weakness is inheritance: if +`Product` had subclasses, `instanceof` would make a parent equal to a child. Use +`Hibernate.getClass` for entity hierarchies, `instanceof` otherwise. Put `instanceof` back. + +### Step 5: Order + +`Order` keeps `Object.equals`: orders are not put in sets, and nothing compares two of them. Do not +add an `equals` "for completeness". An all-fields one would load the `Set` on every +call, and if `LineItem` also compared its `order`, the two `hashCode`s would call each other until +`StackOverflowError`: the classic Lombok `@Data` crash on a bidirectional association. + +### When to use which + +| | Business key | Id + constant `hashCode` | No override (`Object.equals`) | +|---|---|---|---| +| Needs | A unique, always-set, immutable field | Nothing | Nothing | +| New, unsaved object | Equal to the saved one with the same key | Equal only to itself | Equal only to itself | +| Across transactions | Works | Works | Fails | +| Big `HashSet` | Normal speed | One bucket, slow | Normal speed | +| Proxy | `getSku()` loads the row | `getId()` does not | Fine in one transaction | +| Use it for | SKU, ISBN, email, IBAN, username | Order lines, events, audit rows | Entities never compared across transactions | + +### How to say it in an interview + +> "The contract is that equal objects must have equal hash codes, and the hash must not change +> while the object is in a hash-based collection, because a HashSet uses the hash to pick a bucket +> once and only calls equals inside that bucket. Break either rule and objects get duplicated or +> lost, with no exception. For value objects I use records, or equals and hashCode on the same +> immutable fields. For JPA entities I never use every field, which is what Lombok's @Data does: +> it loads lazy associations and changes when the id is assigned or a price is updated. If the +> entity has a business key like a SKU, I compare on that, mark it @NaturalId and make it +> immutable. If not, I compare on the id only when both ids are set, and return a constant +> hashCode so it cannot change on save. Always with instanceof and getters, because Hibernate +> hands out proxies. And inside one persistence context, plain object identity is already +> correct." + +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/15-equals-and-hashcode/solution/.mvn/jvm.config b/java/concepts/junior-mid/15-equals-and-hashcode/solution/.mvn/jvm.config new file mode 100644 index 0000000..ccc1dc4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/.mvn/jvm.config @@ -0,0 +1,3 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow +--add-opens=java.base/java.util=ALL-UNNAMED diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/15-equals-and-hashcode/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/solution/check b/java/concepts/junior-mid/15-equals-and-hashcode/solution/check new file mode 100755 index 0000000..296fad5 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/check.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/solution/check.cmd new file mode 100644 index 0000000..7cdf2d1 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/compose.yaml b/java/concepts/junior-mid/15-equals-and-hashcode/solution/compose.yaml new file mode 100644 index 0000000..48765df --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/compose.yaml @@ -0,0 +1,16 @@ +name: equals-and-hashcode +services: + postgres: + image: postgres:17-alpine + container_name: equals-and-hashcode-postgres + environment: + POSTGRES_DB: shop + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + ports: + - "5454:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U shop -d shop"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/demo b/java/concepts/junior-mid/15-equals-and-hashcode/solution/demo new file mode 100755 index 0000000..438f4da --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/demo.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/solution/demo.cmd new file mode 100644 index 0000000..28b3d47 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/inspect b/java/concepts/junior-mid/15-equals-and-hashcode/solution/inspect new file mode 100755 index 0000000..0c4f568 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/inspect.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/solution/inspect.cmd new file mode 100644 index 0000000..ed551f3 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/mvnw b/java/concepts/junior-mid/15-equals-and-hashcode/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/solution/mvnw.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/solution/pom.xml b/java/concepts/junior-mid/15-equals-and-hashcode/solution/pom.xml new file mode 100644 index 0000000..08a3003 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + equals-and-hashcode + 0.0.1-SNAPSHOT + equals-and-hashcode + equals and hashCode in plain Java and on JPA entities: see objects get lost in a HashSet, then fix them + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + 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/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/EqualityApplication.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/EqualityApplication.java new file mode 100644 index 0000000..94bb835 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/EqualityApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.equality; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EqualityApplication { + + public static void main(String[] args) { + SpringApplication.run(EqualityApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/Cart.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/Cart.java new file mode 100644 index 0000000..5f0eb77 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/Cart.java @@ -0,0 +1,37 @@ +package com.amigoscode.equality.cart; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** A shopping cart: a HashSet of lines. Nothing to change here. */ +public final class Cart { + + private final Set lines = new HashSet<>(); + + /** Returns false when the cart already holds an equal line. */ + public boolean add(CartLine line) { + return lines.add(line); + } + + public boolean remove(CartLine line) { + return lines.remove(line); + } + + public boolean contains(CartLine line) { + return lines.contains(line); + } + + public int size() { + return lines.size(); + } + + public Set lines() { + return Collections.unmodifiableSet(lines); + } + + /** The HashSet itself, so ./inspect can show its buckets. */ + public Set backingSet() { + return lines; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/CartLine.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/CartLine.java new file mode 100644 index 0000000..a4b3850 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/cart/CartLine.java @@ -0,0 +1,58 @@ +package com.amigoscode.equality.cart; + +import com.amigoscode.equality.value.Sku; +import java.util.Objects; + +/** + * One line of a shopping cart: a SKU and how many of it. The customer can change the quantity, so + * a CartLine changes while it sits in the cart's HashSet. + */ +public final class CartLine { + + private final Sku sku; + private int quantity; + + public CartLine(Sku sku, int quantity) { + this.sku = Objects.requireNonNull(sku, "sku"); + changeQuantity(quantity); + } + + public Sku sku() { + return sku; + } + + public int quantity() { + return quantity; + } + + public void changeQuantity(int quantity) { + if (quantity < 1) { + throw new IllegalArgumentException("Quantity must be at least 1, got " + quantity); + } + this.quantity = quantity; + } + + // Task 4: only the field that never changes. A cart has one line per SKU, so the SKU is what + // makes a line this line. The quantity can change while the line is in the HashSet, so it must + // not be part of hashCode, and therefore not part of equals either. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CartLine other)) { + return false; + } + return sku.equals(other.sku); + } + + @Override + public int hashCode() { + return sku.hashCode(); + } + + @Override + public String toString() { + return quantity + " x " + sku; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/ShopData.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/ShopData.java new file mode 100644 index 0000000..13bf0bf --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/ShopData.java @@ -0,0 +1,48 @@ +package com.amigoscode.equality.db; + +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Puts the database back to the same three products and no orders. ./demo, ./inspect and every + * integration test call it first, so every run starts from the same state. Nothing to change here. + */ +public final class ShopData { + + public static final String KEYBOARD = "KEYBOARD-01"; + public static final String MOUSE = "MOUSE-01"; + /** Out of stock. */ + public static final String HEADSET = "HEADSET-01"; + + private ShopData() { + } + + public static void reset(JdbcTemplate jdbc) { + jdbc.execute("truncate table line_item, orders, product_tag, product, tag restart identity"); + jdbc.update("insert into tag (name) values ('wireless'), ('gaming'), ('audio')"); + jdbc.update(""" + insert into product (sku, name, price, stock) values + ('KEYBOARD-01', 'Mechanical keyboard', 89.00, 10), + ('MOUSE-01', 'Wireless mouse', 39.00, 10), + ('HEADSET-01', 'Wireless headset', 59.00, 0) + """); + jdbc.update(""" + insert into product_tag (product_id, tag_id) + select p.id, t.id + from (values ('KEYBOARD-01', 'gaming'), + ('MOUSE-01', 'wireless'), ('MOUSE-01', 'gaming'), + ('HEADSET-01', 'wireless'), ('HEADSET-01', 'audio')) as pt (sku, tag) + join product p on p.sku = pt.sku + join tag t on t.name = pt.tag + """); + } + + /** Saves an order with one line item per SKU, with plain SQL. Returns the order id. */ + public static long insertOrder(JdbcTemplate jdbc, String customer, String... skus) { + long orderId = jdbc.queryForObject("insert into orders (customer) values (?) returning id", Long.class, customer); + for (String sku : skus) { + jdbc.update("insert into line_item (order_id, product_id, quantity) select ?, id, 1 from product where sku = ?", + orderId, sku); + } + return orderId; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/SqlRecorder.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/SqlRecorder.java new file mode 100644 index 0000000..e333cde --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/db/SqlRecorder.java @@ -0,0 +1,36 @@ +package com.amigoscode.equality.db; + +import java.util.ArrayList; +import java.util.List; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** + * Writes down every SQL statement Hibernate sends while recording is on, so the demo can print it + * and the tests can count it. Registered in application.properties. Nothing to change here. + */ +public class SqlRecorder implements StatementInspector { + + private static final List STATEMENTS = new ArrayList<>(); + private static boolean recording; + + public static synchronized void start() { + STATEMENTS.clear(); + recording = true; + } + + /** Stops recording and returns what was sent since start(). */ + public static synchronized List stop() { + recording = false; + return List.copyOf(STATEMENTS); + } + + @Override + public String inspect(String sql) { + synchronized (SqlRecorder.class) { + if (recording) { + STATEMENTS.add(sql); + } + } + return sql; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Buckets.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Buckets.java new file mode 100644 index 0000000..89a52bf --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Buckets.java @@ -0,0 +1,145 @@ +package com.amigoscode.equality.demo; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Reads the bucket table inside a HashSet or HashMap, so ./inspect can show where each element + * really sits. A HashSet is a HashMap whose keys are the elements. Each bucket is a chain of nodes, + * and every node remembers the hash its key had WHEN IT WAS INSERTED. Nothing to change here. + * + *

The fields are private to java.util. The launchers open them with + * --add-opens=java.base/java.util=ALL-UNNAMED (see .mvn/jvm.config). + */ +final class Buckets { + + /** One element in the table: the bucket it sits in and the hashCode it had when it was added. */ + record Entry(int bucket, Object key, int hashAtInsert) { + } + + private Buckets() { + } + + /** What HashMap does with a hashCode before it picks a bucket: it mixes the high bits into the low ones. */ + static int spread(int hashCode) { + return hashCode ^ (hashCode >>> 16); + } + + static int bucketOf(int hashCode, int tableSize) { + return spread(hashCode) & (tableSize - 1); + } + + static int tableSize(Object setOrMap) { + Object[] table = table(setOrMap); + return table == null ? 0 : table.length; + } + + /** Every element, in table order. */ + static List entries(Object setOrMap) { + List entries = new ArrayList<>(); + Object[] table = table(setOrMap); + if (table == null) { + return entries; + } + for (int bucket = 0; bucket < table.length; bucket++) { + for (Object node = table[bucket]; node != null; node = read(node, "next")) { + int stored = (int) read(node, "hash"); + // The node stores spread(hashCode). The top 16 bits are unchanged, so spread is its own inverse. + entries.add(new Entry(bucket, read(node, "key"), spread(stored))); + } + } + return entries; + } + + /** + * What contains(probe) does, step by step: pick the bucket from probe.hashCode(), then for each + * node in that bucket compare the stored hash first, and call equals only when the hashes match. + */ + static List lookup(Object setOrMap, Object probe) { + List steps = new ArrayList<>(); + int hashCode = probe.hashCode(); + int size = tableSize(setOrMap); + int bucket = bucketOf(hashCode, size); + steps.add("hashCode() is " + hashCode + ", so look in bucket " + bucket); + boolean any = false; + for (Entry entry : entries(setOrMap)) { + if (entry.bucket() != bucket) { + continue; + } + any = true; + if (entry.hashAtInsert() != hashCode) { + steps.add("bucket " + bucket + " holds " + entry.key() + " with hash " + entry.hashAtInsert() + + ": different hash, equals is not called"); + } else { + boolean same = entry.key() == probe; + boolean equal = same || probe.equals(entry.key()); + steps.add("bucket " + bucket + " holds " + entry.key() + " with the same hash: " + + (same ? "the same object, found" : "equals() says " + equal)); + } + } + if (!any) { + steps.add("bucket " + bucket + " is empty: equals is never called"); + } + return steps; + } + + private static Object[] table(Object setOrMap) { + Object map = setOrMap; + if (setOrMap instanceof HashSet) { + map = read(setOrMap, HashSet.class, "map"); + } else if (!(setOrMap instanceof HashMap)) { + throw new IllegalArgumentException("Not a HashSet or HashMap: " + setOrMap.getClass().getName()); + } + return (Object[]) read(map, HashMap.class, "table"); + } + + /** The HashSet inside a Hibernate PersistentSet, or the set itself. */ + static Set unwrap(Set set) { + Class type = set.getClass(); + while (type != null && !type.getName().equals("org.hibernate.collection.spi.PersistentSet")) { + type = type.getSuperclass(); + } + return type == null ? set : (Set) read(set, type, "set"); + } + + static boolean isHibernateSet(Set set) { + return unwrap(set) != set; + } + + static Map asMap(Object map) { + return (Map) map; + } + + private static Object read(Object target, String name) { + Class type = target.getClass(); + while (type != null) { + try { + return read(target, type, name); + } catch (IllegalStateException e) { + type = type.getSuperclass(); + } + } + throw new IllegalStateException("No field " + name + " in " + target.getClass().getName()); + } + + private static Object read(Object target, Class type, String name) { + try { + Field field = type.getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } catch (NoSuchFieldException e) { + throw new IllegalStateException("No field " + name + " in " + type.getName(), e); + } catch (IllegalAccessException | RuntimeException e) { + if (e instanceof IllegalStateException ise) { + throw ise; + } + throw new IllegalStateException("Cannot read the bucket table (" + Tool.describe(e) + "). Run this with ./inspect," + + " which opens java.util for reading (see .mvn/jvm.config).", e); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Db.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Db.java new file mode 100644 index 0000000..432174c --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Db.java @@ -0,0 +1,42 @@ +package com.amigoscode.equality.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:5454/shop"); + static final String USER = env("DB_USER", "shop"); + static final String PASSWORD = env("DB_PASSWORD", "shop"); + + private Db() { + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp(Scenario scenario, boolean blankLineFirst) { + try (Connection ignored = DriverManager.getConnection(URL, USER, PASSWORD)) { + return true; + } catch (SQLException e) { + if (blankLineFirst) { + System.out.println(); + } + System.out.println("The scenario " + scenario.flag() + " uses JPA entities and needs Postgres, and Postgres is not"); + System.out.println("reachable at " + URL + ". Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("The plain-Java scenarios run without a database: " + Scenario.names(false) + "."); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + System.out.println(); + 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/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Demo.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Demo.java new file mode 100644 index 0000000..6eef1d9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Demo.java @@ -0,0 +1,380 @@ +package com.amigoscode.equality.demo; + +import static com.amigoscode.equality.demo.Tool.attempt; +import static com.amigoscode.equality.demo.Tool.line; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.order.OrderService; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.hibernate.Hibernate; + +/** + * Runs one scenario and prints the evidence: every call, what it returned, and a RESULT line. The + * plain-Java scenarios need nothing but Java. The database scenarios start the real application + * against the Postgres from compose.yaml. Run it with ./demo (or .\demo on Windows). + */ +public final class Demo { + + public static void main(String[] args) { + Scenario scenario; + try { + scenario = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (scenario == null) { + printHelp(); + return; + } + + System.out.println(); + System.out.println("Scenario: " + scenario.flag() + " | " + scenario.summary()); + System.out.println(); + if (!scenario.needsDatabase()) { + switch (scenario) { + case NO_EQUALS -> noEquals(); + case EQUALS_ONLY -> equalsOnly(); + case MUTABLE -> mutable(); + case RECORD -> record(); + default -> throw new IllegalStateException(scenario.flag()); + } + System.out.println(); + return; + } + if (!Db.isUp(scenario, false)) { + return; + } + try (Shop shop = Shop.start()) { + switch (scenario) { + case NEW_ITEMS -> newItems(shop); + case REMOVE_ITEM -> removeItem(shop); + case LAZY -> lazy(shop); + case PROXY -> proxy(shop); + default -> throw new IllegalStateException(scenario.flag()); + } + } + System.out.println(); + } + + // ---- Plain Java ---- + + private static void noEquals() { + Sku a = new Sku("KEYBOARD-01"); + Sku b = new Sku("KEYBOARD-01"); + Map prices = new HashMap<>(); + prices.put(a, new Money("89.00", "EUR")); + Set set = new HashSet<>(); + set.add(a); + set.add(b); + + System.out.println("Two Skus made from the same text, the way two requests or two rows would make them."); + System.out.println(); + System.out.println(" Sku a = new Sku(\"KEYBOARD-01\")"); + System.out.println(" Sku b = new Sku(\"KEYBOARD-01\")"); + System.out.println(" prices.put(a, 89.00 EUR)"); + System.out.println(); + line("a.equals(b)", a.equals(b)); + line("a.hashCode()", a.hashCode()); + line("b.hashCode()", b.hashCode()); + line("List.of(a).contains(b)", List.of(a).contains(b)); + line("prices.get(b)", prices.get(b)); + line("set.add(a); set.add(b); size", set.size(), set.toString()); + System.out.println(); + + if (prices.get(b) == null || set.size() > 1) { + System.out.println("RESULT: NOT EQUAL. Two Skus with the same code are two different keys: the price of KEYBOARD-01 was not found."); + } else { + System.out.println("RESULT: OK. Two Skus with the same code are one key: the price was found and the set holds one."); + } + } + + private static void equalsOnly() { + Money a = new Money("89.00", "EUR"); + Money b = new Money("89.00", "EUR"); + Set set = new HashSet<>(); + set.add(a); + set.add(b); + Map labels = new HashMap<>(); + labels.put(a, "keyboard price"); + + System.out.println(" Money a = new Money(\"89.00\", \"EUR\")"); + System.out.println(" Money b = new Money(\"89.00\", \"EUR\")"); + System.out.println(" labels.put(a, \"keyboard price\")"); + System.out.println(); + line("a.equals(b)", a.equals(b)); + line("a.hashCode()", a.hashCode()); + line("b.hashCode()", b.hashCode()); + line("List.of(a).contains(b)", List.of(a).contains(b), "a List only calls equals"); + line("set.add(a); set.add(b); size", set.size(), set.toString()); + line("labels.get(b)", labels.get(b)); + System.out.println(); + + if (a.equals(b) && set.size() > 1) { + System.out.println("RESULT: DUPLICATE ITEM. a.equals(b) is true, and the HashSet holds both: equal objects need equal hash codes."); + } else if (labels.get(b) == null) { + System.out.println("RESULT: NOT FOUND. a.equals(b) is true, and HashMap.get(b) did not find the value put with a."); + } else { + System.out.println("RESULT: OK. Equal amounts have equal hash codes: the set holds one and the label was found."); + } + } + + private static void mutable() { + Cart cart = new Cart(); + CartLine line = new CartLine(new Sku("KEYBOARD-01"), 1); + int before = line.hashCode(); + + System.out.println(" CartLine line = new CartLine(KEYBOARD-01, 1)"); + System.out.println(); + line("cart.add(line)", cart.add(line), "hashCode " + before); + line.changeQuantity(3); + int after = line.hashCode(); + line("line.changeQuantity(3)", "", "hashCode " + after + (after == before ? " (unchanged)" : " (was " + before + ")")); + boolean contains = cart.contains(line); + line("cart.contains(line)", contains); + boolean removed = cart.remove(line); + line("cart.remove(line)", removed, "the customer clicked \"remove\""); + line("cart.size()", cart.size(), cart.lines().toString()); + boolean addedAgain = cart.add(line); + line("cart.add(line) again", addedAgain, "size " + cart.size() + (cart.size() > 1 ? ": the same object is in the set twice" : "")); + System.out.println(); + + if (!contains || !removed) { + System.out.println("RESULT: LOST IN SET. The line is still in the cart, and contains and remove cannot find it." + + " ./inspect --scenario mutable shows why."); + } else { + System.out.println("RESULT: OK. The line was found after the change and removed."); + } + } + + private static void record() { + Sku keyboard = new Sku("KEYBOARD-01"); + Sku mouse = new Sku("MOUSE-01"); + List skus = new ArrayList<>(List.of(keyboard, mouse)); + Bundle desk = new Bundle("Desk set", skus); + Map prices = new HashMap<>(); + prices.put(desk, new Money("119.00", "EUR")); + int before = desk.hashCode(); + + System.out.println(" List skus = new ArrayList<>(List.of(KEYBOARD-01, MOUSE-01))"); + System.out.println(" Bundle desk = new Bundle(\"Desk set\", skus)"); + System.out.println(" prices.put(desk, 119.00 EUR)"); + System.out.println(); + line("desk.hashCode()", before); + Object added = attempt(() -> skus.add(new Sku("HEADSET-01"))); + line("skus.add(HEADSET-01)", added, "the caller reuses its list for the next bundle"); + line("desk.skus()", desk.skus()); + int after = desk.hashCode(); + line("desk.hashCode()", after, after == before ? "(unchanged)" : "(was " + before + ")"); + line("prices.get(desk)", prices.get(desk)); + line("prices.size()", prices.size(), prices.keySet().stream().map(Bundle::name).toList().toString()); + System.out.println(); + + if (prices.get(desk) == null) { + System.out.println("RESULT: LOST IN MAP. The price of the desk set is in the Map, and the desk set cannot find it."); + } else { + System.out.println("RESULT: OK. Changing the caller's list did not change the bundle: its price was found."); + } + } + + // ---- JPA ---- + + private static void newItems(Shop shop) { + System.out.println("First, in memory: two new line items, before anything is saved."); + System.out.println(); + Order draft = new Order("ana"); + LineItem a = draft.add(new Product(ShopData.KEYBOARD, "Mechanical keyboard", new BigDecimal("89.00"), 10), 1); + LineItem b = draft.add(new Product(ShopData.MOUSE, "Wireless mouse", new BigDecimal("39.00"), 10), 2); + line("a.getId(), b.getId()", a.getId() + ", " + b.getId()); + line("a.equals(b)", a.equals(b)); + line("order.getItems().size()", draft.getItems().size(), "after order.add(keyboard), order.add(mouse)"); + System.out.println(); + + System.out.println("Now the real thing, saved to Postgres:"); + System.out.println(); + System.out.println(" orderService.placeOrder(\"ana\", [1 x KEYBOARD-01, 2 x MOUSE-01])"); + System.out.println(); + SqlRecorder.start(); + shop.bean(OrderService.class).placeOrder("ana", + List.of(new OrderLine(ShopData.KEYBOARD, 1), new OrderLine(ShopData.MOUSE, 2))); + List sql = SqlRecorder.stop(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + System.out.println("ROWS IN line_item"); + shop.printLineItemRows(); + System.out.println(); + + int rows = shop.lineItemRows(); + if (rows < 2) { + System.out.println("RESULT: MISSING ITEM. 2 lines were ordered and " + rows + " was saved. The second new item" + + " was equal to the first (both ids null), so the Set never took it."); + } else { + System.out.println("RESULT: OK. 2 lines were ordered and 2 were saved."); + } + } + + private static void removeItem(Shop shop) { + System.out.println(" orderService.placeOrder(\"ana\", [1 x HEADSET-01])"); + System.out.println(); + System.out.println("HEADSET-01 has stock 0. placeOrder saves the order first (that gives every item its id),"); + System.out.println("then removes the lines that cannot be delivered: order.remove(item)."); + System.out.println(); + SqlRecorder.start(); + Order order = shop.bean(OrderService.class).placeOrder("ana", List.of(new OrderLine(ShopData.HEADSET, 1))); + List sql = SqlRecorder.stop(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + line("order.getItems()", order.getItems()); + System.out.println(); + System.out.println("ROWS IN line_item"); + shop.printLineItemRows(); + System.out.println(); + + if (shop.lineItemRows() > 0) { + System.out.println("RESULT: LOST IN SET. The out-of-stock headset was removed from the order, the Set did not find it," + + " and its row is still in line_item. ./inspect --scenario remove-item shows why."); + } else { + System.out.println("RESULT: OK. The out-of-stock line was removed from the Set, and orphanRemoval deleted its row."); + } + } + + private static void lazy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + + System.out.println("1. Inside a transaction: List all = products.findAll(); new HashSet<>(all)"); + System.out.println(); + List sql = shop.inTransaction(() -> { + List all = products.findAll(); + SqlRecorder.start(); + new HashSet<>(all); + return SqlRecorder.stop(); + }); + System.out.println("SQL SENT WHILE ADDING 3 PRODUCTS TO A HashSet"); + Tool.sql(sql); + System.out.println(); + + System.out.println("2. The same, with products from a transaction that has already ended (a cache, a DTO mapper,"); + System.out.println(" a test, anything that runs after the @Transactional method returned):"); + System.out.println(); + List loadedEarlier = shop.inTransaction(() -> products.findAll()); + String exception = null; + try { + new HashSet<>(loadedEarlier); + line("new HashSet<>(all)", "ok"); + } catch (RuntimeException e) { + exception = Tool.describe(e); + System.out.println(" new HashSet<>(all) threw"); + System.out.println(" " + exception); + } + System.out.println(); + + if (!sql.isEmpty()) { + System.out.println("RESULT: EXTRA QUERIES. Putting 3 products in a HashSet sent " + sql.size() + + " SELECTs: hashCode loaded each product's tags."); + } + if (exception != null) { + System.out.println("RESULT: LAZY INITIALIZATION EXCEPTION. A product loaded earlier cannot even be put in a HashSet."); + } + if (sql.isEmpty() && exception == null) { + System.out.println("RESULT: OK. No SQL and no exception: hashCode does not touch the tags."); + } + } + + private static void proxy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + long orderId = ShopData.insertOrder(shop.jdbc, "ana", ShopData.KEYBOARD, ShopData.MOUSE); + + System.out.printf(" %-60s %s%n", "Product keyboard = products.findBySkuWithTags(\"KEYBOARD-01\")", "transaction 1: the catalogue"); + System.out.printf(" %-60s %s%n", "Order order = em.find(Order.class, " + orderId + ")", "transaction 2: an order"); + System.out.printf(" %-60s %s%n", "Product proxy = .getProduct()", "the same row, lazy"); + System.out.println(); + Product keyboard = shop.inTransaction(() -> products.findBySkuWithTags(ShopData.KEYBOARD).orElseThrow()); + boolean[] outcome = new boolean[2]; + shop.inTransaction(() -> { + Order order = shop.em.find(Order.class, orderId); + Product proxy = order.getItems().stream() + .map(LineItem::getProduct) + .filter(product -> product.getId().equals(keyboard.getId())) + .findFirst().orElseThrow(); + line("keyboard.getClass()", keyboard.getClass().getSimpleName()); + line("proxy.getClass()", proxy.getClass().getSimpleName()); + line("Hibernate.isInitialized(proxy)", Hibernate.isInitialized(proxy), "the row is not loaded yet"); + line("proxy.getId()", proxy.getId(), "known without loading the row"); + Object keyboardEqualsProxy = attempt(() -> keyboard.equals(proxy)); + line("keyboard.equals(proxy)", keyboardEqualsProxy); + Object proxyEqualsKeyboard = attempt(() -> proxy.equals(keyboard)); + line("proxy.equals(keyboard)", proxyEqualsKeyboard); + Object contains = attempt(() -> { + Set inOrder = order.getItems().stream().map(LineItem::getProduct).collect(Collectors.toSet()); + return inOrder.contains(keyboard); + }); + line("productsInOrder.contains(keyboard)", contains); + outcome[0] = Boolean.TRUE.equals(keyboardEqualsProxy) && Boolean.TRUE.equals(proxyEqualsKeyboard); + outcome[1] = Boolean.TRUE.equals(contains); + }); + System.out.println(); + + if (!outcome[0] || !outcome[1]) { + System.out.println("RESULT: NOT EQUAL. KEYBOARD-01 and KEYBOARD-01, one row, and equals says they are different products."); + } else { + System.out.println("RESULT: OK. The catalogue's keyboard and the order's proxy are equal, both ways, and found in the Set."); + } + } + + // ---- Options ---- + + private static Scenario parse(String[] args) { + Scenario scenario = Scenario.NO_EQUALS; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + if (i + 1 >= args.length) { + throw new IllegalArgumentException("--scenario needs a value"); + } + scenario = Scenario.from(args[++i], true); + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + return scenario; + } + + private static void printHelp() { + System.out.println("Usage: ./demo [--scenario ] (Windows: .\\demo [--scenario ])"); + System.out.println(); + System.out.println("Scenarios (DB = needs the database: docker compose up -d):"); + Scenario.printList(true); + System.out.println(); + System.out.println("Default: no-equals. Examples:"); + System.out.println(" ./demo --scenario mutable"); + System.out.println(" ./demo --scenario new-items"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Inspect.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Inspect.java new file mode 100644 index 0000000..a3b4afa --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Inspect.java @@ -0,0 +1,384 @@ +package com.amigoscode.equality.demo; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.hibernate.Hibernate; + +/** + * Shows what is inside: the buckets of a HashSet or HashMap (which bucket each element sits in, the + * hash it had when it was added and the hash it has now), and for the database scenarios the rows + * next to the objects in the Set and in the persistence context. Run it with ./inspect (or + * .\inspect on Windows). ./inspect --help lists the scenarios. + */ +public final class Inspect { + + public static void main(String[] args) { + Scenario scenario; + try { + scenario = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (scenario == null) { + printHelp(); + return; + } + + System.out.println(); + System.out.println("Inspect: " + scenario.flag() + " | " + scenario.summary()); + if (!scenario.needsDatabase()) { + switch (scenario) { + case NO_EQUALS -> twoEqualLooking(new Sku("KEYBOARD-01"), new Sku("KEYBOARD-01"), new Sku("KEYBOARD-01"), + "Sku a = new Sku(\"KEYBOARD-01\"), Sku b = new Sku(\"KEYBOARD-01\")"); + case EQUALS_ONLY -> twoEqualLooking(new Money("89.00", "EUR"), new Money("89.00", "EUR"), new Money("89.00", "EUR"), + "Money a = new Money(\"89.00\", \"EUR\"), Money b = new Money(\"89.00\", \"EUR\")"); + case COLLISION -> collision(); + case MUTABLE -> mutable(); + case RECORD -> record(); + default -> throw new IllegalStateException(scenario.flag()); + } + System.out.println(); + return; + } + if (!Db.isUp(scenario, true)) { + return; + } + try (Shop shop = Shop.start()) { + switch (scenario) { + case NEW_ITEMS -> newItems(shop); + case REMOVE_ITEM -> removeItem(shop); + case LAZY -> lazy(shop); + case PROXY -> proxy(shop); + default -> throw new IllegalStateException(scenario.flag()); + } + } + System.out.println(); + } + + // ---- Plain Java ---- + + private static void twoEqualLooking(Object a, Object b, Object probe, String made) { + Set set = new HashSet<>(); + set.add(a); + set.add(b); + System.out.println(); + System.out.println(" " + made); + System.out.println(" a.equals(b) is " + a.equals(b)); + System.out.println(); + printBuckets("after set.add(a); set.add(b)", set, named(a, "a", b, "b")); + System.out.println(); + printLookup("set.contains(c), where c is one more object made from the same values", set, probe); + } + + private static void collision() { + Set set = new HashSet<>(); + set.add("Aa"); + set.add("BB"); + set.add("KEYBOARD-01"); + System.out.println(); + System.out.println(" \"Aa\".hashCode() is " + "Aa".hashCode() + " and \"BB\".hashCode() is " + "BB".hashCode() + + ". \"Aa\".equals(\"BB\") is false."); + System.out.println(); + printBuckets("after set.add(\"Aa\"); set.add(\"BB\"); set.add(\"KEYBOARD-01\")", set, named()); + System.out.println(); + printLookup("set.contains(\"BB\")", set, "BB"); + } + + private static void mutable() { + Cart cart = new Cart(); + CartLine keyboard = new CartLine(new Sku("KEYBOARD-01"), 1); + CartLine mouse = new CartLine(new Sku("MOUSE-01"), 2); + cart.add(keyboard); + cart.add(mouse); + System.out.println(); + printBuckets("after cart.add(1 x KEYBOARD-01); cart.add(2 x MOUSE-01)", cart.backingSet(), named()); + System.out.println(); + keyboard.changeQuantity(3); + printBuckets("after keyboard.changeQuantity(3). Nothing in the table moves by itself", cart.backingSet(), named()); + System.out.println(); + printLookup("cart.contains(keyboard), the very same object", cart.backingSet(), keyboard); + } + + private static void record() { + List skus = new ArrayList<>(List.of(new Sku("KEYBOARD-01"), new Sku("MOUSE-01"))); + Bundle desk = new Bundle("Desk set", skus); + Map prices = new HashMap<>(); + prices.put(desk, new Money("119.00", "EUR")); + System.out.println(); + printBuckets("after prices.put(desk, 119.00 EUR)", prices, named()); + System.out.println(); + skus.add(new Sku("HEADSET-01")); + printBuckets("after skus.add(HEADSET-01), on the caller's list", prices, named()); + System.out.println(); + printLookup("prices.get(desk), the very same object", prices, desk); + } + + // ---- JPA ---- + + private static void newItems(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Product mouse = products.findBySku(ShopData.MOUSE).orElseThrow(); + Order order = new Order("ana"); + LineItem first = order.add(keyboard, 1); + LineItem second = order.add(mouse, 2); + Map names = named(first, "first (keyboard)", second, "second (mouse)"); + + System.out.println(); + System.out.println("Step 1. LineItem first = order.add(keyboard, 1); LineItem second = order.add(mouse, 2)"); + System.out.println(" first.equals(second) is " + first.equals(second) + " (ids: " + first.getId() + ", " + second.getId() + ")"); + System.out.println(); + printBuckets("of order.items, before the save", order.backingSet(), names); + System.out.println(); + + shop.em.persist(order); + shop.em.flush(); + System.out.println("Step 2. em.persist(order); em.flush()"); + System.out.println(); + printItems(order, List.of(first, second), names); + System.out.println(); + System.out.println("ROWS IN line_item (this transaction's view)"); + shop.printLineItemRows(); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT (one Java object per row, for this transaction)"); + shop.printPersistenceContext(); + }); + } + + private static void removeItem(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + Product headset = products.findBySku(ShopData.HEADSET).orElseThrow(); + Order order = new Order("ana"); + LineItem item = order.add(headset, 1); + Map names = named(item, "item (headset)"); + + System.out.println(); + System.out.println("Step 1. LineItem item = order.add(headset, 1) item.getId() is " + item.getId()); + System.out.println(); + printBuckets("of order.items, before the save", order.backingSet(), names); + System.out.println(); + + shop.em.persist(order); + shop.em.flush(); + System.out.println("Step 2. em.persist(order); em.flush() item.getId() is " + item.getId()); + System.out.println(); + printItems(order, List.of(item), names); + System.out.println(); + printLookup("order.remove(item) first looks for it", order.backingSet(), item); + System.out.println(); + + boolean removed = order.remove(item); + SqlRecorder.start(); + shop.em.flush(); + List sql = SqlRecorder.stop(); + System.out.println("Step 3. order.remove(item) returned " + removed + "; em.flush()"); + System.out.println(); + System.out.println("SQL SENT BY THE FLUSH"); + Tool.sql(sql); + System.out.println(); + System.out.println("ROWS IN line_item (this transaction's view)"); + shop.printLineItemRows(); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT (one Java object per row, for this transaction)"); + shop.printPersistenceContext(); + }); + } + + private static void lazy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + List all = products.findAll(); + System.out.println(); + System.out.println("Step 1. List all = products.findAll()"); + System.out.println(); + printProducts(all); + System.out.println(); + + SqlRecorder.start(); + Set set = new HashSet<>(all); + List sql = SqlRecorder.stop(); + System.out.println("Step 2. new HashSet<>(all)"); + System.out.println(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + printProducts(all); + System.out.println(); + printBuckets("of the HashSet", set, named()); + }); + } + + private static void proxy(Shop shop) { + long orderId = ShopData.insertOrder(shop.jdbc, "ana", ShopData.KEYBOARD); + shop.inTransaction(() -> { + Order order = shop.em.find(Order.class, orderId); + LineItem item = order.getItems().iterator().next(); + System.out.println(); + System.out.println("Step 1. Order order = em.find(Order.class, " + orderId + "); LineItem item = "); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT"); + shop.printPersistenceContext(); + System.out.println(); + + Product proxy = item.getProduct(); + System.out.println("Step 2. Product proxy = item.getProduct(). Each line shows the SQL it sent, if any."); + System.out.println(); + traced("proxy.getClass()", () -> proxy.getClass().getSimpleName()); + traced("proxy.getClass().getSuperclass()", () -> proxy.getClass().getSuperclass().getSimpleName()); + traced("Hibernate.isInitialized(proxy)", () -> Hibernate.isInitialized(proxy)); + traced("proxy.getId()", proxy::getId); + traced("the field proxy.sku, read directly", () -> field(proxy, "sku")); + traced("Hibernate.getClass(proxy)", () -> Hibernate.getClass(proxy).getSimpleName()); + traced("Hibernate.isInitialized(proxy)", () -> Hibernate.isInitialized(proxy)); + traced("the field proxy.sku, read directly", () -> field(proxy, "sku")); + traced("proxy.getSku()", proxy::getSku); + traced("Hibernate.unproxy(proxy)", () -> Tool.identity(Hibernate.unproxy(proxy))); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT"); + shop.printPersistenceContext(); + }); + } + + // ---- Printing ---- + + /** + * Labels for objects, looked up by identity. A normal Map would call the very equals and + * hashCode this tool is inspecting, and Map.of refuses two keys that are equal. + */ + private static Map named(Object... objectsAndLabels) { + Map names = new IdentityHashMap<>(); + for (int i = 0; i < objectsAndLabels.length; i += 2) { + names.put(objectsAndLabels[i], (String) objectsAndLabels[i + 1]); + } + return names; + } + + /** Prints the table of a HashSet or HashMap: bucket, element, the hash it was added with, its hash now. */ + private static void printBuckets(String title, Object setOrMap, Map names) { + Object table = setOrMap instanceof Set set ? Buckets.unwrap(set) : setOrMap; + int size = Buckets.tableSize(table); + List entries = Buckets.entries(table); + System.out.println("BUCKETS " + title); + System.out.println(" " + entries.size() + (entries.size() == 1 ? " element" : " elements") + " in a table of " + + size + " buckets (empty buckets not shown)" + + (setOrMap instanceof Set set && Buckets.isHibernateSet(set) ? "; the HashSet inside Hibernate's PersistentSet" : "")); + List rows = Tool.rows("bucket", "element", "Java object", "hash when added", "hashCode() now", "a lookup goes to"); + for (Buckets.Entry entry : entries) { + Object key = entry.key(); + int now = key.hashCode(); + int bucketNow = Buckets.bucketOf(now, size); + String label = names.getOrDefault(key, String.valueOf(key)); + rows.add(new String[] {String.valueOf(entry.bucket()), label, Tool.identity(key), + String.valueOf(entry.hashAtInsert()), String.valueOf(now), + now == entry.hashAtInsert() ? String.valueOf(bucketNow) + : bucketNow + (bucketNow == entry.bucket() ? " <- HASH CHANGED" : " <- WRONG BUCKET")}); + } + Tool.table(rows); + } + + private static void printLookup(String title, Object setOrMap, Object probe) { + Object table = setOrMap instanceof Set set ? Buckets.unwrap(set) : setOrMap; + System.out.println("LOOKUP " + title); + for (String step : Buckets.lookup(table, probe)) { + System.out.println(" " + step); + } + boolean found = setOrMap instanceof Set set ? set.contains(probe) : ((Map) setOrMap).containsKey(probe); + System.out.println(" " + (setOrMap instanceof Set ? "contains" : "containsKey") + " returns " + found); + } + + private static void printItems(Order order, List items, Map names) { + System.out.println("THE ITEMS YOU ADDED, AND WHAT order.items SAYS ABOUT THEM"); + List rows = Tool.rows("item", "id", "in the Set's table?", "order.getItems().contains(item)"); + Set inTable = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + Buckets.entries(Buckets.unwrap(order.backingSet())).forEach(entry -> inTable.add(entry.key())); + for (LineItem item : items) { + rows.add(new String[] {names.get(item), String.valueOf(item.getId()), inTable.contains(item) ? "yes" : "no", + String.valueOf(order.getItems().contains(item))}); + } + Tool.table(rows); + System.out.println(); + printBuckets("of order.items, after the save", order.backingSet(), names); + } + + private static void printProducts(List products) { + List rows = Tool.rows("product", "Java object", "tags loaded?"); + for (Product product : products) { + rows.add(new String[] {product.getSku(), Tool.identity(product), Hibernate.isInitialized(product.getTags()) ? "yes" : "no"}); + } + Tool.table(rows); + } + + private static void traced(String call, java.util.function.Supplier work) { + SqlRecorder.start(); + Object result = Tool.attempt(work); + List sql = SqlRecorder.stop(); + Tool.line(call, result, sql.isEmpty() ? "no SQL" : "SQL: " + String.join("; ", sql)); + } + + private static Object field(Object target, String name) { + try { + Field field = Product.class.getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + // ---- Options ---- + + private static Scenario parse(String[] args) { + Scenario scenario = Scenario.EQUALS_ONLY; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + if (i + 1 >= args.length) { + throw new IllegalArgumentException("--scenario needs a value"); + } + scenario = Scenario.from(args[++i], false); + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + return scenario; + } + + private static void printHelp() { + System.out.println("Usage: ./inspect [--scenario ] (Windows: .\\inspect [--scenario ])"); + System.out.println(); + System.out.println("Scenarios (DB = needs the database: docker compose up -d):"); + Scenario.printList(false); + System.out.println(); + System.out.println("Default: equals-only. Examples:"); + System.out.println(" ./inspect --scenario mutable"); + System.out.println(" ./inspect --scenario remove-item"); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Scenario.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Scenario.java new file mode 100644 index 0000000..f929863 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Scenario.java @@ -0,0 +1,79 @@ +package com.amigoscode.equality.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** What ./demo and ./inspect can show. The first four are plain Java, the rest use the database. */ +enum Scenario { + + NO_EQUALS("no-equals", "1, 2", false, true, "Sku has no equals and no hashCode of its own"), + EQUALS_ONLY("equals-only", "1, 2, 3", false, true, "Money has equals, but no hashCode of its own"), + COLLISION("collision", "3", false, false, "two different Strings with the same hashCode (./inspect only)"), + MUTABLE("mutable", "1, 4", false, true, "a CartLine changes while it sits in a HashSet"), + RECORD("record", "4", false, true, "a record that keeps the caller's list, used as a Map key"), + NEW_ITEMS("new-items", "5, 6", true, true, "two new line items added to one order, then saved"), + REMOVE_ITEM("remove-item", "5, 6", true, true, "a line item removed after the save gave it an id"), + LAZY("lazy", "7", true, true, "products put in a HashSet: hashCode reads the lazy tags"), + PROXY("proxy", "7", true, true, "a product compared with a Hibernate proxy of the same row"); + + private final String flag; + private final String tasks; + private final boolean database; + private final boolean inDemo; + private final String summary; + + Scenario(String flag, String tasks, boolean database, boolean inDemo, String summary) { + this.flag = flag; + this.tasks = tasks; + this.database = database; + this.inDemo = inDemo; + this.summary = summary; + } + + String flag() { + return flag; + } + + String tasks() { + return tasks; + } + + boolean needsDatabase() { + return database; + } + + boolean inDemo() { + return inDemo; + } + + String summary() { + return summary; + } + + static Scenario from(String value, boolean demo) { + String wanted = value.toLowerCase(Locale.ROOT); + return Arrays.stream(values()) + .filter(scenario -> scenario.flag.equals(wanted) && (scenario.inDemo || !demo)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown scenario: " + value)); + } + + /** The plain-Java (false) or the database (true) scenarios, as "a, b, c". */ + static String names(boolean database) { + return Arrays.stream(values()) + .filter(scenario -> scenario.database == database && scenario.inDemo) + .map(Scenario::flag) + .collect(Collectors.joining(", ")); + } + + static void printList(boolean demo) { + for (Scenario scenario : values()) { + if (demo && !scenario.inDemo) { + continue; + } + System.out.printf(" %-12s %-3s Task %-8s %s%n", scenario.flag, + scenario.database ? "DB" : "", scenario.tasks, scenario.summary); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Shop.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Shop.java new file mode 100644 index 0000000..ec64fac --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Shop.java @@ -0,0 +1,97 @@ +package com.amigoscode.equality.demo; + +import com.amigoscode.equality.EqualityApplication; +import com.amigoscode.equality.db.ShopData; +import jakarta.persistence.EntityManager; +import java.util.List; +import java.util.function.Supplier; +import org.hibernate.engine.spi.EntityHolder; +import org.hibernate.engine.spi.EntityKey; +import org.hibernate.engine.spi.SessionImplementor; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * What the database scenarios of ./demo and ./inspect share: the real application (Spring, Hibernate, + * Postgres), a fresh set of products, transactions, and a look into the persistence context. + */ +final class Shop implements AutoCloseable { + + private final ConfigurableApplicationContext context; + final JdbcTemplate jdbc; + final EntityManager em; + private final TransactionTemplate transactions; + + private Shop(ConfigurableApplicationContext context) { + this.context = context; + this.jdbc = context.getBean(JdbcTemplate.class); + this.em = context.getBean(EntityManager.class); + this.transactions = context.getBean(TransactionTemplate.class); + } + + static Shop start() { + SpringApplication app = new SpringApplication(EqualityApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + Shop shop = new Shop(app.run("--logging.level.root=WARN")); + ShopData.reset(shop.jdbc); + return shop; + } + + T bean(Class type) { + return context.getBean(type); + } + + T inTransaction(Supplier work) { + return transactions.execute(status -> work.get()); + } + + void inTransaction(Runnable work) { + transactions.executeWithoutResult(status -> work.run()); + } + + /** The rows of line_item, as the database has them right now (inside a transaction: as this transaction sees them). */ + void printLineItemRows() { + List rows = Tool.rows("id", "order_id", "sku", "quantity"); + jdbc.query(""" + select li.id, li.order_id, p.sku, li.quantity + from line_item li join product p on p.id = li.product_id + order by li.id + """, row -> { + rows.add(new String[] {row.getString(1), row.getString(2), row.getString(3), row.getString(4)}); + }); + Tool.table(rows); + } + + int lineItemRows() { + return jdbc.queryForObject("select count(*) from line_item", Integer.class); + } + + /** Every entity the current transaction's persistence context holds, and whether it is loaded. */ + void printPersistenceContext() { + SessionImplementor session = em.unwrap(SessionImplementor.class); + List rows = Tool.rows("entity", "Java object", "state"); + for (var holder : session.getPersistenceContextInternal().getEntityHoldersByKey().entrySet()) { + EntityKey key = holder.getKey(); + EntityHolder value = holder.getValue(); + Object object = value.getProxy() != null ? value.getProxy() : value.getEntity(); + String state = value.getProxy() == null ? "loaded" + : value.getEntity() == null ? "proxy, row not loaded" : "proxy, row loaded"; + rows.add(new String[] {simpleName(key.getEntityName()) + "#" + key.getIdentifier(), Tool.identity(object), state}); + } + rows.subList(1, rows.size()).sort((a, b) -> a[0].compareTo(b[0])); + Tool.table(rows); + } + + private static String simpleName(String entityName) { + return entityName.substring(entityName.lastIndexOf('.') + 1); + } + + @Override + public void close() { + context.close(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Tool.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Tool.java new file mode 100644 index 0000000..86c1722 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/demo/Tool.java @@ -0,0 +1,86 @@ +package com.amigoscode.equality.demo; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +/** Small printing helpers shared by Demo and Inspect. */ +final class Tool { + + private Tool() { + } + + /** One line of evidence: what was called, and what it returned. */ + static void line(String call, Object result) { + line(call, result, ""); + } + + static void line(String call, Object result, String note) { + String value = String.valueOf(result); + String text = String.format(" %-36s %-" + Math.max(12, value.length()) + "s %s", call, value, note); + System.out.println(text.stripTrailing()); + } + + /** Runs the call. An exception is returned as its text instead of stopping the demo. */ + static Object attempt(Supplier call) { + try { + return call.get(); + } catch (RuntimeException e) { + return describe(e); + } + } + + /** "LazyInitializationException: Cannot lazily initialize ..." */ + static String describe(Throwable e) { + String message = e.getMessage() == null ? "" : e.getMessage().lines().findFirst().orElse(""); + return e.getClass().getSimpleName() + (message.isEmpty() ? "" : ": " + message); + } + + /** ClassName@1b2c3d: which Java object this is. */ + static String identity(Object object) { + return object.getClass().getSimpleName() + "@" + Integer.toHexString(System.identityHashCode(object)); + } + + /** Prints rows as a plain text table. The first row is the header. */ + static void table(List rows) { + if (rows.size() == 1) { + System.out.println(" (none)"); + return; + } + 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()); + } + } + } + + static List rows(String... header) { + List rows = new ArrayList<>(); + rows.add(header); + return rows; + } + + static void sql(List statements) { + if (statements.isEmpty()) { + System.out.println(" (none)"); + } + for (String statement : statements) { + System.out.println(" " + statement); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/LineItem.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/LineItem.java new file mode 100644 index 0000000..3073c6a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/LineItem.java @@ -0,0 +1,90 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +/** + * One line of an order: a product and a quantity. It has no business key of its own (the same + * product can be ordered twice), so the only thing that identifies it is its id, and the database + * assigns the id when the row is inserted. + */ +@Entity +@Table(name = "line_item") +public class LineItem { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "order_id") + private Order order; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id") + private Product product; + + private int quantity; + + protected LineItem() { + } + + LineItem(Order order, Product product, int quantity) { + this.order = order; + this.product = product; + this.quantity = quantity; + } + + public Long getId() { + return id; + } + + public Order getOrder() { + return order; + } + + public Product getProduct() { + return product; + } + + public int getQuantity() { + return quantity; + } + + // Task 5: the id, with a hashCode that does not use it. + // - Two items are equal only when both have an id and it is the same id. A new item (id null) + // is equal to nothing but itself. + // - hashCode is the same for every LineItem, before and after the id is assigned, so an item + // never moves to another bucket. The price: every LineItem in a HashSet shares one bucket. + // Fine for the handful of items in one order, wrong for a Set of a million. + // - instanceof and getId() so it also works on a Hibernate proxy. getId() on a proxy returns + // the id without loading the row. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof LineItem other)) { + return false; + } + return id != null && id.equals(other.getId()); + } + + @Override + public int hashCode() { + return LineItem.class.hashCode(); + } + + @Override + public String toString() { + // product.getId(), not getSku(): on a proxy the id is known without loading the row. + return "LineItem#" + (id == null ? "new" : id) + " (" + quantity + " x product " + product.getId() + ")"; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/Order.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/Order.java new file mode 100644 index 0000000..abc401f --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/Order.java @@ -0,0 +1,72 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * An order and its line items. The items are a {@code Set}, so every add and remove goes through + * LineItem.hashCode and LineItem.equals. + * + *

Order itself does not override equals or hashCode: nothing puts orders in a Set or compares + * two of them. Nothing to change here. + */ +@Entity +@Table(name = "orders") +public class Order { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String customer; + + // orphanRemoval: an item removed from this Set is deleted from the database when the + // transaction commits. Only if it really leaves the Set. + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) + private Set items = new HashSet<>(); + + protected Order() { + } + + public Order(String customer) { + this.customer = customer; + } + + public Long getId() { + return id; + } + + public String getCustomer() { + return customer; + } + + /** Adds a new line item. Returns it, whether or not the Set accepted it. */ + public LineItem add(Product product, int quantity) { + LineItem item = new LineItem(this, product, quantity); + items.add(item); + return item; + } + + /** Returns false when the Set did not find the item, and so did not remove it. */ + public boolean remove(LineItem item) { + return items.remove(item); + } + + public Set getItems() { + return Collections.unmodifiableSet(items); + } + + /** The Set Hibernate manages, so ./inspect can show its buckets. */ + public Set backingSet() { + return items; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderLine.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderLine.java new file mode 100644 index 0000000..6e1efe9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderLine.java @@ -0,0 +1,5 @@ +package com.amigoscode.equality.order; + +/** What the customer asked for: this many of this SKU. */ +public record OrderLine(String sku, int quantity) { +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderRepository.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderRepository.java new file mode 100644 index 0000000..c03c23a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderRepository.java @@ -0,0 +1,6 @@ +package com.amigoscode.equality.order; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrderRepository extends JpaRepository { +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderService.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderService.java new file mode 100644 index 0000000..14b691b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/OrderService.java @@ -0,0 +1,43 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Places orders. Nothing to change here: the bugs are in the equals and hashCode of the entities. */ +@Service +public class OrderService { + + private final OrderRepository orders; + private final ProductRepository products; + + public OrderService(OrderRepository orders, ProductRepository products) { + this.orders = orders; + this.products = products; + } + + /** + * Creates the order with one line item per requested line and saves it. Then it drops every + * line the warehouse cannot deliver. That happens after the save on purpose: the stock + * reservation is made with the order number, which only exists once the order is saved. + */ + @Transactional + public Order placeOrder(String customer, List lines) { + Order order = new Order(customer); + for (OrderLine line : lines) { + Product product = products.findBySku(line.sku()).orElseThrow(() -> new UnknownProductException(line.sku())); + order.add(product, line.quantity()); + } + + orders.save(order); // INSERTs the order and its items now: every item gets its id here + + for (LineItem item : List.copyOf(order.getItems())) { + if (item.getProduct().getStock() < item.getQuantity()) { + order.remove(item); // out of stock: orphanRemoval deletes the row at commit + } + } + return order; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/UnknownProductException.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/UnknownProductException.java new file mode 100644 index 0000000..33bb573 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/order/UnknownProductException.java @@ -0,0 +1,8 @@ +package com.amigoscode.equality.order; + +public class UnknownProductException extends RuntimeException { + + public UnknownProductException(String sku) { + super("No product with SKU " + sku); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Product.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Product.java new file mode 100644 index 0000000..d702b24 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Product.java @@ -0,0 +1,111 @@ +package com.amigoscode.equality.product; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.Set; +import org.hibernate.annotations.NaturalId; + +/** A product in the catalogue. Its SKU is unique and never changes. */ +@Entity +public class Product { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // Task 7: the business key. Unique in the database, known before the row is inserted, and never + // changed. @NaturalId tells Hibernate the same thing: it refuses to update an immutable natural id. + @NaturalId + @Column(nullable = false, unique = true, updatable = false) + private String sku; + + private String name; + + private BigDecimal price; + + private int stock; + + @ManyToMany + @JoinTable(name = "product_tag", + joinColumns = @JoinColumn(name = "product_id"), + inverseJoinColumns = @JoinColumn(name = "tag_id")) + private Set tags = new HashSet<>(); + + protected Product() { + } + + public Product(String sku, String name, BigDecimal price, int stock) { + this.sku = sku; + this.name = name; + this.price = price; + this.stock = stock; + } + + public Long getId() { + return id; + } + + public String getSku() { + return sku; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public Set getTags() { + return tags; + } + + public void rename(String name) { + this.name = name; + } + + public void changePrice(BigDecimal price) { + this.price = price; + } + + // Task 7: equal when the SKU is equal, and nothing else. + // - instanceof, not getClass(): a Hibernate proxy is a subclass of Product, so + // getClass() == other.getClass() is false for the same row. + // - other.getSku(), not other.sku: on a proxy the fields are never filled in. Only the getter + // goes through to the loaded row. + // - no tags, no price, no name: hashCode never touches a lazy collection (no extra query, no + // LazyInitializationException) and never changes while the product sits in a HashSet. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Product other)) { + return false; + } + return sku.equals(other.getSku()); + } + + @Override + public int hashCode() { + return sku.hashCode(); + } + + @Override + public String toString() { + return sku; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/ProductRepository.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/ProductRepository.java new file mode 100644 index 0000000..ba42a3e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/ProductRepository.java @@ -0,0 +1,15 @@ +package com.amigoscode.equality.product; + +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ProductRepository extends JpaRepository { + + Optional findBySku(String sku); + + /** The product with its tags already loaded, so they can be read after the transaction ends. */ + @Query("select p from Product p left join fetch p.tags where p.sku = :sku") + Optional findBySkuWithTags(@Param("sku") String sku); +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Tag.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Tag.java new file mode 100644 index 0000000..f248f00 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/product/Tag.java @@ -0,0 +1,44 @@ +package com.amigoscode.equality.product; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +/** + * A label on a product: wireless, gaming, audio. + * + *

Exhibit: Tag does NOT override equals or hashCode, in start/ and in solution/. It uses + * Object's: an object is only equal to itself. That is fine inside one transaction, because + * Hibernate gives you one Java object per row there. It stops working as soon as you compare a Tag + * from one transaction with a Tag from another. Task 6 shows both. Do not fix. + */ +@Entity +public class Tag { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + protected Tag() { + } + + public Tag(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Bundle.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Bundle.java new file mode 100644 index 0000000..0cc752e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Bundle.java @@ -0,0 +1,21 @@ +package com.amigoscode.equality.value; + +import java.util.List; +import java.util.Objects; + +/** + * Products sold together at one price, for example "Desk set" = KEYBOARD-01 + MOUSE-01. The shop + * keeps bundle prices in a {@code Map}, so a Bundle is used as a map key. + * + *

A record compares its components with their own equals. For {@code skus} that is + * List.equals: same elements in the same order. + */ +public record Bundle(String name, List skus) { + + // Task 4: a record is only as immutable as its components. List.copyOf makes an unmodifiable + // copy, so changing the list the bundle was built from cannot change the bundle (or its hashCode). + public Bundle { + Objects.requireNonNull(name, "name"); + skus = List.copyOf(skus); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Money.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Money.java new file mode 100644 index 0000000..175a476 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Money.java @@ -0,0 +1,65 @@ +package com.amigoscode.equality.value; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Objects; + +/** + * An amount in a currency, for example 89.00 EUR. A value object: equal amount and currency means + * equal Money. + */ +public final class Money { + + private final BigDecimal amount; + private final String currency; + + public Money(String amount, String currency) { + this(new BigDecimal(amount), currency); + } + + public Money(BigDecimal amount, String currency) { + Objects.requireNonNull(amount, "amount"); + Objects.requireNonNull(currency, "currency"); + // Always two decimals. BigDecimal.equals compares the scale too: 10.0 is not equal to 10.00. + // Setting the scale here means equals and hashCode below only ever see 10.00. + this.amount = amount.setScale(2, RoundingMode.UNNECESSARY); + this.currency = currency; + } + + public BigDecimal amount() { + return amount; + } + + public String currency() { + return currency; + } + + public Money plus(Money other) { + if (!currency.equals(other.currency)) { + throw new IllegalArgumentException("Cannot add " + other.currency + " to " + currency); + } + return new Money(amount.add(other.amount), currency); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Money other)) { + return false; + } + return amount.equals(other.amount) && currency.equals(other.currency); + } + + // Task 2: equal objects must have equal hash codes, so hashCode uses the same fields as equals. + @Override + public int hashCode() { + return Objects.hash(amount, currency); + } + + @Override + public String toString() { + return amount.toPlainString() + " " + currency; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Sku.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Sku.java new file mode 100644 index 0000000..bee4633 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/java/com/amigoscode/equality/value/Sku.java @@ -0,0 +1,25 @@ +package com.amigoscode.equality.value; + +import java.util.Objects; + +/** + * A stock keeping unit: the code that identifies a product, for example KEYBOARD-01. A value + * object: two Skus with the same code are the same Sku. + * + *

A record gets equals, hashCode and toString from its components, so two Skus with the same + * code are equal and have the same hashCode. Task 2. + */ +public record Sku(String code) { + + public Sku { + Objects.requireNonNull(code, "code"); + if (code.isBlank()) { + throw new IllegalArgumentException("A SKU code cannot be blank"); + } + } + + @Override + public String toString() { + return code; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/application.properties b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/application.properties new file mode 100644 index 0000000..ed60b5a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/application.properties @@ -0,0 +1,20 @@ +spring.application.name=equals-and-hashcode + +# No web server: the demo and the tests call the services directly. +spring.main.web-application-type=none + +# Postgres from compose.yaml. Port 5454 so it does not clash with a Postgres you already run. +# Only the JPA part (Tasks 5 to 7) needs it. The plain-Java part runs without a database. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5454/shop} +spring.datasource.username=${DB_USER:shop} +spring.datasource.password=${DB_PASSWORD:shop} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always + +# Lets the demo print, and the tests count, the SQL Hibernate sends. +spring.jpa.properties.hibernate.session_factory.statement_inspector=com.amigoscode.equality.db.SqlRecorder + +# Uncomment to see every SQL statement. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..fcbf2dd --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/main/resources/schema.sql @@ -0,0 +1,30 @@ +create table if not exists tag ( + id bigint generated by default as identity primary key, + name text not null unique +); + +create table if not exists product ( + id bigint generated by default as identity primary key, + sku text not null unique, + name text not null, + price numeric(10, 2) not null, + stock int not null check (stock >= 0) +); + +create table if not exists product_tag ( + product_id bigint not null references product (id), + tag_id bigint not null references tag (id), + primary key (product_id, tag_id) +); + +create table if not exists orders ( + id bigint generated by default as identity primary key, + customer text not null +); + +create table if not exists line_item ( + id bigint generated by default as identity primary key, + order_id bigint not null references orders (id), + product_id bigint not null references product (id), + quantity int not null check (quantity > 0) +); diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/BundleTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/BundleTest.java new file mode 100644 index 0000000..490ef9e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/BundleTest.java @@ -0,0 +1,69 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.util.ArrayList; +import java.util.HashMap; +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 4: Bundle is a record, and a record is only as immutable as its components. */ +@Tag("task4") +class BundleTest { + + private final Sku keyboard = new Sku("KEYBOARD-01"); + private final Sku mouse = new Sku("MOUSE-01"); + private final Sku headset = new Sku("HEADSET-01"); + + @Test + @DisplayName("Bundle: two bundles with the same name and SKUs are equal with the same hashCode: the record writes both (already passing: keep it that way)") + void recordsWriteEqualsAndHashCode() { + Bundle a = new Bundle("Desk set", List.of(keyboard, mouse)); + Bundle b = new Bundle("Desk set", new ArrayList<>(List.of(keyboard, mouse))); + + assertThat(a).isEqualTo(b); + assertThat(a.hashCode()).isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Bundle: changing the list a bundle was made from does not change the bundle, and its price is still found in the Map") + void theCallersListCannotChangeTheBundle() { + Map prices = new HashMap<>(); + List skus = new ArrayList<>(List.of(keyboard, mouse)); + Bundle desk = new Bundle("Desk set", skus); + prices.put(desk, new Money("119.00", "EUR")); + + skus.add(headset); // the caller reuses its list for the next bundle + + assertThat(desk.skus()).as("the bundle's SKUs").containsExactly(keyboard, mouse); + assertThat(prices.get(desk)).as("prices.get(desk)").isEqualTo(new Money("119.00", "EUR")); + } + + @Test + @DisplayName("Bundle: the list that skus() returns cannot be changed") + void skusCannotBeChanged() { + Bundle desk = new Bundle("Desk set", new ArrayList<>(List.of(keyboard, mouse))); + + assertThatThrownBy(() -> desk.skus().add(headset)).isInstanceOf(UnsupportedOperationException.class); + } + + /** A record with an array component. Records compare arrays with ==, like Object.equals. */ + record Barcode(byte[] digits) { + } + + @Test + @DisplayName("A record with an array component compares the array by identity: two Barcodes with the same digits are not equal (this documents the trap)") + void arraysInRecordsCompareByIdentity() { + Barcode a = new Barcode(new byte[] {4, 0, 0, 6}); + Barcode b = new Barcode(new byte[] {4, 0, 0, 6}); + + assertThat(a.equals(b)).as("a.equals(b)").isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/CartLineTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/CartLineTest.java new file mode 100644 index 0000000..1a02863 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/CartLineTest.java @@ -0,0 +1,55 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.value.Sku; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 4: a CartLine changes while it sits in the cart's HashSet. */ +@Tag("task4") +class CartLineTest { + + private final Sku keyboard = new Sku("KEYBOARD-01"); + + @Test + @DisplayName("CartLine: after the quantity changes, the cart still contains the line, and remove takes it out") + void stillFoundAfterTheQuantityChanges() { + Cart cart = new Cart(); + CartLine line = new CartLine(keyboard, 1); + cart.add(line); + + line.changeQuantity(3); + + assertThat(cart.contains(line)).as("cart.contains(line)").isTrue(); + assertThat(cart.remove(line)).as("cart.remove(line)").isTrue(); + assertThat(cart.size()).as("lines left in the cart").isZero(); + } + + @Test + @DisplayName("CartLine: adding the same line again after a change does not put it in the cart twice") + void notAddedTwice() { + Cart cart = new Cart(); + CartLine line = new CartLine(keyboard, 1); + cart.add(line); + + line.changeQuantity(3); + cart.add(line); + + assertThat(cart.size()).as("lines in the cart").isEqualTo(1); + } + + @Test + @DisplayName("CartLine: hashCode stays the same when the quantity changes") + void hashCodeDoesNotChange() { + CartLine line = new CartLine(keyboard, 1); + int before = line.hashCode(); + + line.changeQuantity(3); + + assertThat(line.hashCode()).as("hashCode after the change").isEqualTo(before); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/Check.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/Check.java new file mode 100644 index 0000000..a4daa1a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.equality; + +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. Task 8 is an inspection task with nothing to run: you answer questions. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: one value, one order line (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See it break"); + TASKS.put("2", "Task 2: Fix the value objects"); + TASKS.put("3", "Task 3: Inspect the hash table"); + TASKS.put("4", "Task 4: Fix the keys that change"); + TASKS.put("5", "Task 5: Fix the line items (generated id)"); + TASKS.put("6", "Task 6: Inspect the persistence context"); + TASKS.put("7", "Task 7: Fix the product (all-fields equals, lazy loading, proxies)"); + } + + 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/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/HashContractTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/HashContractTest.java new file mode 100644 index 0000000..35c931b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/HashContractTest.java @@ -0,0 +1,49 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +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 3. These tests pass on purpose: they pin down the other half of the contract. Equal objects + * must have the same hash. The same hash does NOT mean equal. + */ +@Tag("task3") +class HashContractTest { + + @Test + @DisplayName("\"Aa\" and \"BB\" have the same hashCode and a HashSet keeps both: the same hash does not mean equal (this documents the contract)") + void sameHashIsNotEqual() { + assertThat("Aa".hashCode()).isEqualTo("BB".hashCode()); + + Set set = new HashSet<>(Set.of("Aa", "BB")); + + assertThat(set).containsExactlyInAnyOrder("Aa", "BB"); + } + + /** Legal, and slow: every object has the same hash. */ + record SameHash(int value) { + @Override + public int hashCode() { + return 42; + } + } + + @Test + @DisplayName("A hashCode that returns 42 for every object is legal: the HashSet is still correct, only slower (this documents the contract)") + void constantHashIsLegal() { + Set set = new HashSet<>(); + for (int i = 0; i < 100; i++) { + set.add(new SameHash(i)); + } + set.add(new SameHash(7)); + + assertThat(set).hasSize(100); + assertThat(set.contains(new SameHash(99))).isTrue(); + assertThat(set.contains(new SameHash(100))).isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/LineItemIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/LineItemIT.java new file mode 100644 index 0000000..83f003d --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/LineItemIT.java @@ -0,0 +1,84 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: LineItem has no business key. Its id is assigned by the database, during the save. */ +@Tag("task5") +class LineItemIT extends IntegrationTest { + + @Test + @DisplayName("LineItem: two new line items added to an order before it is saved are both saved") + void twoNewItemsAreBothSaved() { + orderService.placeOrder("ana", List.of(new OrderLine(ShopData.KEYBOARD, 1), new OrderLine(ShopData.MOUSE, 2))); + + assertThat(lineItemRows()).as("rows in line_item for 2 ordered lines").isEqualTo(2); + } + + @Test + @DisplayName("LineItem: an out-of-stock line removed after the order was saved is really removed: its row is deleted") + void removedAfterTheSave() { + Order order = orderService.placeOrder("ana", List.of(new OrderLine(ShopData.HEADSET, 1))); + + assertThat(order.getItems()).as("items left in the order").isEmpty(); + assertThat(lineItemRows()).as("rows in line_item").isZero(); + } + + @Test + @DisplayName("LineItem: an item is still found in order.getItems() after the save gave it an id") + void stillFoundAfterTheIdIsAssigned() { + inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Order order = new Order("ana"); + LineItem item = order.add(keyboard, 1); + + em.persist(order); + + assertThat(item.getId()).as("id after persist").isNotNull(); + assertThat(order.getItems().contains(item)).as("order.getItems().contains(item)").isTrue(); + }); + } + + @Test + @DisplayName("LineItem: the same row loaded in two transactions gives two objects that are equal (already passing: keep it that way)") + void sameRowInTwoTransactionsIsEqual() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD); + long itemId = jdbc.queryForObject("select id from line_item where order_id = ?", Long.class, orderId); + + LineItem first = inTransaction(() -> em.find(LineItem.class, itemId)); + LineItem second = inTransaction(() -> em.find(LineItem.class, itemId)); + + assertThat(first).as("two loads, two Java objects").isNotSameAs(second); + assertThat(first.equals(second)).as("first.equals(second)").isTrue(); + } + + @Test + @DisplayName("LineItem: an item is equal to a Hibernate proxy of the same row, and comparing them does not load the row") + void equalToItsProxyWithoutLoadingIt() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD); + long itemId = jdbc.queryForObject("select id from line_item where order_id = ?", Long.class, orderId); + LineItem loaded = inTransaction(() -> em.find(LineItem.class, itemId)); + + inTransaction(() -> { + LineItem proxy = em.getReference(LineItem.class, itemId); + + SqlRecorder.start(); + boolean equal = loaded.equals(proxy); + List sql = SqlRecorder.stop(); + + assertThat(equal).as("loaded.equals(proxy), proxy class " + proxy.getClass().getSimpleName()).isTrue(); + assertThat(sql).as("SQL sent by loaded.equals(proxy)").isEmpty(); + }); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/MoneyTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/MoneyTest.java new file mode 100644 index 0000000..96f1f6a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/MoneyTest.java @@ -0,0 +1,47 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.value.Money; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 2: Money already has equals. Equal objects must also have equal hash codes. */ +@Tag("task2") +class MoneyTest { + + @Test + @DisplayName("Money: equal amounts have the same hashCode, also when one is written 10.5 and the other 10.50") + void equalMoneyHasEqualHashCodes() { + Money a = new Money("10.5", "EUR"); + Money b = new Money("10.50", "EUR"); + + assertThat(a.equals(b)).as("a.equals(b)").isTrue(); + assertThat(a.hashCode()).as("hashCode of a and of b").isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Money: a HashSet keeps one of two equal amounts, and HashMap.get finds the value by an equal key") + void hashCollectionsAgreeWithEquals() { + Set amounts = new HashSet<>(); + amounts.add(new Money("89.00", "EUR")); + amounts.add(new Money("89.00", "EUR")); + + Map labels = new HashMap<>(); + labels.put(new Money("0.00", "EUR"), "free"); + + assertThat(amounts).as("HashSet of two equal amounts").hasSize(1); + assertThat(labels.get(new Money("0.00", "EUR"))).as("labels.get").isEqualTo("free"); + } + + @Test + @DisplayName("Money: 10.00 EUR is not equal to 10.00 USD (already passing: keep it that way)") + void currencyIsPartOfEquality() { + assertThat(new Money("10.00", "EUR").equals(new Money("10.00", "USD"))).isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java new file mode 100644 index 0000000..4d0b209 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java @@ -0,0 +1,73 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +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 1. These tests pass on purpose: they pin down what Java does when a class does not write its + * own equals and hashCode, and in which order a HashSet asks the two questions. + */ +@Tag("task1") +class ObjectIdentityTest { + + /** A class with no equals and no hashCode of its own, like Sku in start/. */ + static final class Code { + final String value; + + Code(String value) { + this.value = value; + } + } + + @Test + @DisplayName("A class without its own equals inherits Object.equals: same values are not enough, an object is only equal to itself (this documents the cause)") + void objectEqualsIsIdentity() { + Code a = new Code("KEYBOARD-01"); + Code b = new Code("KEYBOARD-01"); + + assertThat(a.equals(b)).as("a.equals(b)").isFalse(); + assertThat(a.equals(a)).as("a.equals(a)").isTrue(); + assertThat(new HashSet<>(Set.of(a, b))).as("a HashSet of a and b").hasSize(2); + } + + /** Counts how often a HashSet calls equals, so you can see when it does. */ + static final class Counted { + static int equalsCalls; + final int hash; + + Counted(int hash) { + this.hash = hash; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object o) { + equalsCalls++; + return o instanceof Counted other && other.hash == hash; + } + } + + @Test + @DisplayName("HashSet.add asks hashCode first, and only calls equals for an element with the same hash (this documents the order)") + void hashCodeFirstThenEquals() { + Set set = new HashSet<>(); + set.add(new Counted(1)); + + Counted.equalsCalls = 0; + set.add(new Counted(2)); + assertThat(Counted.equalsCalls).as("equals calls when the hash is different").isZero(); + + set.add(new Counted(1)); + assertThat(Counted.equalsCalls).as("equals calls when the hash is the same").isEqualTo(1); + assertThat(set).hasSize(2); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/OrderBasicsIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/OrderBasicsIT.java new file mode 100644 index 0000000..11beb1b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/OrderBasicsIT.java @@ -0,0 +1,26 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline: one order with one line works. Passes from the start and must stay green. */ +@Tag("baseline") +class OrderBasicsIT extends IntegrationTest { + + @Test + @DisplayName("An order placed with one line is saved with that line") + void oneLineIsSaved() { + orderService.placeOrder("ana", List.of(new OrderLine(ShopData.KEYBOARD, 2))); + + assertThat(jdbc.queryForList(""" + select p.sku, li.quantity from line_item li join product p on p.id = li.product_id + """)).as("rows in line_item").containsExactly(java.util.Map.of("sku", ShopData.KEYBOARD, "quantity", 2)); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/PersistenceContextIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/PersistenceContextIT.java new file mode 100644 index 0000000..59d0c8b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/PersistenceContextIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.Tag; +import com.amigoscode.equality.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Task 6. These tests pass on purpose: they pin down what the persistence context promises (one + * Java object per row, inside one transaction) and where that promise ends. + */ +@org.junit.jupiter.api.Tag("task6") +class PersistenceContextIT extends IntegrationTest { + + @Test + @DisplayName("Inside one transaction, loading the same row twice gives the same Java object, so even Object.equals works (this documents the guarantee)") + void oneRowOneObjectInOneTransaction() { + inTransaction(() -> { + Product byId = em.find(Product.class, productId(ShopData.KEYBOARD)); + Product bySku = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + + assertThat(bySku).as("find by id and find by SKU").isSameAs(byId); + }); + } + + @Test + @DisplayName("In two transactions, the same row comes back as two different Java objects (this documents where the guarantee ends)") + void twoObjectsInTwoTransactions() { + Product first = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + Product second = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + assertThat(second).isNotSameAs(first); + } + + @Test + @DisplayName("Tag uses Object.equals: a product's tags contain the tag loaded in the same transaction, and not the same tag loaded in another one (this documents the trap)") + void identityEqualsAcrossTransactions() { + Tag gamingFromEarlier = inTransaction(() -> gamingTag()); + + inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Tag gamingNow = gamingTag(); + + assertThat(keyboard.getTags().contains(gamingNow)).as("contains the gaming tag from this transaction").isTrue(); + assertThat(keyboard.getTags().contains(gamingFromEarlier)).as("contains the gaming tag from another transaction").isFalse(); + }); + } + + private Tag gamingTag() { + return em.createQuery("select t from Tag t where t.name = 'gaming'", Tag.class).getSingleResult(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductIT.java new file mode 100644 index 0000000..a7e571e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductIT.java @@ -0,0 +1,88 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.support.IntegrationTest; +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7: Product has a business key, its SKU. */ +@Tag("task7") +class ProductIT extends IntegrationTest { + + @Test + @DisplayName("Product: putting loaded products in a HashSet sends no SQL (hashCode does not load the lazy tags)") + void hashingSendsNoSql() { + inTransaction(() -> { + List all = products.findAll(); + + SqlRecorder.start(); + Set set = new HashSet<>(all); + List sql = SqlRecorder.stop(); + + assertThat(set).hasSize(3); + assertThat(sql).as("SQL sent while adding 3 products to a HashSet").isEmpty(); + }); + } + + @Test + @DisplayName("Product: products can be put in a HashSet after their transaction has ended (no LazyInitializationException)") + void hashingWorksAfterTheTransaction() { + List all = inTransaction(() -> products.findAll()); + + assertThatCode(() -> new HashSet<>(all)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("Product: a product is equal to a Hibernate proxy of the same row, in both directions") + void equalToItsProxyBothWays() { + Product keyboard = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + inTransaction(() -> { + Product proxy = em.getReference(Product.class, keyboard.getId()); + + assertThat(keyboard.equals(proxy)).as("keyboard.equals(proxy), proxy class " + proxy.getClass().getSimpleName()).isTrue(); + assertThat(proxy.equals(keyboard)).as("proxy.equals(keyboard)").isTrue(); + }); + } + + @Test + @DisplayName("Product: the products of an order (lazy proxies) contain the same product loaded by the catalogue in another transaction") + void foundAmongTheProductsOfAnOrder() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD, ShopData.MOUSE); + Product keyboard = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + inTransaction(() -> { + Order order = em.find(Order.class, orderId); + Set inOrder = order.getItems().stream().map(LineItem::getProduct).collect(Collectors.toSet()); + + assertThat(inOrder.contains(keyboard)).as("products in the order contain the keyboard").isTrue(); + }); + } + + @Test + @DisplayName("Product: a new product is still found in its HashSet after the save gave it an id") + void stillFoundAfterTheIdIsAssigned() { + inTransaction(() -> { + Product cable = new Product("CABLE-01", "USB-C cable", new BigDecimal("9.00"), 100); + Set newProducts = new HashSet<>(Set.of(cable)); + + em.persist(cable); + + assertThat(cable.getId()).as("id after persist").isNotNull(); + assertThat(newProducts.contains(cable)).as("newProducts.contains(cable)").isTrue(); + }); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductTest.java new file mode 100644 index 0000000..7107634 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ProductTest.java @@ -0,0 +1,29 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.product.Product; +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 7, without a database: the price of a product changes, its identity does not. */ +@Tag("task7") +class ProductTest { + + @Test + @DisplayName("Product: changing the price does not change the hashCode, so the product is not lost from a HashSet") + void priceChangeDoesNotLoseIt() { + Product keyboard = new Product("KEYBOARD-01", "Mechanical keyboard", new BigDecimal("89.00"), 10); + Set onSale = new HashSet<>(Set.of(keyboard)); + int before = keyboard.hashCode(); + + keyboard.changePrice(new BigDecimal("79.00")); + + assertThat(keyboard.hashCode()).as("hashCode after the price change").isEqualTo(before); + assertThat(onSale.contains(keyboard)).as("onSale.contains(keyboard)").isTrue(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/SkuTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/SkuTest.java new file mode 100644 index 0000000..f4054e0 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/SkuTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 2: Sku is a value object. Two Skus with the same code are the same Sku. */ +@Tag("task2") +class SkuTest { + + @Test + @DisplayName("Sku: two Skus with the same code are equal, and have the same hashCode") + void sameCodeIsEqual() { + Sku a = new Sku("KEYBOARD-01"); + Sku b = new Sku("KEYBOARD-01"); + + assertThat(a.equals(b)).as("a.equals(b)").isTrue(); + assertThat(b.equals(a)).as("b.equals(a)").isTrue(); + assertThat(a.hashCode()).as("hashCode of a and of b").isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Sku: list.contains and map.get find an equal Sku that is a different object") + void lookupsFindAnEqualSku() { + Map prices = new HashMap<>(); + prices.put(new Sku("KEYBOARD-01"), new Money("89.00", "EUR")); + + assertThat(List.of(new Sku("KEYBOARD-01")).contains(new Sku("KEYBOARD-01"))).as("list.contains").isTrue(); + assertThat(prices.get(new Sku("KEYBOARD-01"))).as("prices.get").isEqualTo(new Money("89.00", "EUR")); + } + + @Test + @DisplayName("Sku: a HashSet keeps one of two equal Skus") + void setKeepsOne() { + Set skus = new HashSet<>(); + + assertThat(skus.add(new Sku("KEYBOARD-01"))).as("first add").isTrue(); + assertThat(skus.add(new Sku("KEYBOARD-01"))).as("second add of an equal Sku").isFalse(); + assertThat(skus).hasSize(1); + } + + @Test + @DisplayName("Sku: not equal to a different code, to null, or to a String with the same text (already passing: keep it that way)") + void notEqualToOtherThings() { + Sku keyboard = new Sku("KEYBOARD-01"); + + assertThat(keyboard.equals(new Sku("MOUSE-01"))).as("different code").isFalse(); + assertThat(keyboard.equals(null)).as("null").isFalse(); + assertThat(keyboard.equals((Object) "KEYBOARD-01")).as("a String").isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ValueBasicsTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ValueBasicsTest.java new file mode 100644 index 0000000..de19b8e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/ValueBasicsTest.java @@ -0,0 +1,27 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline: the value objects hold their values. Passes from the start and must stay green. */ +@Tag("baseline") +class ValueBasicsTest { + + @Test + @DisplayName("Sku and Money hold their values: a blank SKU is rejected, 10.5 EUR is kept as 10.50, and Money adds up") + void valueObjectsHoldTheirValues() { + assertThat(new Sku("KEYBOARD-01").code()).isEqualTo("KEYBOARD-01"); + assertThatThrownBy(() -> new Sku(" ")).isInstanceOf(IllegalArgumentException.class); + + Money money = new Money("10.5", "EUR"); + assertThat(money.amount()).hasToString("10.50"); + assertThat(money.plus(new Money("0.25", "EUR")).amount()).hasToString("10.75"); + assertThatThrownBy(() -> money.plus(new Money("1", "USD"))).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/support/IntegrationTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/support/IntegrationTest.java new file mode 100644 index 0000000..7c148a4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/java/com/amigoscode/equality/support/IntegrationTest.java @@ -0,0 +1,76 @@ +package com.amigoscode.equality.support; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.order.OrderService; +import com.amigoscode.equality.product.ProductRepository; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run real Hibernate against a real Postgres started by + * Testcontainers (Docker must be running), because proxies, lazy loading and generated ids only + * behave like this with a real persistence context. One container is shared by every test class. + * + *

The tests are not @Transactional on purpose: each one says where its transactions start and + * end with {@code inTransaction(...)}, because what equals does depends on it. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @Autowired + protected OrderService orderService; + + @Autowired + protected ProductRepository products; + + @Autowired + protected EntityManager em; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private TransactionTemplate transactions; + + @BeforeEach + void freshShop() { + ShopData.reset(jdbc); + } + + /** Runs the work in one new transaction, and returns what it returns. */ + protected T inTransaction(java.util.function.Supplier work) { + return transactions.execute(status -> work.get()); + } + + protected void inTransaction(Runnable work) { + transactions.executeWithoutResult(status -> work.run()); + } + + protected int lineItemRows() { + return jdbc.queryForObject("select count(*) from line_item", Integer.class); + } + + protected long productId(String sku) { + return jdbc.queryForObject("select id from product where sku = ?", Long.class, sku); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/solution/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/.mvn/jvm.config b/java/concepts/junior-mid/15-equals-and-hashcode/start/.mvn/jvm.config new file mode 100644 index 0000000..ccc1dc4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/.mvn/jvm.config @@ -0,0 +1,3 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow +--add-opens=java.base/java.util=ALL-UNNAMED diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/15-equals-and-hashcode/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/start/check b/java/concepts/junior-mid/15-equals-and-hashcode/start/check new file mode 100755 index 0000000..296fad5 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/check.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/start/check.cmd new file mode 100644 index 0000000..7cdf2d1 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/compose.yaml b/java/concepts/junior-mid/15-equals-and-hashcode/start/compose.yaml new file mode 100644 index 0000000..48765df --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/compose.yaml @@ -0,0 +1,16 @@ +name: equals-and-hashcode +services: + postgres: + image: postgres:17-alpine + container_name: equals-and-hashcode-postgres + environment: + POSTGRES_DB: shop + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + ports: + - "5454:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U shop -d shop"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/demo b/java/concepts/junior-mid/15-equals-and-hashcode/start/demo new file mode 100755 index 0000000..438f4da --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/demo.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/start/demo.cmd new file mode 100644 index 0000000..28b3d47 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/inspect b/java/concepts/junior-mid/15-equals-and-hashcode/start/inspect new file mode 100755 index 0000000..0c4f568 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/inspect.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/start/inspect.cmd new file mode 100644 index 0000000..ed551f3 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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.equality.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/mvnw b/java/concepts/junior-mid/15-equals-and-hashcode/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/start/mvnw.cmd b/java/concepts/junior-mid/15-equals-and-hashcode/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/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/15-equals-and-hashcode/start/pom.xml b/java/concepts/junior-mid/15-equals-and-hashcode/start/pom.xml new file mode 100644 index 0000000..08a3003 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + equals-and-hashcode + 0.0.1-SNAPSHOT + equals-and-hashcode + equals and hashCode in plain Java and on JPA entities: see objects get lost in a HashSet, then fix them + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + 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/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/EqualityApplication.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/EqualityApplication.java new file mode 100644 index 0000000..94bb835 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/EqualityApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.equality; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EqualityApplication { + + public static void main(String[] args) { + SpringApplication.run(EqualityApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/Cart.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/Cart.java new file mode 100644 index 0000000..5f0eb77 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/Cart.java @@ -0,0 +1,37 @@ +package com.amigoscode.equality.cart; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** A shopping cart: a HashSet of lines. Nothing to change here. */ +public final class Cart { + + private final Set lines = new HashSet<>(); + + /** Returns false when the cart already holds an equal line. */ + public boolean add(CartLine line) { + return lines.add(line); + } + + public boolean remove(CartLine line) { + return lines.remove(line); + } + + public boolean contains(CartLine line) { + return lines.contains(line); + } + + public int size() { + return lines.size(); + } + + public Set lines() { + return Collections.unmodifiableSet(lines); + } + + /** The HashSet itself, so ./inspect can show its buckets. */ + public Set backingSet() { + return lines; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/CartLine.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/CartLine.java new file mode 100644 index 0000000..87d3e49 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/cart/CartLine.java @@ -0,0 +1,58 @@ +package com.amigoscode.equality.cart; + +import com.amigoscode.equality.value.Sku; +import java.util.Objects; + +/** + * One line of a shopping cart: a SKU and how many of it. The customer can change the quantity, so + * a CartLine changes while it sits in the cart's HashSet. + */ +public final class CartLine { + + private final Sku sku; + private int quantity; + + public CartLine(Sku sku, int quantity) { + this.sku = Objects.requireNonNull(sku, "sku"); + changeQuantity(quantity); + } + + public Sku sku() { + return sku; + } + + public int quantity() { + return quantity; + } + + public void changeQuantity(int quantity) { + if (quantity < 1) { + throw new IllegalArgumentException("Quantity must be at least 1, got " + quantity); + } + this.quantity = quantity; + } + + // TODO Task 4: generated by the IDE with every field ticked. The quantity changes while the + // line is in the cart's HashSet. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CartLine other = (CartLine) o; + return quantity == other.quantity && sku.equals(other.sku); + } + + @Override + public int hashCode() { + return Objects.hash(sku, quantity); + } + + @Override + public String toString() { + return quantity + " x " + sku; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/ShopData.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/ShopData.java new file mode 100644 index 0000000..13bf0bf --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/ShopData.java @@ -0,0 +1,48 @@ +package com.amigoscode.equality.db; + +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Puts the database back to the same three products and no orders. ./demo, ./inspect and every + * integration test call it first, so every run starts from the same state. Nothing to change here. + */ +public final class ShopData { + + public static final String KEYBOARD = "KEYBOARD-01"; + public static final String MOUSE = "MOUSE-01"; + /** Out of stock. */ + public static final String HEADSET = "HEADSET-01"; + + private ShopData() { + } + + public static void reset(JdbcTemplate jdbc) { + jdbc.execute("truncate table line_item, orders, product_tag, product, tag restart identity"); + jdbc.update("insert into tag (name) values ('wireless'), ('gaming'), ('audio')"); + jdbc.update(""" + insert into product (sku, name, price, stock) values + ('KEYBOARD-01', 'Mechanical keyboard', 89.00, 10), + ('MOUSE-01', 'Wireless mouse', 39.00, 10), + ('HEADSET-01', 'Wireless headset', 59.00, 0) + """); + jdbc.update(""" + insert into product_tag (product_id, tag_id) + select p.id, t.id + from (values ('KEYBOARD-01', 'gaming'), + ('MOUSE-01', 'wireless'), ('MOUSE-01', 'gaming'), + ('HEADSET-01', 'wireless'), ('HEADSET-01', 'audio')) as pt (sku, tag) + join product p on p.sku = pt.sku + join tag t on t.name = pt.tag + """); + } + + /** Saves an order with one line item per SKU, with plain SQL. Returns the order id. */ + public static long insertOrder(JdbcTemplate jdbc, String customer, String... skus) { + long orderId = jdbc.queryForObject("insert into orders (customer) values (?) returning id", Long.class, customer); + for (String sku : skus) { + jdbc.update("insert into line_item (order_id, product_id, quantity) select ?, id, 1 from product where sku = ?", + orderId, sku); + } + return orderId; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/SqlRecorder.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/SqlRecorder.java new file mode 100644 index 0000000..e333cde --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/db/SqlRecorder.java @@ -0,0 +1,36 @@ +package com.amigoscode.equality.db; + +import java.util.ArrayList; +import java.util.List; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** + * Writes down every SQL statement Hibernate sends while recording is on, so the demo can print it + * and the tests can count it. Registered in application.properties. Nothing to change here. + */ +public class SqlRecorder implements StatementInspector { + + private static final List STATEMENTS = new ArrayList<>(); + private static boolean recording; + + public static synchronized void start() { + STATEMENTS.clear(); + recording = true; + } + + /** Stops recording and returns what was sent since start(). */ + public static synchronized List stop() { + recording = false; + return List.copyOf(STATEMENTS); + } + + @Override + public String inspect(String sql) { + synchronized (SqlRecorder.class) { + if (recording) { + STATEMENTS.add(sql); + } + } + return sql; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Buckets.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Buckets.java new file mode 100644 index 0000000..89a52bf --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Buckets.java @@ -0,0 +1,145 @@ +package com.amigoscode.equality.demo; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Reads the bucket table inside a HashSet or HashMap, so ./inspect can show where each element + * really sits. A HashSet is a HashMap whose keys are the elements. Each bucket is a chain of nodes, + * and every node remembers the hash its key had WHEN IT WAS INSERTED. Nothing to change here. + * + *

The fields are private to java.util. The launchers open them with + * --add-opens=java.base/java.util=ALL-UNNAMED (see .mvn/jvm.config). + */ +final class Buckets { + + /** One element in the table: the bucket it sits in and the hashCode it had when it was added. */ + record Entry(int bucket, Object key, int hashAtInsert) { + } + + private Buckets() { + } + + /** What HashMap does with a hashCode before it picks a bucket: it mixes the high bits into the low ones. */ + static int spread(int hashCode) { + return hashCode ^ (hashCode >>> 16); + } + + static int bucketOf(int hashCode, int tableSize) { + return spread(hashCode) & (tableSize - 1); + } + + static int tableSize(Object setOrMap) { + Object[] table = table(setOrMap); + return table == null ? 0 : table.length; + } + + /** Every element, in table order. */ + static List entries(Object setOrMap) { + List entries = new ArrayList<>(); + Object[] table = table(setOrMap); + if (table == null) { + return entries; + } + for (int bucket = 0; bucket < table.length; bucket++) { + for (Object node = table[bucket]; node != null; node = read(node, "next")) { + int stored = (int) read(node, "hash"); + // The node stores spread(hashCode). The top 16 bits are unchanged, so spread is its own inverse. + entries.add(new Entry(bucket, read(node, "key"), spread(stored))); + } + } + return entries; + } + + /** + * What contains(probe) does, step by step: pick the bucket from probe.hashCode(), then for each + * node in that bucket compare the stored hash first, and call equals only when the hashes match. + */ + static List lookup(Object setOrMap, Object probe) { + List steps = new ArrayList<>(); + int hashCode = probe.hashCode(); + int size = tableSize(setOrMap); + int bucket = bucketOf(hashCode, size); + steps.add("hashCode() is " + hashCode + ", so look in bucket " + bucket); + boolean any = false; + for (Entry entry : entries(setOrMap)) { + if (entry.bucket() != bucket) { + continue; + } + any = true; + if (entry.hashAtInsert() != hashCode) { + steps.add("bucket " + bucket + " holds " + entry.key() + " with hash " + entry.hashAtInsert() + + ": different hash, equals is not called"); + } else { + boolean same = entry.key() == probe; + boolean equal = same || probe.equals(entry.key()); + steps.add("bucket " + bucket + " holds " + entry.key() + " with the same hash: " + + (same ? "the same object, found" : "equals() says " + equal)); + } + } + if (!any) { + steps.add("bucket " + bucket + " is empty: equals is never called"); + } + return steps; + } + + private static Object[] table(Object setOrMap) { + Object map = setOrMap; + if (setOrMap instanceof HashSet) { + map = read(setOrMap, HashSet.class, "map"); + } else if (!(setOrMap instanceof HashMap)) { + throw new IllegalArgumentException("Not a HashSet or HashMap: " + setOrMap.getClass().getName()); + } + return (Object[]) read(map, HashMap.class, "table"); + } + + /** The HashSet inside a Hibernate PersistentSet, or the set itself. */ + static Set unwrap(Set set) { + Class type = set.getClass(); + while (type != null && !type.getName().equals("org.hibernate.collection.spi.PersistentSet")) { + type = type.getSuperclass(); + } + return type == null ? set : (Set) read(set, type, "set"); + } + + static boolean isHibernateSet(Set set) { + return unwrap(set) != set; + } + + static Map asMap(Object map) { + return (Map) map; + } + + private static Object read(Object target, String name) { + Class type = target.getClass(); + while (type != null) { + try { + return read(target, type, name); + } catch (IllegalStateException e) { + type = type.getSuperclass(); + } + } + throw new IllegalStateException("No field " + name + " in " + target.getClass().getName()); + } + + private static Object read(Object target, Class type, String name) { + try { + Field field = type.getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } catch (NoSuchFieldException e) { + throw new IllegalStateException("No field " + name + " in " + type.getName(), e); + } catch (IllegalAccessException | RuntimeException e) { + if (e instanceof IllegalStateException ise) { + throw ise; + } + throw new IllegalStateException("Cannot read the bucket table (" + Tool.describe(e) + "). Run this with ./inspect," + + " which opens java.util for reading (see .mvn/jvm.config).", e); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Db.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Db.java new file mode 100644 index 0000000..432174c --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Db.java @@ -0,0 +1,42 @@ +package com.amigoscode.equality.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:5454/shop"); + static final String USER = env("DB_USER", "shop"); + static final String PASSWORD = env("DB_PASSWORD", "shop"); + + private Db() { + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp(Scenario scenario, boolean blankLineFirst) { + try (Connection ignored = DriverManager.getConnection(URL, USER, PASSWORD)) { + return true; + } catch (SQLException e) { + if (blankLineFirst) { + System.out.println(); + } + System.out.println("The scenario " + scenario.flag() + " uses JPA entities and needs Postgres, and Postgres is not"); + System.out.println("reachable at " + URL + ". Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("The plain-Java scenarios run without a database: " + Scenario.names(false) + "."); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + System.out.println(); + 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/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Demo.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Demo.java new file mode 100644 index 0000000..6eef1d9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Demo.java @@ -0,0 +1,380 @@ +package com.amigoscode.equality.demo; + +import static com.amigoscode.equality.demo.Tool.attempt; +import static com.amigoscode.equality.demo.Tool.line; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.order.OrderService; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.hibernate.Hibernate; + +/** + * Runs one scenario and prints the evidence: every call, what it returned, and a RESULT line. The + * plain-Java scenarios need nothing but Java. The database scenarios start the real application + * against the Postgres from compose.yaml. Run it with ./demo (or .\demo on Windows). + */ +public final class Demo { + + public static void main(String[] args) { + Scenario scenario; + try { + scenario = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (scenario == null) { + printHelp(); + return; + } + + System.out.println(); + System.out.println("Scenario: " + scenario.flag() + " | " + scenario.summary()); + System.out.println(); + if (!scenario.needsDatabase()) { + switch (scenario) { + case NO_EQUALS -> noEquals(); + case EQUALS_ONLY -> equalsOnly(); + case MUTABLE -> mutable(); + case RECORD -> record(); + default -> throw new IllegalStateException(scenario.flag()); + } + System.out.println(); + return; + } + if (!Db.isUp(scenario, false)) { + return; + } + try (Shop shop = Shop.start()) { + switch (scenario) { + case NEW_ITEMS -> newItems(shop); + case REMOVE_ITEM -> removeItem(shop); + case LAZY -> lazy(shop); + case PROXY -> proxy(shop); + default -> throw new IllegalStateException(scenario.flag()); + } + } + System.out.println(); + } + + // ---- Plain Java ---- + + private static void noEquals() { + Sku a = new Sku("KEYBOARD-01"); + Sku b = new Sku("KEYBOARD-01"); + Map prices = new HashMap<>(); + prices.put(a, new Money("89.00", "EUR")); + Set set = new HashSet<>(); + set.add(a); + set.add(b); + + System.out.println("Two Skus made from the same text, the way two requests or two rows would make them."); + System.out.println(); + System.out.println(" Sku a = new Sku(\"KEYBOARD-01\")"); + System.out.println(" Sku b = new Sku(\"KEYBOARD-01\")"); + System.out.println(" prices.put(a, 89.00 EUR)"); + System.out.println(); + line("a.equals(b)", a.equals(b)); + line("a.hashCode()", a.hashCode()); + line("b.hashCode()", b.hashCode()); + line("List.of(a).contains(b)", List.of(a).contains(b)); + line("prices.get(b)", prices.get(b)); + line("set.add(a); set.add(b); size", set.size(), set.toString()); + System.out.println(); + + if (prices.get(b) == null || set.size() > 1) { + System.out.println("RESULT: NOT EQUAL. Two Skus with the same code are two different keys: the price of KEYBOARD-01 was not found."); + } else { + System.out.println("RESULT: OK. Two Skus with the same code are one key: the price was found and the set holds one."); + } + } + + private static void equalsOnly() { + Money a = new Money("89.00", "EUR"); + Money b = new Money("89.00", "EUR"); + Set set = new HashSet<>(); + set.add(a); + set.add(b); + Map labels = new HashMap<>(); + labels.put(a, "keyboard price"); + + System.out.println(" Money a = new Money(\"89.00\", \"EUR\")"); + System.out.println(" Money b = new Money(\"89.00\", \"EUR\")"); + System.out.println(" labels.put(a, \"keyboard price\")"); + System.out.println(); + line("a.equals(b)", a.equals(b)); + line("a.hashCode()", a.hashCode()); + line("b.hashCode()", b.hashCode()); + line("List.of(a).contains(b)", List.of(a).contains(b), "a List only calls equals"); + line("set.add(a); set.add(b); size", set.size(), set.toString()); + line("labels.get(b)", labels.get(b)); + System.out.println(); + + if (a.equals(b) && set.size() > 1) { + System.out.println("RESULT: DUPLICATE ITEM. a.equals(b) is true, and the HashSet holds both: equal objects need equal hash codes."); + } else if (labels.get(b) == null) { + System.out.println("RESULT: NOT FOUND. a.equals(b) is true, and HashMap.get(b) did not find the value put with a."); + } else { + System.out.println("RESULT: OK. Equal amounts have equal hash codes: the set holds one and the label was found."); + } + } + + private static void mutable() { + Cart cart = new Cart(); + CartLine line = new CartLine(new Sku("KEYBOARD-01"), 1); + int before = line.hashCode(); + + System.out.println(" CartLine line = new CartLine(KEYBOARD-01, 1)"); + System.out.println(); + line("cart.add(line)", cart.add(line), "hashCode " + before); + line.changeQuantity(3); + int after = line.hashCode(); + line("line.changeQuantity(3)", "", "hashCode " + after + (after == before ? " (unchanged)" : " (was " + before + ")")); + boolean contains = cart.contains(line); + line("cart.contains(line)", contains); + boolean removed = cart.remove(line); + line("cart.remove(line)", removed, "the customer clicked \"remove\""); + line("cart.size()", cart.size(), cart.lines().toString()); + boolean addedAgain = cart.add(line); + line("cart.add(line) again", addedAgain, "size " + cart.size() + (cart.size() > 1 ? ": the same object is in the set twice" : "")); + System.out.println(); + + if (!contains || !removed) { + System.out.println("RESULT: LOST IN SET. The line is still in the cart, and contains and remove cannot find it." + + " ./inspect --scenario mutable shows why."); + } else { + System.out.println("RESULT: OK. The line was found after the change and removed."); + } + } + + private static void record() { + Sku keyboard = new Sku("KEYBOARD-01"); + Sku mouse = new Sku("MOUSE-01"); + List skus = new ArrayList<>(List.of(keyboard, mouse)); + Bundle desk = new Bundle("Desk set", skus); + Map prices = new HashMap<>(); + prices.put(desk, new Money("119.00", "EUR")); + int before = desk.hashCode(); + + System.out.println(" List skus = new ArrayList<>(List.of(KEYBOARD-01, MOUSE-01))"); + System.out.println(" Bundle desk = new Bundle(\"Desk set\", skus)"); + System.out.println(" prices.put(desk, 119.00 EUR)"); + System.out.println(); + line("desk.hashCode()", before); + Object added = attempt(() -> skus.add(new Sku("HEADSET-01"))); + line("skus.add(HEADSET-01)", added, "the caller reuses its list for the next bundle"); + line("desk.skus()", desk.skus()); + int after = desk.hashCode(); + line("desk.hashCode()", after, after == before ? "(unchanged)" : "(was " + before + ")"); + line("prices.get(desk)", prices.get(desk)); + line("prices.size()", prices.size(), prices.keySet().stream().map(Bundle::name).toList().toString()); + System.out.println(); + + if (prices.get(desk) == null) { + System.out.println("RESULT: LOST IN MAP. The price of the desk set is in the Map, and the desk set cannot find it."); + } else { + System.out.println("RESULT: OK. Changing the caller's list did not change the bundle: its price was found."); + } + } + + // ---- JPA ---- + + private static void newItems(Shop shop) { + System.out.println("First, in memory: two new line items, before anything is saved."); + System.out.println(); + Order draft = new Order("ana"); + LineItem a = draft.add(new Product(ShopData.KEYBOARD, "Mechanical keyboard", new BigDecimal("89.00"), 10), 1); + LineItem b = draft.add(new Product(ShopData.MOUSE, "Wireless mouse", new BigDecimal("39.00"), 10), 2); + line("a.getId(), b.getId()", a.getId() + ", " + b.getId()); + line("a.equals(b)", a.equals(b)); + line("order.getItems().size()", draft.getItems().size(), "after order.add(keyboard), order.add(mouse)"); + System.out.println(); + + System.out.println("Now the real thing, saved to Postgres:"); + System.out.println(); + System.out.println(" orderService.placeOrder(\"ana\", [1 x KEYBOARD-01, 2 x MOUSE-01])"); + System.out.println(); + SqlRecorder.start(); + shop.bean(OrderService.class).placeOrder("ana", + List.of(new OrderLine(ShopData.KEYBOARD, 1), new OrderLine(ShopData.MOUSE, 2))); + List sql = SqlRecorder.stop(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + System.out.println("ROWS IN line_item"); + shop.printLineItemRows(); + System.out.println(); + + int rows = shop.lineItemRows(); + if (rows < 2) { + System.out.println("RESULT: MISSING ITEM. 2 lines were ordered and " + rows + " was saved. The second new item" + + " was equal to the first (both ids null), so the Set never took it."); + } else { + System.out.println("RESULT: OK. 2 lines were ordered and 2 were saved."); + } + } + + private static void removeItem(Shop shop) { + System.out.println(" orderService.placeOrder(\"ana\", [1 x HEADSET-01])"); + System.out.println(); + System.out.println("HEADSET-01 has stock 0. placeOrder saves the order first (that gives every item its id),"); + System.out.println("then removes the lines that cannot be delivered: order.remove(item)."); + System.out.println(); + SqlRecorder.start(); + Order order = shop.bean(OrderService.class).placeOrder("ana", List.of(new OrderLine(ShopData.HEADSET, 1))); + List sql = SqlRecorder.stop(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + line("order.getItems()", order.getItems()); + System.out.println(); + System.out.println("ROWS IN line_item"); + shop.printLineItemRows(); + System.out.println(); + + if (shop.lineItemRows() > 0) { + System.out.println("RESULT: LOST IN SET. The out-of-stock headset was removed from the order, the Set did not find it," + + " and its row is still in line_item. ./inspect --scenario remove-item shows why."); + } else { + System.out.println("RESULT: OK. The out-of-stock line was removed from the Set, and orphanRemoval deleted its row."); + } + } + + private static void lazy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + + System.out.println("1. Inside a transaction: List all = products.findAll(); new HashSet<>(all)"); + System.out.println(); + List sql = shop.inTransaction(() -> { + List all = products.findAll(); + SqlRecorder.start(); + new HashSet<>(all); + return SqlRecorder.stop(); + }); + System.out.println("SQL SENT WHILE ADDING 3 PRODUCTS TO A HashSet"); + Tool.sql(sql); + System.out.println(); + + System.out.println("2. The same, with products from a transaction that has already ended (a cache, a DTO mapper,"); + System.out.println(" a test, anything that runs after the @Transactional method returned):"); + System.out.println(); + List loadedEarlier = shop.inTransaction(() -> products.findAll()); + String exception = null; + try { + new HashSet<>(loadedEarlier); + line("new HashSet<>(all)", "ok"); + } catch (RuntimeException e) { + exception = Tool.describe(e); + System.out.println(" new HashSet<>(all) threw"); + System.out.println(" " + exception); + } + System.out.println(); + + if (!sql.isEmpty()) { + System.out.println("RESULT: EXTRA QUERIES. Putting 3 products in a HashSet sent " + sql.size() + + " SELECTs: hashCode loaded each product's tags."); + } + if (exception != null) { + System.out.println("RESULT: LAZY INITIALIZATION EXCEPTION. A product loaded earlier cannot even be put in a HashSet."); + } + if (sql.isEmpty() && exception == null) { + System.out.println("RESULT: OK. No SQL and no exception: hashCode does not touch the tags."); + } + } + + private static void proxy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + long orderId = ShopData.insertOrder(shop.jdbc, "ana", ShopData.KEYBOARD, ShopData.MOUSE); + + System.out.printf(" %-60s %s%n", "Product keyboard = products.findBySkuWithTags(\"KEYBOARD-01\")", "transaction 1: the catalogue"); + System.out.printf(" %-60s %s%n", "Order order = em.find(Order.class, " + orderId + ")", "transaction 2: an order"); + System.out.printf(" %-60s %s%n", "Product proxy = .getProduct()", "the same row, lazy"); + System.out.println(); + Product keyboard = shop.inTransaction(() -> products.findBySkuWithTags(ShopData.KEYBOARD).orElseThrow()); + boolean[] outcome = new boolean[2]; + shop.inTransaction(() -> { + Order order = shop.em.find(Order.class, orderId); + Product proxy = order.getItems().stream() + .map(LineItem::getProduct) + .filter(product -> product.getId().equals(keyboard.getId())) + .findFirst().orElseThrow(); + line("keyboard.getClass()", keyboard.getClass().getSimpleName()); + line("proxy.getClass()", proxy.getClass().getSimpleName()); + line("Hibernate.isInitialized(proxy)", Hibernate.isInitialized(proxy), "the row is not loaded yet"); + line("proxy.getId()", proxy.getId(), "known without loading the row"); + Object keyboardEqualsProxy = attempt(() -> keyboard.equals(proxy)); + line("keyboard.equals(proxy)", keyboardEqualsProxy); + Object proxyEqualsKeyboard = attempt(() -> proxy.equals(keyboard)); + line("proxy.equals(keyboard)", proxyEqualsKeyboard); + Object contains = attempt(() -> { + Set inOrder = order.getItems().stream().map(LineItem::getProduct).collect(Collectors.toSet()); + return inOrder.contains(keyboard); + }); + line("productsInOrder.contains(keyboard)", contains); + outcome[0] = Boolean.TRUE.equals(keyboardEqualsProxy) && Boolean.TRUE.equals(proxyEqualsKeyboard); + outcome[1] = Boolean.TRUE.equals(contains); + }); + System.out.println(); + + if (!outcome[0] || !outcome[1]) { + System.out.println("RESULT: NOT EQUAL. KEYBOARD-01 and KEYBOARD-01, one row, and equals says they are different products."); + } else { + System.out.println("RESULT: OK. The catalogue's keyboard and the order's proxy are equal, both ways, and found in the Set."); + } + } + + // ---- Options ---- + + private static Scenario parse(String[] args) { + Scenario scenario = Scenario.NO_EQUALS; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + if (i + 1 >= args.length) { + throw new IllegalArgumentException("--scenario needs a value"); + } + scenario = Scenario.from(args[++i], true); + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + return scenario; + } + + private static void printHelp() { + System.out.println("Usage: ./demo [--scenario ] (Windows: .\\demo [--scenario ])"); + System.out.println(); + System.out.println("Scenarios (DB = needs the database: docker compose up -d):"); + Scenario.printList(true); + System.out.println(); + System.out.println("Default: no-equals. Examples:"); + System.out.println(" ./demo --scenario mutable"); + System.out.println(" ./demo --scenario new-items"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Inspect.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Inspect.java new file mode 100644 index 0000000..a3b4afa --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Inspect.java @@ -0,0 +1,384 @@ +package com.amigoscode.equality.demo; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.hibernate.Hibernate; + +/** + * Shows what is inside: the buckets of a HashSet or HashMap (which bucket each element sits in, the + * hash it had when it was added and the hash it has now), and for the database scenarios the rows + * next to the objects in the Set and in the persistence context. Run it with ./inspect (or + * .\inspect on Windows). ./inspect --help lists the scenarios. + */ +public final class Inspect { + + public static void main(String[] args) { + Scenario scenario; + try { + scenario = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (scenario == null) { + printHelp(); + return; + } + + System.out.println(); + System.out.println("Inspect: " + scenario.flag() + " | " + scenario.summary()); + if (!scenario.needsDatabase()) { + switch (scenario) { + case NO_EQUALS -> twoEqualLooking(new Sku("KEYBOARD-01"), new Sku("KEYBOARD-01"), new Sku("KEYBOARD-01"), + "Sku a = new Sku(\"KEYBOARD-01\"), Sku b = new Sku(\"KEYBOARD-01\")"); + case EQUALS_ONLY -> twoEqualLooking(new Money("89.00", "EUR"), new Money("89.00", "EUR"), new Money("89.00", "EUR"), + "Money a = new Money(\"89.00\", \"EUR\"), Money b = new Money(\"89.00\", \"EUR\")"); + case COLLISION -> collision(); + case MUTABLE -> mutable(); + case RECORD -> record(); + default -> throw new IllegalStateException(scenario.flag()); + } + System.out.println(); + return; + } + if (!Db.isUp(scenario, true)) { + return; + } + try (Shop shop = Shop.start()) { + switch (scenario) { + case NEW_ITEMS -> newItems(shop); + case REMOVE_ITEM -> removeItem(shop); + case LAZY -> lazy(shop); + case PROXY -> proxy(shop); + default -> throw new IllegalStateException(scenario.flag()); + } + } + System.out.println(); + } + + // ---- Plain Java ---- + + private static void twoEqualLooking(Object a, Object b, Object probe, String made) { + Set set = new HashSet<>(); + set.add(a); + set.add(b); + System.out.println(); + System.out.println(" " + made); + System.out.println(" a.equals(b) is " + a.equals(b)); + System.out.println(); + printBuckets("after set.add(a); set.add(b)", set, named(a, "a", b, "b")); + System.out.println(); + printLookup("set.contains(c), where c is one more object made from the same values", set, probe); + } + + private static void collision() { + Set set = new HashSet<>(); + set.add("Aa"); + set.add("BB"); + set.add("KEYBOARD-01"); + System.out.println(); + System.out.println(" \"Aa\".hashCode() is " + "Aa".hashCode() + " and \"BB\".hashCode() is " + "BB".hashCode() + + ". \"Aa\".equals(\"BB\") is false."); + System.out.println(); + printBuckets("after set.add(\"Aa\"); set.add(\"BB\"); set.add(\"KEYBOARD-01\")", set, named()); + System.out.println(); + printLookup("set.contains(\"BB\")", set, "BB"); + } + + private static void mutable() { + Cart cart = new Cart(); + CartLine keyboard = new CartLine(new Sku("KEYBOARD-01"), 1); + CartLine mouse = new CartLine(new Sku("MOUSE-01"), 2); + cart.add(keyboard); + cart.add(mouse); + System.out.println(); + printBuckets("after cart.add(1 x KEYBOARD-01); cart.add(2 x MOUSE-01)", cart.backingSet(), named()); + System.out.println(); + keyboard.changeQuantity(3); + printBuckets("after keyboard.changeQuantity(3). Nothing in the table moves by itself", cart.backingSet(), named()); + System.out.println(); + printLookup("cart.contains(keyboard), the very same object", cart.backingSet(), keyboard); + } + + private static void record() { + List skus = new ArrayList<>(List.of(new Sku("KEYBOARD-01"), new Sku("MOUSE-01"))); + Bundle desk = new Bundle("Desk set", skus); + Map prices = new HashMap<>(); + prices.put(desk, new Money("119.00", "EUR")); + System.out.println(); + printBuckets("after prices.put(desk, 119.00 EUR)", prices, named()); + System.out.println(); + skus.add(new Sku("HEADSET-01")); + printBuckets("after skus.add(HEADSET-01), on the caller's list", prices, named()); + System.out.println(); + printLookup("prices.get(desk), the very same object", prices, desk); + } + + // ---- JPA ---- + + private static void newItems(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Product mouse = products.findBySku(ShopData.MOUSE).orElseThrow(); + Order order = new Order("ana"); + LineItem first = order.add(keyboard, 1); + LineItem second = order.add(mouse, 2); + Map names = named(first, "first (keyboard)", second, "second (mouse)"); + + System.out.println(); + System.out.println("Step 1. LineItem first = order.add(keyboard, 1); LineItem second = order.add(mouse, 2)"); + System.out.println(" first.equals(second) is " + first.equals(second) + " (ids: " + first.getId() + ", " + second.getId() + ")"); + System.out.println(); + printBuckets("of order.items, before the save", order.backingSet(), names); + System.out.println(); + + shop.em.persist(order); + shop.em.flush(); + System.out.println("Step 2. em.persist(order); em.flush()"); + System.out.println(); + printItems(order, List.of(first, second), names); + System.out.println(); + System.out.println("ROWS IN line_item (this transaction's view)"); + shop.printLineItemRows(); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT (one Java object per row, for this transaction)"); + shop.printPersistenceContext(); + }); + } + + private static void removeItem(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + Product headset = products.findBySku(ShopData.HEADSET).orElseThrow(); + Order order = new Order("ana"); + LineItem item = order.add(headset, 1); + Map names = named(item, "item (headset)"); + + System.out.println(); + System.out.println("Step 1. LineItem item = order.add(headset, 1) item.getId() is " + item.getId()); + System.out.println(); + printBuckets("of order.items, before the save", order.backingSet(), names); + System.out.println(); + + shop.em.persist(order); + shop.em.flush(); + System.out.println("Step 2. em.persist(order); em.flush() item.getId() is " + item.getId()); + System.out.println(); + printItems(order, List.of(item), names); + System.out.println(); + printLookup("order.remove(item) first looks for it", order.backingSet(), item); + System.out.println(); + + boolean removed = order.remove(item); + SqlRecorder.start(); + shop.em.flush(); + List sql = SqlRecorder.stop(); + System.out.println("Step 3. order.remove(item) returned " + removed + "; em.flush()"); + System.out.println(); + System.out.println("SQL SENT BY THE FLUSH"); + Tool.sql(sql); + System.out.println(); + System.out.println("ROWS IN line_item (this transaction's view)"); + shop.printLineItemRows(); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT (one Java object per row, for this transaction)"); + shop.printPersistenceContext(); + }); + } + + private static void lazy(Shop shop) { + ProductRepository products = shop.bean(ProductRepository.class); + shop.inTransaction(() -> { + List all = products.findAll(); + System.out.println(); + System.out.println("Step 1. List all = products.findAll()"); + System.out.println(); + printProducts(all); + System.out.println(); + + SqlRecorder.start(); + Set set = new HashSet<>(all); + List sql = SqlRecorder.stop(); + System.out.println("Step 2. new HashSet<>(all)"); + System.out.println(); + System.out.println("SQL SENT"); + Tool.sql(sql); + System.out.println(); + printProducts(all); + System.out.println(); + printBuckets("of the HashSet", set, named()); + }); + } + + private static void proxy(Shop shop) { + long orderId = ShopData.insertOrder(shop.jdbc, "ana", ShopData.KEYBOARD); + shop.inTransaction(() -> { + Order order = shop.em.find(Order.class, orderId); + LineItem item = order.getItems().iterator().next(); + System.out.println(); + System.out.println("Step 1. Order order = em.find(Order.class, " + orderId + "); LineItem item = "); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT"); + shop.printPersistenceContext(); + System.out.println(); + + Product proxy = item.getProduct(); + System.out.println("Step 2. Product proxy = item.getProduct(). Each line shows the SQL it sent, if any."); + System.out.println(); + traced("proxy.getClass()", () -> proxy.getClass().getSimpleName()); + traced("proxy.getClass().getSuperclass()", () -> proxy.getClass().getSuperclass().getSimpleName()); + traced("Hibernate.isInitialized(proxy)", () -> Hibernate.isInitialized(proxy)); + traced("proxy.getId()", proxy::getId); + traced("the field proxy.sku, read directly", () -> field(proxy, "sku")); + traced("Hibernate.getClass(proxy)", () -> Hibernate.getClass(proxy).getSimpleName()); + traced("Hibernate.isInitialized(proxy)", () -> Hibernate.isInitialized(proxy)); + traced("the field proxy.sku, read directly", () -> field(proxy, "sku")); + traced("proxy.getSku()", proxy::getSku); + traced("Hibernate.unproxy(proxy)", () -> Tool.identity(Hibernate.unproxy(proxy))); + System.out.println(); + System.out.println("PERSISTENCE CONTEXT"); + shop.printPersistenceContext(); + }); + } + + // ---- Printing ---- + + /** + * Labels for objects, looked up by identity. A normal Map would call the very equals and + * hashCode this tool is inspecting, and Map.of refuses two keys that are equal. + */ + private static Map named(Object... objectsAndLabels) { + Map names = new IdentityHashMap<>(); + for (int i = 0; i < objectsAndLabels.length; i += 2) { + names.put(objectsAndLabels[i], (String) objectsAndLabels[i + 1]); + } + return names; + } + + /** Prints the table of a HashSet or HashMap: bucket, element, the hash it was added with, its hash now. */ + private static void printBuckets(String title, Object setOrMap, Map names) { + Object table = setOrMap instanceof Set set ? Buckets.unwrap(set) : setOrMap; + int size = Buckets.tableSize(table); + List entries = Buckets.entries(table); + System.out.println("BUCKETS " + title); + System.out.println(" " + entries.size() + (entries.size() == 1 ? " element" : " elements") + " in a table of " + + size + " buckets (empty buckets not shown)" + + (setOrMap instanceof Set set && Buckets.isHibernateSet(set) ? "; the HashSet inside Hibernate's PersistentSet" : "")); + List rows = Tool.rows("bucket", "element", "Java object", "hash when added", "hashCode() now", "a lookup goes to"); + for (Buckets.Entry entry : entries) { + Object key = entry.key(); + int now = key.hashCode(); + int bucketNow = Buckets.bucketOf(now, size); + String label = names.getOrDefault(key, String.valueOf(key)); + rows.add(new String[] {String.valueOf(entry.bucket()), label, Tool.identity(key), + String.valueOf(entry.hashAtInsert()), String.valueOf(now), + now == entry.hashAtInsert() ? String.valueOf(bucketNow) + : bucketNow + (bucketNow == entry.bucket() ? " <- HASH CHANGED" : " <- WRONG BUCKET")}); + } + Tool.table(rows); + } + + private static void printLookup(String title, Object setOrMap, Object probe) { + Object table = setOrMap instanceof Set set ? Buckets.unwrap(set) : setOrMap; + System.out.println("LOOKUP " + title); + for (String step : Buckets.lookup(table, probe)) { + System.out.println(" " + step); + } + boolean found = setOrMap instanceof Set set ? set.contains(probe) : ((Map) setOrMap).containsKey(probe); + System.out.println(" " + (setOrMap instanceof Set ? "contains" : "containsKey") + " returns " + found); + } + + private static void printItems(Order order, List items, Map names) { + System.out.println("THE ITEMS YOU ADDED, AND WHAT order.items SAYS ABOUT THEM"); + List rows = Tool.rows("item", "id", "in the Set's table?", "order.getItems().contains(item)"); + Set inTable = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + Buckets.entries(Buckets.unwrap(order.backingSet())).forEach(entry -> inTable.add(entry.key())); + for (LineItem item : items) { + rows.add(new String[] {names.get(item), String.valueOf(item.getId()), inTable.contains(item) ? "yes" : "no", + String.valueOf(order.getItems().contains(item))}); + } + Tool.table(rows); + System.out.println(); + printBuckets("of order.items, after the save", order.backingSet(), names); + } + + private static void printProducts(List products) { + List rows = Tool.rows("product", "Java object", "tags loaded?"); + for (Product product : products) { + rows.add(new String[] {product.getSku(), Tool.identity(product), Hibernate.isInitialized(product.getTags()) ? "yes" : "no"}); + } + Tool.table(rows); + } + + private static void traced(String call, java.util.function.Supplier work) { + SqlRecorder.start(); + Object result = Tool.attempt(work); + List sql = SqlRecorder.stop(); + Tool.line(call, result, sql.isEmpty() ? "no SQL" : "SQL: " + String.join("; ", sql)); + } + + private static Object field(Object target, String name) { + try { + Field field = Product.class.getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + // ---- Options ---- + + private static Scenario parse(String[] args) { + Scenario scenario = Scenario.EQUALS_ONLY; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + if (i + 1 >= args.length) { + throw new IllegalArgumentException("--scenario needs a value"); + } + scenario = Scenario.from(args[++i], false); + } + default -> throw new IllegalArgumentException("Unknown option: " + args[i]); + } + } + return scenario; + } + + private static void printHelp() { + System.out.println("Usage: ./inspect [--scenario ] (Windows: .\\inspect [--scenario ])"); + System.out.println(); + System.out.println("Scenarios (DB = needs the database: docker compose up -d):"); + Scenario.printList(false); + System.out.println(); + System.out.println("Default: equals-only. Examples:"); + System.out.println(" ./inspect --scenario mutable"); + System.out.println(" ./inspect --scenario remove-item"); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Scenario.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Scenario.java new file mode 100644 index 0000000..f929863 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Scenario.java @@ -0,0 +1,79 @@ +package com.amigoscode.equality.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** What ./demo and ./inspect can show. The first four are plain Java, the rest use the database. */ +enum Scenario { + + NO_EQUALS("no-equals", "1, 2", false, true, "Sku has no equals and no hashCode of its own"), + EQUALS_ONLY("equals-only", "1, 2, 3", false, true, "Money has equals, but no hashCode of its own"), + COLLISION("collision", "3", false, false, "two different Strings with the same hashCode (./inspect only)"), + MUTABLE("mutable", "1, 4", false, true, "a CartLine changes while it sits in a HashSet"), + RECORD("record", "4", false, true, "a record that keeps the caller's list, used as a Map key"), + NEW_ITEMS("new-items", "5, 6", true, true, "two new line items added to one order, then saved"), + REMOVE_ITEM("remove-item", "5, 6", true, true, "a line item removed after the save gave it an id"), + LAZY("lazy", "7", true, true, "products put in a HashSet: hashCode reads the lazy tags"), + PROXY("proxy", "7", true, true, "a product compared with a Hibernate proxy of the same row"); + + private final String flag; + private final String tasks; + private final boolean database; + private final boolean inDemo; + private final String summary; + + Scenario(String flag, String tasks, boolean database, boolean inDemo, String summary) { + this.flag = flag; + this.tasks = tasks; + this.database = database; + this.inDemo = inDemo; + this.summary = summary; + } + + String flag() { + return flag; + } + + String tasks() { + return tasks; + } + + boolean needsDatabase() { + return database; + } + + boolean inDemo() { + return inDemo; + } + + String summary() { + return summary; + } + + static Scenario from(String value, boolean demo) { + String wanted = value.toLowerCase(Locale.ROOT); + return Arrays.stream(values()) + .filter(scenario -> scenario.flag.equals(wanted) && (scenario.inDemo || !demo)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown scenario: " + value)); + } + + /** The plain-Java (false) or the database (true) scenarios, as "a, b, c". */ + static String names(boolean database) { + return Arrays.stream(values()) + .filter(scenario -> scenario.database == database && scenario.inDemo) + .map(Scenario::flag) + .collect(Collectors.joining(", ")); + } + + static void printList(boolean demo) { + for (Scenario scenario : values()) { + if (demo && !scenario.inDemo) { + continue; + } + System.out.printf(" %-12s %-3s Task %-8s %s%n", scenario.flag, + scenario.database ? "DB" : "", scenario.tasks, scenario.summary); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Shop.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Shop.java new file mode 100644 index 0000000..ec64fac --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Shop.java @@ -0,0 +1,97 @@ +package com.amigoscode.equality.demo; + +import com.amigoscode.equality.EqualityApplication; +import com.amigoscode.equality.db.ShopData; +import jakarta.persistence.EntityManager; +import java.util.List; +import java.util.function.Supplier; +import org.hibernate.engine.spi.EntityHolder; +import org.hibernate.engine.spi.EntityKey; +import org.hibernate.engine.spi.SessionImplementor; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * What the database scenarios of ./demo and ./inspect share: the real application (Spring, Hibernate, + * Postgres), a fresh set of products, transactions, and a look into the persistence context. + */ +final class Shop implements AutoCloseable { + + private final ConfigurableApplicationContext context; + final JdbcTemplate jdbc; + final EntityManager em; + private final TransactionTemplate transactions; + + private Shop(ConfigurableApplicationContext context) { + this.context = context; + this.jdbc = context.getBean(JdbcTemplate.class); + this.em = context.getBean(EntityManager.class); + this.transactions = context.getBean(TransactionTemplate.class); + } + + static Shop start() { + SpringApplication app = new SpringApplication(EqualityApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + Shop shop = new Shop(app.run("--logging.level.root=WARN")); + ShopData.reset(shop.jdbc); + return shop; + } + + T bean(Class type) { + return context.getBean(type); + } + + T inTransaction(Supplier work) { + return transactions.execute(status -> work.get()); + } + + void inTransaction(Runnable work) { + transactions.executeWithoutResult(status -> work.run()); + } + + /** The rows of line_item, as the database has them right now (inside a transaction: as this transaction sees them). */ + void printLineItemRows() { + List rows = Tool.rows("id", "order_id", "sku", "quantity"); + jdbc.query(""" + select li.id, li.order_id, p.sku, li.quantity + from line_item li join product p on p.id = li.product_id + order by li.id + """, row -> { + rows.add(new String[] {row.getString(1), row.getString(2), row.getString(3), row.getString(4)}); + }); + Tool.table(rows); + } + + int lineItemRows() { + return jdbc.queryForObject("select count(*) from line_item", Integer.class); + } + + /** Every entity the current transaction's persistence context holds, and whether it is loaded. */ + void printPersistenceContext() { + SessionImplementor session = em.unwrap(SessionImplementor.class); + List rows = Tool.rows("entity", "Java object", "state"); + for (var holder : session.getPersistenceContextInternal().getEntityHoldersByKey().entrySet()) { + EntityKey key = holder.getKey(); + EntityHolder value = holder.getValue(); + Object object = value.getProxy() != null ? value.getProxy() : value.getEntity(); + String state = value.getProxy() == null ? "loaded" + : value.getEntity() == null ? "proxy, row not loaded" : "proxy, row loaded"; + rows.add(new String[] {simpleName(key.getEntityName()) + "#" + key.getIdentifier(), Tool.identity(object), state}); + } + rows.subList(1, rows.size()).sort((a, b) -> a[0].compareTo(b[0])); + Tool.table(rows); + } + + private static String simpleName(String entityName) { + return entityName.substring(entityName.lastIndexOf('.') + 1); + } + + @Override + public void close() { + context.close(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Tool.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Tool.java new file mode 100644 index 0000000..86c1722 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/demo/Tool.java @@ -0,0 +1,86 @@ +package com.amigoscode.equality.demo; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +/** Small printing helpers shared by Demo and Inspect. */ +final class Tool { + + private Tool() { + } + + /** One line of evidence: what was called, and what it returned. */ + static void line(String call, Object result) { + line(call, result, ""); + } + + static void line(String call, Object result, String note) { + String value = String.valueOf(result); + String text = String.format(" %-36s %-" + Math.max(12, value.length()) + "s %s", call, value, note); + System.out.println(text.stripTrailing()); + } + + /** Runs the call. An exception is returned as its text instead of stopping the demo. */ + static Object attempt(Supplier call) { + try { + return call.get(); + } catch (RuntimeException e) { + return describe(e); + } + } + + /** "LazyInitializationException: Cannot lazily initialize ..." */ + static String describe(Throwable e) { + String message = e.getMessage() == null ? "" : e.getMessage().lines().findFirst().orElse(""); + return e.getClass().getSimpleName() + (message.isEmpty() ? "" : ": " + message); + } + + /** ClassName@1b2c3d: which Java object this is. */ + static String identity(Object object) { + return object.getClass().getSimpleName() + "@" + Integer.toHexString(System.identityHashCode(object)); + } + + /** Prints rows as a plain text table. The first row is the header. */ + static void table(List rows) { + if (rows.size() == 1) { + System.out.println(" (none)"); + return; + } + 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()); + } + } + } + + static List rows(String... header) { + List rows = new ArrayList<>(); + rows.add(header); + return rows; + } + + static void sql(List statements) { + if (statements.isEmpty()) { + System.out.println(" (none)"); + } + for (String statement : statements) { + System.out.println(" " + statement); + } + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/LineItem.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/LineItem.java new file mode 100644 index 0000000..d6b46de --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/LineItem.java @@ -0,0 +1,86 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.util.Objects; + +/** + * One line of an order: a product and a quantity. It has no business key of its own (the same + * product can be ordered twice), so the only thing that identifies it is its id, and the database + * assigns the id when the row is inserted. + */ +@Entity +@Table(name = "line_item") +public class LineItem { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "order_id") + private Order order; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id") + private Product product; + + private int quantity; + + protected LineItem() { + } + + LineItem(Order order, Product product, int quantity) { + this.order = order; + this.product = product; + this.quantity = quantity; + } + + public Long getId() { + return id; + } + + public Order getOrder() { + return order; + } + + public Product getProduct() { + return product; + } + + public int getQuantity() { + return quantity; + } + + // TODO Task 5: generated by the IDE with only the id ticked. The id is null until the row is + // inserted, and the database picks it during the save. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LineItem other = (LineItem) o; + return Objects.equals(id, other.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + @Override + public String toString() { + // product.getId(), not getSku(): on a proxy the id is known without loading the row. + return "LineItem#" + (id == null ? "new" : id) + " (" + quantity + " x product " + product.getId() + ")"; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/Order.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/Order.java new file mode 100644 index 0000000..abc401f --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/Order.java @@ -0,0 +1,72 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * An order and its line items. The items are a {@code Set}, so every add and remove goes through + * LineItem.hashCode and LineItem.equals. + * + *

Order itself does not override equals or hashCode: nothing puts orders in a Set or compares + * two of them. Nothing to change here. + */ +@Entity +@Table(name = "orders") +public class Order { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String customer; + + // orphanRemoval: an item removed from this Set is deleted from the database when the + // transaction commits. Only if it really leaves the Set. + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) + private Set items = new HashSet<>(); + + protected Order() { + } + + public Order(String customer) { + this.customer = customer; + } + + public Long getId() { + return id; + } + + public String getCustomer() { + return customer; + } + + /** Adds a new line item. Returns it, whether or not the Set accepted it. */ + public LineItem add(Product product, int quantity) { + LineItem item = new LineItem(this, product, quantity); + items.add(item); + return item; + } + + /** Returns false when the Set did not find the item, and so did not remove it. */ + public boolean remove(LineItem item) { + return items.remove(item); + } + + public Set getItems() { + return Collections.unmodifiableSet(items); + } + + /** The Set Hibernate manages, so ./inspect can show its buckets. */ + public Set backingSet() { + return items; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderLine.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderLine.java new file mode 100644 index 0000000..6e1efe9 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderLine.java @@ -0,0 +1,5 @@ +package com.amigoscode.equality.order; + +/** What the customer asked for: this many of this SKU. */ +public record OrderLine(String sku, int quantity) { +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderRepository.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderRepository.java new file mode 100644 index 0000000..c03c23a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderRepository.java @@ -0,0 +1,6 @@ +package com.amigoscode.equality.order; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrderRepository extends JpaRepository { +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderService.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderService.java new file mode 100644 index 0000000..14b691b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/OrderService.java @@ -0,0 +1,43 @@ +package com.amigoscode.equality.order; + +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.ProductRepository; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Places orders. Nothing to change here: the bugs are in the equals and hashCode of the entities. */ +@Service +public class OrderService { + + private final OrderRepository orders; + private final ProductRepository products; + + public OrderService(OrderRepository orders, ProductRepository products) { + this.orders = orders; + this.products = products; + } + + /** + * Creates the order with one line item per requested line and saves it. Then it drops every + * line the warehouse cannot deliver. That happens after the save on purpose: the stock + * reservation is made with the order number, which only exists once the order is saved. + */ + @Transactional + public Order placeOrder(String customer, List lines) { + Order order = new Order(customer); + for (OrderLine line : lines) { + Product product = products.findBySku(line.sku()).orElseThrow(() -> new UnknownProductException(line.sku())); + order.add(product, line.quantity()); + } + + orders.save(order); // INSERTs the order and its items now: every item gets its id here + + for (LineItem item : List.copyOf(order.getItems())) { + if (item.getProduct().getStock() < item.getQuantity()) { + order.remove(item); // out of stock: orphanRemoval deletes the row at commit + } + } + return order; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/UnknownProductException.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/UnknownProductException.java new file mode 100644 index 0000000..33bb573 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/order/UnknownProductException.java @@ -0,0 +1,8 @@ +package com.amigoscode.equality.order; + +public class UnknownProductException extends RuntimeException { + + public UnknownProductException(String sku) { + super("No product with SKU " + sku); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Product.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Product.java new file mode 100644 index 0000000..cc7ee47 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Product.java @@ -0,0 +1,109 @@ +package com.amigoscode.equality.product; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** A product in the catalogue. Its SKU is unique and never changes. */ +@Entity +public class Product { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true) + private String sku; + + private String name; + + private BigDecimal price; + + private int stock; + + @ManyToMany + @JoinTable(name = "product_tag", + joinColumns = @JoinColumn(name = "product_id"), + inverseJoinColumns = @JoinColumn(name = "tag_id")) + private Set tags = new HashSet<>(); + + protected Product() { + } + + public Product(String sku, String name, BigDecimal price, int stock) { + this.sku = sku; + this.name = name; + this.price = price; + this.stock = stock; + } + + public Long getId() { + return id; + } + + public String getSku() { + return sku; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public Set getTags() { + return tags; + } + + public void rename(String name) { + this.name = name; + } + + public void changePrice(BigDecimal price) { + this.price = price; + } + + // TODO Task 7: generated by the IDE with every field ticked. Lombok's @Data or + // @EqualsAndHashCode would use the same fields: the id, the price and the lazy tags. + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Product other = (Product) o; + return stock == other.stock + && Objects.equals(id, other.id) + && Objects.equals(sku, other.sku) + && Objects.equals(name, other.name) + && Objects.equals(price, other.price) + && Objects.equals(tags, other.tags); + } + + @Override + public int hashCode() { + return Objects.hash(id, sku, name, price, stock, tags); + } + + @Override + public String toString() { + return sku; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/ProductRepository.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/ProductRepository.java new file mode 100644 index 0000000..ba42a3e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/ProductRepository.java @@ -0,0 +1,15 @@ +package com.amigoscode.equality.product; + +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ProductRepository extends JpaRepository { + + Optional findBySku(String sku); + + /** The product with its tags already loaded, so they can be read after the transaction ends. */ + @Query("select p from Product p left join fetch p.tags where p.sku = :sku") + Optional findBySkuWithTags(@Param("sku") String sku); +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Tag.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Tag.java new file mode 100644 index 0000000..f248f00 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/product/Tag.java @@ -0,0 +1,44 @@ +package com.amigoscode.equality.product; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +/** + * A label on a product: wireless, gaming, audio. + * + *

Exhibit: Tag does NOT override equals or hashCode, in start/ and in solution/. It uses + * Object's: an object is only equal to itself. That is fine inside one transaction, because + * Hibernate gives you one Java object per row there. It stops working as soon as you compare a Tag + * from one transaction with a Tag from another. Task 6 shows both. Do not fix. + */ +@Entity +public class Tag { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + protected Tag() { + } + + public Tag(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Bundle.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Bundle.java new file mode 100644 index 0000000..e764535 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Bundle.java @@ -0,0 +1,19 @@ +package com.amigoscode.equality.value; + +import java.util.List; +import java.util.Objects; + +/** + * Products sold together at one price, for example "Desk set" = KEYBOARD-01 + MOUSE-01. The shop + * keeps bundle prices in a {@code Map}, so a Bundle is used as a map key. + * + *

A record compares its components with their own equals. For {@code skus} that is + * List.equals: same elements in the same order. + */ +public record Bundle(String name, List skus) { + + // TODO Task 4: the record keeps the list it was given. Whoever made that list can still change it. + public Bundle { + Objects.requireNonNull(name, "name"); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Money.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Money.java new file mode 100644 index 0000000..fffee3b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Money.java @@ -0,0 +1,61 @@ +package com.amigoscode.equality.value; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Objects; + +/** + * An amount in a currency, for example 89.00 EUR. A value object: equal amount and currency means + * equal Money. + */ +public final class Money { + + private final BigDecimal amount; + private final String currency; + + public Money(String amount, String currency) { + this(new BigDecimal(amount), currency); + } + + public Money(BigDecimal amount, String currency) { + Objects.requireNonNull(amount, "amount"); + Objects.requireNonNull(currency, "currency"); + // Always two decimals. BigDecimal.equals compares the scale too: 10.0 is not equal to 10.00. + // Setting the scale here means equals and hashCode below only ever see 10.00. + this.amount = amount.setScale(2, RoundingMode.UNNECESSARY); + this.currency = currency; + } + + public BigDecimal amount() { + return amount; + } + + public String currency() { + return currency; + } + + public Money plus(Money other) { + if (!currency.equals(other.currency)) { + throw new IllegalArgumentException("Cannot add " + other.currency + " to " + currency); + } + return new Money(amount.add(other.amount), currency); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Money other)) { + return false; + } + return amount.equals(other.amount) && currency.equals(other.currency); + } + + // TODO Task 2: equals is here, hashCode is not. + + @Override + public String toString() { + return amount.toPlainString() + " " + currency; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Sku.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Sku.java new file mode 100644 index 0000000..7c09a5b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/java/com/amigoscode/equality/value/Sku.java @@ -0,0 +1,31 @@ +package com.amigoscode.equality.value; + +import java.util.Objects; + +/** + * A stock keeping unit: the code that identifies a product, for example KEYBOARD-01. A value + * object: two Skus with the same code are the same Sku. + */ +public final class Sku { + + private final String code; + + public Sku(String code) { + Objects.requireNonNull(code, "code"); + if (code.isBlank()) { + throw new IllegalArgumentException("A SKU code cannot be blank"); + } + this.code = code; + } + + public String code() { + return code; + } + + // TODO Task 2: there is no equals and no hashCode here, so Sku inherits both from Object. + + @Override + public String toString() { + return code; + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/application.properties b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/application.properties new file mode 100644 index 0000000..ed60b5a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/application.properties @@ -0,0 +1,20 @@ +spring.application.name=equals-and-hashcode + +# No web server: the demo and the tests call the services directly. +spring.main.web-application-type=none + +# Postgres from compose.yaml. Port 5454 so it does not clash with a Postgres you already run. +# Only the JPA part (Tasks 5 to 7) needs it. The plain-Java part runs without a database. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5454/shop} +spring.datasource.username=${DB_USER:shop} +spring.datasource.password=${DB_PASSWORD:shop} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always + +# Lets the demo print, and the tests count, the SQL Hibernate sends. +spring.jpa.properties.hibernate.session_factory.statement_inspector=com.amigoscode.equality.db.SqlRecorder + +# Uncomment to see every SQL statement. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/schema.sql b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/schema.sql new file mode 100644 index 0000000..fcbf2dd --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/main/resources/schema.sql @@ -0,0 +1,30 @@ +create table if not exists tag ( + id bigint generated by default as identity primary key, + name text not null unique +); + +create table if not exists product ( + id bigint generated by default as identity primary key, + sku text not null unique, + name text not null, + price numeric(10, 2) not null, + stock int not null check (stock >= 0) +); + +create table if not exists product_tag ( + product_id bigint not null references product (id), + tag_id bigint not null references tag (id), + primary key (product_id, tag_id) +); + +create table if not exists orders ( + id bigint generated by default as identity primary key, + customer text not null +); + +create table if not exists line_item ( + id bigint generated by default as identity primary key, + order_id bigint not null references orders (id), + product_id bigint not null references product (id), + quantity int not null check (quantity > 0) +); diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/BundleTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/BundleTest.java new file mode 100644 index 0000000..490ef9e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/BundleTest.java @@ -0,0 +1,69 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.equality.value.Bundle; +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.util.ArrayList; +import java.util.HashMap; +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 4: Bundle is a record, and a record is only as immutable as its components. */ +@Tag("task4") +class BundleTest { + + private final Sku keyboard = new Sku("KEYBOARD-01"); + private final Sku mouse = new Sku("MOUSE-01"); + private final Sku headset = new Sku("HEADSET-01"); + + @Test + @DisplayName("Bundle: two bundles with the same name and SKUs are equal with the same hashCode: the record writes both (already passing: keep it that way)") + void recordsWriteEqualsAndHashCode() { + Bundle a = new Bundle("Desk set", List.of(keyboard, mouse)); + Bundle b = new Bundle("Desk set", new ArrayList<>(List.of(keyboard, mouse))); + + assertThat(a).isEqualTo(b); + assertThat(a.hashCode()).isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Bundle: changing the list a bundle was made from does not change the bundle, and its price is still found in the Map") + void theCallersListCannotChangeTheBundle() { + Map prices = new HashMap<>(); + List skus = new ArrayList<>(List.of(keyboard, mouse)); + Bundle desk = new Bundle("Desk set", skus); + prices.put(desk, new Money("119.00", "EUR")); + + skus.add(headset); // the caller reuses its list for the next bundle + + assertThat(desk.skus()).as("the bundle's SKUs").containsExactly(keyboard, mouse); + assertThat(prices.get(desk)).as("prices.get(desk)").isEqualTo(new Money("119.00", "EUR")); + } + + @Test + @DisplayName("Bundle: the list that skus() returns cannot be changed") + void skusCannotBeChanged() { + Bundle desk = new Bundle("Desk set", new ArrayList<>(List.of(keyboard, mouse))); + + assertThatThrownBy(() -> desk.skus().add(headset)).isInstanceOf(UnsupportedOperationException.class); + } + + /** A record with an array component. Records compare arrays with ==, like Object.equals. */ + record Barcode(byte[] digits) { + } + + @Test + @DisplayName("A record with an array component compares the array by identity: two Barcodes with the same digits are not equal (this documents the trap)") + void arraysInRecordsCompareByIdentity() { + Barcode a = new Barcode(new byte[] {4, 0, 0, 6}); + Barcode b = new Barcode(new byte[] {4, 0, 0, 6}); + + assertThat(a.equals(b)).as("a.equals(b)").isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/CartLineTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/CartLineTest.java new file mode 100644 index 0000000..1a02863 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/CartLineTest.java @@ -0,0 +1,55 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.cart.Cart; +import com.amigoscode.equality.cart.CartLine; +import com.amigoscode.equality.value.Sku; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 4: a CartLine changes while it sits in the cart's HashSet. */ +@Tag("task4") +class CartLineTest { + + private final Sku keyboard = new Sku("KEYBOARD-01"); + + @Test + @DisplayName("CartLine: after the quantity changes, the cart still contains the line, and remove takes it out") + void stillFoundAfterTheQuantityChanges() { + Cart cart = new Cart(); + CartLine line = new CartLine(keyboard, 1); + cart.add(line); + + line.changeQuantity(3); + + assertThat(cart.contains(line)).as("cart.contains(line)").isTrue(); + assertThat(cart.remove(line)).as("cart.remove(line)").isTrue(); + assertThat(cart.size()).as("lines left in the cart").isZero(); + } + + @Test + @DisplayName("CartLine: adding the same line again after a change does not put it in the cart twice") + void notAddedTwice() { + Cart cart = new Cart(); + CartLine line = new CartLine(keyboard, 1); + cart.add(line); + + line.changeQuantity(3); + cart.add(line); + + assertThat(cart.size()).as("lines in the cart").isEqualTo(1); + } + + @Test + @DisplayName("CartLine: hashCode stays the same when the quantity changes") + void hashCodeDoesNotChange() { + CartLine line = new CartLine(keyboard, 1); + int before = line.hashCode(); + + line.changeQuantity(3); + + assertThat(line.hashCode()).as("hashCode after the change").isEqualTo(before); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/Check.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/Check.java new file mode 100644 index 0000000..a4daa1a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.equality; + +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. Task 8 is an inspection task with nothing to run: you answer questions. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: one value, one order line (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See it break"); + TASKS.put("2", "Task 2: Fix the value objects"); + TASKS.put("3", "Task 3: Inspect the hash table"); + TASKS.put("4", "Task 4: Fix the keys that change"); + TASKS.put("5", "Task 5: Fix the line items (generated id)"); + TASKS.put("6", "Task 6: Inspect the persistence context"); + TASKS.put("7", "Task 7: Fix the product (all-fields equals, lazy loading, proxies)"); + } + + 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/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/HashContractTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/HashContractTest.java new file mode 100644 index 0000000..35c931b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/HashContractTest.java @@ -0,0 +1,49 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +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 3. These tests pass on purpose: they pin down the other half of the contract. Equal objects + * must have the same hash. The same hash does NOT mean equal. + */ +@Tag("task3") +class HashContractTest { + + @Test + @DisplayName("\"Aa\" and \"BB\" have the same hashCode and a HashSet keeps both: the same hash does not mean equal (this documents the contract)") + void sameHashIsNotEqual() { + assertThat("Aa".hashCode()).isEqualTo("BB".hashCode()); + + Set set = new HashSet<>(Set.of("Aa", "BB")); + + assertThat(set).containsExactlyInAnyOrder("Aa", "BB"); + } + + /** Legal, and slow: every object has the same hash. */ + record SameHash(int value) { + @Override + public int hashCode() { + return 42; + } + } + + @Test + @DisplayName("A hashCode that returns 42 for every object is legal: the HashSet is still correct, only slower (this documents the contract)") + void constantHashIsLegal() { + Set set = new HashSet<>(); + for (int i = 0; i < 100; i++) { + set.add(new SameHash(i)); + } + set.add(new SameHash(7)); + + assertThat(set).hasSize(100); + assertThat(set.contains(new SameHash(99))).isTrue(); + assertThat(set.contains(new SameHash(100))).isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/LineItemIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/LineItemIT.java new file mode 100644 index 0000000..83f003d --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/LineItemIT.java @@ -0,0 +1,84 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: LineItem has no business key. Its id is assigned by the database, during the save. */ +@Tag("task5") +class LineItemIT extends IntegrationTest { + + @Test + @DisplayName("LineItem: two new line items added to an order before it is saved are both saved") + void twoNewItemsAreBothSaved() { + orderService.placeOrder("ana", List.of(new OrderLine(ShopData.KEYBOARD, 1), new OrderLine(ShopData.MOUSE, 2))); + + assertThat(lineItemRows()).as("rows in line_item for 2 ordered lines").isEqualTo(2); + } + + @Test + @DisplayName("LineItem: an out-of-stock line removed after the order was saved is really removed: its row is deleted") + void removedAfterTheSave() { + Order order = orderService.placeOrder("ana", List.of(new OrderLine(ShopData.HEADSET, 1))); + + assertThat(order.getItems()).as("items left in the order").isEmpty(); + assertThat(lineItemRows()).as("rows in line_item").isZero(); + } + + @Test + @DisplayName("LineItem: an item is still found in order.getItems() after the save gave it an id") + void stillFoundAfterTheIdIsAssigned() { + inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Order order = new Order("ana"); + LineItem item = order.add(keyboard, 1); + + em.persist(order); + + assertThat(item.getId()).as("id after persist").isNotNull(); + assertThat(order.getItems().contains(item)).as("order.getItems().contains(item)").isTrue(); + }); + } + + @Test + @DisplayName("LineItem: the same row loaded in two transactions gives two objects that are equal (already passing: keep it that way)") + void sameRowInTwoTransactionsIsEqual() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD); + long itemId = jdbc.queryForObject("select id from line_item where order_id = ?", Long.class, orderId); + + LineItem first = inTransaction(() -> em.find(LineItem.class, itemId)); + LineItem second = inTransaction(() -> em.find(LineItem.class, itemId)); + + assertThat(first).as("two loads, two Java objects").isNotSameAs(second); + assertThat(first.equals(second)).as("first.equals(second)").isTrue(); + } + + @Test + @DisplayName("LineItem: an item is equal to a Hibernate proxy of the same row, and comparing them does not load the row") + void equalToItsProxyWithoutLoadingIt() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD); + long itemId = jdbc.queryForObject("select id from line_item where order_id = ?", Long.class, orderId); + LineItem loaded = inTransaction(() -> em.find(LineItem.class, itemId)); + + inTransaction(() -> { + LineItem proxy = em.getReference(LineItem.class, itemId); + + SqlRecorder.start(); + boolean equal = loaded.equals(proxy); + List sql = SqlRecorder.stop(); + + assertThat(equal).as("loaded.equals(proxy), proxy class " + proxy.getClass().getSimpleName()).isTrue(); + assertThat(sql).as("SQL sent by loaded.equals(proxy)").isEmpty(); + }); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/MoneyTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/MoneyTest.java new file mode 100644 index 0000000..96f1f6a --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/MoneyTest.java @@ -0,0 +1,47 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.value.Money; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 2: Money already has equals. Equal objects must also have equal hash codes. */ +@Tag("task2") +class MoneyTest { + + @Test + @DisplayName("Money: equal amounts have the same hashCode, also when one is written 10.5 and the other 10.50") + void equalMoneyHasEqualHashCodes() { + Money a = new Money("10.5", "EUR"); + Money b = new Money("10.50", "EUR"); + + assertThat(a.equals(b)).as("a.equals(b)").isTrue(); + assertThat(a.hashCode()).as("hashCode of a and of b").isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Money: a HashSet keeps one of two equal amounts, and HashMap.get finds the value by an equal key") + void hashCollectionsAgreeWithEquals() { + Set amounts = new HashSet<>(); + amounts.add(new Money("89.00", "EUR")); + amounts.add(new Money("89.00", "EUR")); + + Map labels = new HashMap<>(); + labels.put(new Money("0.00", "EUR"), "free"); + + assertThat(amounts).as("HashSet of two equal amounts").hasSize(1); + assertThat(labels.get(new Money("0.00", "EUR"))).as("labels.get").isEqualTo("free"); + } + + @Test + @DisplayName("Money: 10.00 EUR is not equal to 10.00 USD (already passing: keep it that way)") + void currencyIsPartOfEquality() { + assertThat(new Money("10.00", "EUR").equals(new Money("10.00", "USD"))).isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java new file mode 100644 index 0000000..4d0b209 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ObjectIdentityTest.java @@ -0,0 +1,73 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +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 1. These tests pass on purpose: they pin down what Java does when a class does not write its + * own equals and hashCode, and in which order a HashSet asks the two questions. + */ +@Tag("task1") +class ObjectIdentityTest { + + /** A class with no equals and no hashCode of its own, like Sku in start/. */ + static final class Code { + final String value; + + Code(String value) { + this.value = value; + } + } + + @Test + @DisplayName("A class without its own equals inherits Object.equals: same values are not enough, an object is only equal to itself (this documents the cause)") + void objectEqualsIsIdentity() { + Code a = new Code("KEYBOARD-01"); + Code b = new Code("KEYBOARD-01"); + + assertThat(a.equals(b)).as("a.equals(b)").isFalse(); + assertThat(a.equals(a)).as("a.equals(a)").isTrue(); + assertThat(new HashSet<>(Set.of(a, b))).as("a HashSet of a and b").hasSize(2); + } + + /** Counts how often a HashSet calls equals, so you can see when it does. */ + static final class Counted { + static int equalsCalls; + final int hash; + + Counted(int hash) { + this.hash = hash; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object o) { + equalsCalls++; + return o instanceof Counted other && other.hash == hash; + } + } + + @Test + @DisplayName("HashSet.add asks hashCode first, and only calls equals for an element with the same hash (this documents the order)") + void hashCodeFirstThenEquals() { + Set set = new HashSet<>(); + set.add(new Counted(1)); + + Counted.equalsCalls = 0; + set.add(new Counted(2)); + assertThat(Counted.equalsCalls).as("equals calls when the hash is different").isZero(); + + set.add(new Counted(1)); + assertThat(Counted.equalsCalls).as("equals calls when the hash is the same").isEqualTo(1); + assertThat(set).hasSize(2); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/OrderBasicsIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/OrderBasicsIT.java new file mode 100644 index 0000000..11beb1b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/OrderBasicsIT.java @@ -0,0 +1,26 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.order.OrderLine; +import com.amigoscode.equality.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline: one order with one line works. Passes from the start and must stay green. */ +@Tag("baseline") +class OrderBasicsIT extends IntegrationTest { + + @Test + @DisplayName("An order placed with one line is saved with that line") + void oneLineIsSaved() { + orderService.placeOrder("ana", List.of(new OrderLine(ShopData.KEYBOARD, 2))); + + assertThat(jdbc.queryForList(""" + select p.sku, li.quantity from line_item li join product p on p.id = li.product_id + """)).as("rows in line_item").containsExactly(java.util.Map.of("sku", ShopData.KEYBOARD, "quantity", 2)); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/PersistenceContextIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/PersistenceContextIT.java new file mode 100644 index 0000000..59d0c8b --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/PersistenceContextIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.product.Tag; +import com.amigoscode.equality.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Task 6. These tests pass on purpose: they pin down what the persistence context promises (one + * Java object per row, inside one transaction) and where that promise ends. + */ +@org.junit.jupiter.api.Tag("task6") +class PersistenceContextIT extends IntegrationTest { + + @Test + @DisplayName("Inside one transaction, loading the same row twice gives the same Java object, so even Object.equals works (this documents the guarantee)") + void oneRowOneObjectInOneTransaction() { + inTransaction(() -> { + Product byId = em.find(Product.class, productId(ShopData.KEYBOARD)); + Product bySku = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + + assertThat(bySku).as("find by id and find by SKU").isSameAs(byId); + }); + } + + @Test + @DisplayName("In two transactions, the same row comes back as two different Java objects (this documents where the guarantee ends)") + void twoObjectsInTwoTransactions() { + Product first = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + Product second = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + assertThat(second).isNotSameAs(first); + } + + @Test + @DisplayName("Tag uses Object.equals: a product's tags contain the tag loaded in the same transaction, and not the same tag loaded in another one (this documents the trap)") + void identityEqualsAcrossTransactions() { + Tag gamingFromEarlier = inTransaction(() -> gamingTag()); + + inTransaction(() -> { + Product keyboard = products.findBySku(ShopData.KEYBOARD).orElseThrow(); + Tag gamingNow = gamingTag(); + + assertThat(keyboard.getTags().contains(gamingNow)).as("contains the gaming tag from this transaction").isTrue(); + assertThat(keyboard.getTags().contains(gamingFromEarlier)).as("contains the gaming tag from another transaction").isFalse(); + }); + } + + private Tag gamingTag() { + return em.createQuery("select t from Tag t where t.name = 'gaming'", Tag.class).getSingleResult(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductIT.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductIT.java new file mode 100644 index 0000000..a7e571e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductIT.java @@ -0,0 +1,88 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.db.SqlRecorder; +import com.amigoscode.equality.order.LineItem; +import com.amigoscode.equality.order.Order; +import com.amigoscode.equality.product.Product; +import com.amigoscode.equality.support.IntegrationTest; +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7: Product has a business key, its SKU. */ +@Tag("task7") +class ProductIT extends IntegrationTest { + + @Test + @DisplayName("Product: putting loaded products in a HashSet sends no SQL (hashCode does not load the lazy tags)") + void hashingSendsNoSql() { + inTransaction(() -> { + List all = products.findAll(); + + SqlRecorder.start(); + Set set = new HashSet<>(all); + List sql = SqlRecorder.stop(); + + assertThat(set).hasSize(3); + assertThat(sql).as("SQL sent while adding 3 products to a HashSet").isEmpty(); + }); + } + + @Test + @DisplayName("Product: products can be put in a HashSet after their transaction has ended (no LazyInitializationException)") + void hashingWorksAfterTheTransaction() { + List all = inTransaction(() -> products.findAll()); + + assertThatCode(() -> new HashSet<>(all)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("Product: a product is equal to a Hibernate proxy of the same row, in both directions") + void equalToItsProxyBothWays() { + Product keyboard = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + inTransaction(() -> { + Product proxy = em.getReference(Product.class, keyboard.getId()); + + assertThat(keyboard.equals(proxy)).as("keyboard.equals(proxy), proxy class " + proxy.getClass().getSimpleName()).isTrue(); + assertThat(proxy.equals(keyboard)).as("proxy.equals(keyboard)").isTrue(); + }); + } + + @Test + @DisplayName("Product: the products of an order (lazy proxies) contain the same product loaded by the catalogue in another transaction") + void foundAmongTheProductsOfAnOrder() { + long orderId = ShopData.insertOrder(jdbc, "ana", ShopData.KEYBOARD, ShopData.MOUSE); + Product keyboard = inTransaction(() -> products.findBySku(ShopData.KEYBOARD).orElseThrow()); + + inTransaction(() -> { + Order order = em.find(Order.class, orderId); + Set inOrder = order.getItems().stream().map(LineItem::getProduct).collect(Collectors.toSet()); + + assertThat(inOrder.contains(keyboard)).as("products in the order contain the keyboard").isTrue(); + }); + } + + @Test + @DisplayName("Product: a new product is still found in its HashSet after the save gave it an id") + void stillFoundAfterTheIdIsAssigned() { + inTransaction(() -> { + Product cable = new Product("CABLE-01", "USB-C cable", new BigDecimal("9.00"), 100); + Set newProducts = new HashSet<>(Set.of(cable)); + + em.persist(cable); + + assertThat(cable.getId()).as("id after persist").isNotNull(); + assertThat(newProducts.contains(cable)).as("newProducts.contains(cable)").isTrue(); + }); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductTest.java new file mode 100644 index 0000000..7107634 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ProductTest.java @@ -0,0 +1,29 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.product.Product; +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 7, without a database: the price of a product changes, its identity does not. */ +@Tag("task7") +class ProductTest { + + @Test + @DisplayName("Product: changing the price does not change the hashCode, so the product is not lost from a HashSet") + void priceChangeDoesNotLoseIt() { + Product keyboard = new Product("KEYBOARD-01", "Mechanical keyboard", new BigDecimal("89.00"), 10); + Set onSale = new HashSet<>(Set.of(keyboard)); + int before = keyboard.hashCode(); + + keyboard.changePrice(new BigDecimal("79.00")); + + assertThat(keyboard.hashCode()).as("hashCode after the price change").isEqualTo(before); + assertThat(onSale.contains(keyboard)).as("onSale.contains(keyboard)").isTrue(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/SkuTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/SkuTest.java new file mode 100644 index 0000000..f4054e0 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/SkuTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 2: Sku is a value object. Two Skus with the same code are the same Sku. */ +@Tag("task2") +class SkuTest { + + @Test + @DisplayName("Sku: two Skus with the same code are equal, and have the same hashCode") + void sameCodeIsEqual() { + Sku a = new Sku("KEYBOARD-01"); + Sku b = new Sku("KEYBOARD-01"); + + assertThat(a.equals(b)).as("a.equals(b)").isTrue(); + assertThat(b.equals(a)).as("b.equals(a)").isTrue(); + assertThat(a.hashCode()).as("hashCode of a and of b").isEqualTo(b.hashCode()); + } + + @Test + @DisplayName("Sku: list.contains and map.get find an equal Sku that is a different object") + void lookupsFindAnEqualSku() { + Map prices = new HashMap<>(); + prices.put(new Sku("KEYBOARD-01"), new Money("89.00", "EUR")); + + assertThat(List.of(new Sku("KEYBOARD-01")).contains(new Sku("KEYBOARD-01"))).as("list.contains").isTrue(); + assertThat(prices.get(new Sku("KEYBOARD-01"))).as("prices.get").isEqualTo(new Money("89.00", "EUR")); + } + + @Test + @DisplayName("Sku: a HashSet keeps one of two equal Skus") + void setKeepsOne() { + Set skus = new HashSet<>(); + + assertThat(skus.add(new Sku("KEYBOARD-01"))).as("first add").isTrue(); + assertThat(skus.add(new Sku("KEYBOARD-01"))).as("second add of an equal Sku").isFalse(); + assertThat(skus).hasSize(1); + } + + @Test + @DisplayName("Sku: not equal to a different code, to null, or to a String with the same text (already passing: keep it that way)") + void notEqualToOtherThings() { + Sku keyboard = new Sku("KEYBOARD-01"); + + assertThat(keyboard.equals(new Sku("MOUSE-01"))).as("different code").isFalse(); + assertThat(keyboard.equals(null)).as("null").isFalse(); + assertThat(keyboard.equals((Object) "KEYBOARD-01")).as("a String").isFalse(); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ValueBasicsTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ValueBasicsTest.java new file mode 100644 index 0000000..de19b8e --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/ValueBasicsTest.java @@ -0,0 +1,27 @@ +package com.amigoscode.equality; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.equality.value.Money; +import com.amigoscode.equality.value.Sku; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline: the value objects hold their values. Passes from the start and must stay green. */ +@Tag("baseline") +class ValueBasicsTest { + + @Test + @DisplayName("Sku and Money hold their values: a blank SKU is rejected, 10.5 EUR is kept as 10.50, and Money adds up") + void valueObjectsHoldTheirValues() { + assertThat(new Sku("KEYBOARD-01").code()).isEqualTo("KEYBOARD-01"); + assertThatThrownBy(() -> new Sku(" ")).isInstanceOf(IllegalArgumentException.class); + + Money money = new Money("10.5", "EUR"); + assertThat(money.amount()).hasToString("10.50"); + assertThat(money.plus(new Money("0.25", "EUR")).amount()).hasToString("10.75"); + assertThatThrownBy(() -> money.plus(new Money("1", "USD"))).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/support/IntegrationTest.java b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/support/IntegrationTest.java new file mode 100644 index 0000000..7c148a4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/java/com/amigoscode/equality/support/IntegrationTest.java @@ -0,0 +1,76 @@ +package com.amigoscode.equality.support; + +import com.amigoscode.equality.db.ShopData; +import com.amigoscode.equality.order.OrderService; +import com.amigoscode.equality.product.ProductRepository; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run real Hibernate against a real Postgres started by + * Testcontainers (Docker must be running), because proxies, lazy loading and generated ids only + * behave like this with a real persistence context. One container is shared by every test class. + * + *

The tests are not @Transactional on purpose: each one says where its transactions start and + * end with {@code inTransaction(...)}, because what equals does depends on it. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + 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); + } + + @Autowired + protected OrderService orderService; + + @Autowired + protected ProductRepository products; + + @Autowired + protected EntityManager em; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private TransactionTemplate transactions; + + @BeforeEach + void freshShop() { + ShopData.reset(jdbc); + } + + /** Runs the work in one new transaction, and returns what it returns. */ + protected T inTransaction(java.util.function.Supplier work) { + return transactions.execute(status -> work.get()); + } + + protected void inTransaction(Runnable work) { + transactions.executeWithoutResult(status -> work.run()); + } + + protected int lineItemRows() { + return jdbc.queryForObject("select count(*) from line_item", Integer.class); + } + + protected long productId(String sku) { + return jdbc.queryForObject("select id from product where sku = ?", Long.class, sku); + } +} diff --git a/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/15-equals-and-hashcode/start/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + +