├── .github └── workflows │ └── build.yml ├── .gitignore ├── README.md ├── adapter ├── pom.xml └── src │ ├── main │ ├── java │ │ └── eu │ │ │ └── happycoders │ │ │ └── shop │ │ │ └── adapter │ │ │ ├── in │ │ │ └── rest │ │ │ │ ├── cart │ │ │ │ ├── AddToCartController.java │ │ │ │ ├── CartLineItemWebModel.java │ │ │ │ ├── CartWebModel.java │ │ │ │ ├── EmptyCartController.java │ │ │ │ └── GetCartController.java │ │ │ │ ├── common │ │ │ │ ├── ControllerCommons.java │ │ │ │ ├── CustomerIdParser.java │ │ │ │ ├── ErrorEntity.java │ │ │ │ └── ProductIdParser.java │ │ │ │ └── product │ │ │ │ ├── FindProductsController.java │ │ │ │ └── ProductInListWebModel.java │ │ │ └── out │ │ │ └── persistence │ │ │ ├── DemoProducts.java │ │ │ ├── inmemory │ │ │ ├── InMemoryCartRepository.java │ │ │ └── InMemoryProductRepository.java │ │ │ └── jpa │ │ │ ├── CartJpaEntity.java │ │ │ ├── CartLineItemJpaEntity.java │ │ │ ├── CartMapper.java │ │ │ ├── EntityManagerFactoryFactory.java │ │ │ ├── JpaCartRepository.java │ │ │ ├── JpaProductRepository.java │ │ │ ├── ProductJpaEntity.java │ │ │ └── ProductMapper.java │ └── resources │ │ └── META-INF │ │ └── persistence.xml │ └── test │ └── java │ └── eu │ └── happycoders │ └── shop │ └── adapter │ ├── in │ └── rest │ │ ├── HttpTestCommons.java │ │ ├── cart │ │ ├── CartsControllerAssertions.java │ │ └── CartsControllerTest.java │ │ └── product │ │ ├── ProductsControllerAssertions.java │ │ └── ProductsControllerTest.java │ └── out │ └── persistence │ ├── AbstractCartRepositoryTest.java │ ├── AbstractProductRepositoryTest.java │ ├── inmemory │ ├── InMemoryCartRepositoryTest.java │ └── InMemoryProductRepositoryTest.java │ └── jpa │ ├── JpaCartRepositoryTest.java │ └── JpaProductRepositoryTest.java ├── application ├── pom.xml └── src │ ├── main │ └── java │ │ └── eu │ │ └── happycoders │ │ └── shop │ │ └── application │ │ ├── port │ │ ├── in │ │ │ ├── cart │ │ │ │ ├── AddToCartUseCase.java │ │ │ │ ├── EmptyCartUseCase.java │ │ │ │ ├── GetCartUseCase.java │ │ │ │ └── ProductNotFoundException.java │ │ │ └── product │ │ │ │ └── FindProductsUseCase.java │ │ └── out │ │ │ └── persistence │ │ │ ├── CartRepository.java │ │ │ └── ProductRepository.java │ │ └── service │ │ ├── cart │ │ ├── AddToCartService.java │ │ ├── EmptyCartService.java │ │ └── GetCartService.java │ │ └── product │ │ └── FindProductsService.java │ └── test │ └── java │ └── eu │ └── happycoders │ └── shop │ └── application │ └── service │ ├── cart │ ├── AddToCartServiceTest.java │ ├── EmptyCartServiceTest.java │ └── GetCartServiceTest.java │ └── product │ └── FindProductsServiceTest.java ├── bootstrap ├── pom.xml └── src │ ├── main │ └── java │ │ └── eu │ │ └── happycoders │ │ └── shop │ │ └── bootstrap │ │ ├── Launcher.java │ │ └── RestEasyUndertowShopApplication.java │ └── test │ └── java │ └── eu │ └── happycoders │ └── shop │ └── bootstrap │ ├── archunit │ └── DependencyRuleTest.java │ └── e2e │ ├── CartTest.java │ ├── EndToEndTest.java │ └── FindProductsTest.java ├── doc ├── architecture-components.plantuml ├── hexagonal-architecture-modules.png ├── persistence-tests.plantuml ├── ports-and-services-and-adapters-alt.plantuml ├── ports-and-services-and-adapters.plantuml ├── ports-and-services.plantuml ├── sample-requests.http ├── shop-model-iteration-1.plantuml ├── shop-model-iteration-2.plantuml ├── shop-model-iteration-3.plantuml ├── shop-model-iteration-4.plantuml └── shop-model-iteration-5.plantuml ├── google_checks.xml ├── img ├── Java_Versions_PDF_Cheat_Sheet_Mockup_936.png ├── big-o-cheat-sheet-pdf-en-transp_936.png └── mastering-data-structures-product-mockup-cropped-1600.png ├── model ├── pom.xml └── src │ ├── main │ └── java │ │ └── eu │ │ └── happycoders │ │ └── shop │ │ └── model │ │ ├── cart │ │ ├── Cart.java │ │ ├── CartLineItem.java │ │ └── NotEnoughItemsInStockException.java │ │ ├── customer │ │ └── CustomerId.java │ │ ├── money │ │ └── Money.java │ │ └── product │ │ ├── Product.java │ │ └── ProductId.java │ └── test │ └── java │ └── eu │ └── happycoders │ └── shop │ └── model │ ├── cart │ ├── CartTest.java │ └── TestCartFactory.java │ ├── customer │ └── CustomerIdTest.java │ ├── money │ ├── MoneyTest.java │ └── TestMoneyFactory.java │ └── product │ └── TestProductFactory.java ├── pmd-ruleset.xml ├── pom.xml └── spotbugs-exclude.xml /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build-jvm: 11 | name: Build 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v3 18 | with: 19 | fetch-depth: 0 # Fetch all history for all branches and tags (otherwise Sonar will report: "Shallow clone detected, no blame information will be provided.") 20 | 21 | - name: Set up JDK 22 | uses: actions/setup-java@v3 23 | with: 24 | distribution: 'temurin' 25 | java-version: 20 26 | 27 | - name: Cache SonarCloud packages 28 | uses: actions/cache@v3 29 | with: 30 | path: ~/.sonar/cache 31 | key: ${{ runner.os }}-sonar 32 | restore-keys: ${{ runner.os }}-sonar 33 | 34 | - name: Cache Maven packages 35 | uses: actions/cache@v3 36 | with: 37 | path: ~/.m2 38 | key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} 39 | restore-keys: ${{ runner.os }}-m2 40 | 41 | - name: Verify code format 42 | run: mvn -B spotless:check 43 | 44 | - name: Compile, test, and verify 45 | run: mvn -B verify -Ptest-coverage,code-analysis 46 | 47 | - name: Analyze code with Sonar 48 | if: ${{ env.SONAR_TOKEN }} # the token is not available in Dependabot-triggered builds 49 | env: 50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 51 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 52 | run: mvn -B package org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -DskipTests 53 | # We're building twice (takes only 2s) as otherwise, Sonar would complain: 54 | # The following dependencies could not be resolved at this point of the build but seem to be part of the reactor: 55 | # o ... 56 | # Try running the build up to the lifecycle phase "package" 57 | # 58 | # If the "package" phase takes much longer in the future, this step and the previous one should be combined into one. 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | !**/src/main/**/target/ 4 | !**/src/test/**/target/ 5 | 6 | ### IntelliJ IDEA ### 7 | .idea 8 | *.iws 9 | *.iml 10 | *.ipr 11 | 12 | ### Eclipse ### 13 | .apt_generated 14 | .classpath 15 | .factorypath 16 | .project 17 | .settings 18 | .springBeans 19 | .sts4-cache 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | build/ 28 | !**/src/main/**/build/ 29 | !**/src/test/**/build/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | 34 | ### Mac OS ### 35 | .DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hexagonal Architecture in Java Tutorial 2 | 3 | [![Build](https://github.com/SvenWoltmann/hexagonal-architecture-java/actions/workflows/build.yml/badge.svg)](https://github.com/SvenWoltmann/hexagonal-architecture-java/actions/workflows/build.yml) 4 | [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_hexagonal-architecture-java&metric=coverage)](https://sonarcloud.io/dashboard?id=SvenWoltmann_hexagonal-architecture-java) 5 | [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_hexagonal-architecture-java&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_hexagonal-architecture-java) 6 | [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_hexagonal-architecture-java&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_hexagonal-architecture-java) 7 | [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_hexagonal-architecture-java&metric=security_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_hexagonal-architecture-java) 8 | 9 | This repository contains a sample Java REST application implemented according to hexagonal architecture. 10 | 11 | It is part of the HappyCoders tutorial series on Hexagonal Architecture: 12 | * [Part 1: Hexagonal Architecture - What Is It? Why Should You Use It?](https://www.happycoders.eu/software-craftsmanship/hexagonal-architecture/). 13 | * [Part 2: Hexagonal Architecture with Java - Tutorial](https://www.happycoders.eu/software-craftsmanship/hexagonal-architecture-java/). 14 | * [Part 3: Ports and Adapters Java Tutorial: Adding a Database Adapter](https://www.happycoders.eu/software-craftsmanship/ports-and-adapters-java-tutorial-db/). 15 | * [Part 4: Hexagonal Architecture with Quarkus - Tutorial](https://www.happycoders.eu/software-craftsmanship/hexagonal-architecture-quarkus/). 16 | * [Part 5: Hexagonal Architecture with Spring Boot - Tutorial](https://www.happycoders.eu/software-craftsmanship/hexagonal-architecture-spring-boot/). 17 | 18 | # Branches 19 | 20 | ## `main` 21 | 22 | In the `main` branch, you'll find the application implemented without an application framework. It's only using: 23 | * [RESTEasy](https://resteasy.dev/) (implementing [Jakarta RESTful Web Services](https://jakarta.ee/specifications/restful-ws/)), 24 | * [Hibernate](https://hibernate.org/) (implementing [Jakarta Persistence API](https://jakarta.ee/specifications/persistence/)), and 25 | * [Undertow](https://undertow.io/) as a lightweight web server. 26 | 27 | ## `without-jpa-adapters` 28 | 29 | In the `without-jpa-adapters` branch, you'll find the application implemented without an application framework and without JPA adapters. It's only using RESTEasy and Undertow. 30 | 31 | ## `with-quarkus` 32 | 33 | In the `with-quarkus` branch, you'll find an implementation using [Quarkus](https://quarkus.io/) as application framework. 34 | 35 | ## `with-spring` 36 | 37 | In the `with-quarkus` branch, you'll find an implementation using [Spring](https://spring.io/) as application framework. 38 | 39 | # Architecture Overview 40 | 41 | The source code is separated into four modules: 42 | * `model` - contains the domain model 43 | * `application` - contains the domain services and the ports of the hexagon 44 | * `adapters` - contains the REST, in-memory and JPA adapters 45 | * `boostrap` - contains the configuration and bootstrapping logic 46 | 47 | The following diagram shows the hexagonal architecture of the application along with the source code modules: 48 | 49 | ![Hexagonal Architecture Modules](doc/hexagonal-architecture-modules.png) 50 | 51 | The `model` module is not represented as a hexagon because it is not defined by the Hexagonal Architecture. Hexagonal Architecture leaves open what happens inside the application hexagon. 52 | 53 | # How to Run the Application 54 | 55 | The easiest way to run the application is to start the `main` method of the `Launcher` class (you'll find it in the `boostrap` module) from your IDE. 56 | 57 | You can use one of the following VM options to select a persistence mechanism: 58 | 59 | * `-Dpersistence=inmemory` to select the in-memory persistence option (default) 60 | * `-Dpersistence=mysql` to select the MySQL option 61 | 62 | If you selected the MySQL option, you will need a running MySQL database. The easiest way to start one is to use the following Docker command: 63 | 64 | ```shell 65 | docker run --name hexagon-mysql -d -p3306:3306 \ 66 | -e MYSQL_DATABASE=shop -e MYSQL_ROOT_PASSWORD=test mysql:8.1 67 | ``` 68 | 69 | The connection parameters for the database are hardcoded in `RestEasyUndertowShopApplication.initMySqlAdapter()`. If you are using the Docker container as described above, you can leave the connection parameters as they are. Otherwise, you may need to adjust them. 70 | 71 | 72 | # Example Curl Commands 73 | 74 | The following `curl` commands assume that you have installed `jq`, a tool for pretty-printing JSON strings. 75 | 76 | ## Find Products 77 | 78 | The following queries return one and two results, respectively: 79 | 80 | ```shell 81 | curl localhost:8080/products/?query=plastic | jq 82 | curl localhost:8080/products/?query=monitor | jq 83 | ``` 84 | 85 | The response of the second query looks like this: 86 | ```json 87 | [ 88 | { 89 | "id": "K3SR7PBX", 90 | "name": "27-Inch Curved Computer Monitor", 91 | "price": { 92 | "currency": "EUR", 93 | "amount": 159.99 94 | }, 95 | "itemsInStock": 24081 96 | }, 97 | { 98 | "id": "Q3W43CNC", 99 | "name": "Dual Monitor Desk Mount", 100 | "price": { 101 | "currency": "EUR", 102 | "amount": 119.9 103 | }, 104 | "itemsInStock": 1079 105 | } 106 | ] 107 | ``` 108 | 109 | ## Get a Cart 110 | 111 | To show the cart of user 61157 (this cart is empty when you begin): 112 | 113 | ```shell 114 | curl localhost:8080/carts/61157 | jq 115 | ``` 116 | 117 | The response should look like this: 118 | 119 | ```json 120 | { 121 | "lineItems": [], 122 | "numberOfItems": 0, 123 | "subTotal": null 124 | } 125 | ``` 126 | 127 | ## Adding Products to a Cart 128 | 129 | Each of the following commands adds a product to the cart and returns the contents of the cart after the product is added (note that on Windows, you have to replace the single quotes with double quotes): 130 | 131 | ```shell 132 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=TTKQ8NJZ&quantity=20' | jq 133 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=K3SR7PBX&quantity=2' | jq 134 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=Q3W43CNC&quantity=1' | jq 135 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=WM3BPG3E&quantity=3' | jq 136 | ``` 137 | 138 | After executing two of the four commands, you can see that the cart contains the two products. You also see the total number of items and the sub-total: 139 | 140 | ```json 141 | { 142 | "lineItems": [ 143 | { 144 | "productId": "TTKQ8NJZ", 145 | "productName": "Plastic Sheeting", 146 | "price": { 147 | "currency": "EUR", 148 | "amount": 42.99 149 | }, 150 | "quantity": 20 151 | }, 152 | { 153 | "productId": "K3SR7PBX", 154 | "productName": "27-Inch Curved Computer Monitor", 155 | "price": { 156 | "currency": "EUR", 157 | "amount": 159.99 158 | }, 159 | "quantity": 2 160 | } 161 | ], 162 | "numberOfItems": 22, 163 | "subTotal": { 164 | "currency": "EUR", 165 | "amount": 1179.78 166 | } 167 | } 168 | ``` 169 | 170 | This will increase the number of plastic sheetings to 40: 171 | ```shell 172 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=TTKQ8NJZ&quantity=20' | jq 173 | ``` 174 | 175 | ### Producing an Error Message 176 | 177 | Trying to add another 20 plastic sheetings will result in error message saying that there are only 55 items in stock: 178 | 179 | ```shell 180 | curl -X POST 'localhost:8080/carts/61157/line-items?productId=TTKQ8NJZ&quantity=20' | jq 181 | ``` 182 | 183 | This is how the error response looks like: 184 | ```json 185 | { 186 | "httpStatus": 400, 187 | "errorMessage": "Only 55 items in stock" 188 | } 189 | ``` 190 | 191 | ## Emptying the Cart 192 | 193 | To empty the cart, send a DELETE command to its URL: 194 | 195 | ```shell 196 | curl -X DELETE localhost:8080/carts/61157 197 | ``` 198 | 199 | To verify it's empty: 200 | ```shell 201 | curl localhost:8080/carts/61157 | jq 202 | ``` 203 | 204 | You'll see an empty cart again. 205 | 206 | ##
Additional Resources 207 | 208 | ###
Java Versions PDF Cheat Sheet 209 | 210 | **Stay up-to-date** with the latest Java features with [this PDF Cheat Sheet](https://www.happycoders.eu/java-versions/)! 211 | 212 | [Java Versions PDF Cheat Sheet Mockup](https://www.happycoders.eu/java-versions/) 213 | 214 | * Avoid lengthy research with this **concise overview of all Java versions up to Java 23**. 215 | * **Discover the innovative features** of each new Java version, summarized on a single page. 216 | * **Impress your team** with your up-to-date knowledge of the latest Java version. 217 | 218 | 👉 [Download the Java Versions PDF](https://www.happycoders.eu/java-versions/)
219 | 220 | _(Hier geht's zur deutschen Version → [Java-Versionen PDF](https://www.happycoders.eu/de/java-versionen/))_ 221 | 222 | 223 | ###
The Big O Cheat Sheet 224 | 225 | With this [1-page PDF cheat sheet](https://www.happycoders.eu/big-o-cheat-sheet/), you'll always have the **7 most important complexity classes** at a glance. 226 | 227 | [Big O PDF Cheat Sheet Mockup](https://www.happycoders.eu/big-o-cheat-sheet/) 228 | 229 | * **Always choose the most efficient data structures** and thus increase the performance of your applications. 230 | * **Be prepared for technical interviews** and confidently present your algorithm knowledge. 231 | * **Become a sought-after problem solver** and be known for systematically tackling complex problems. 232 | 233 | 👉 [Download the Big O Cheat Sheet](https://www.happycoders.eu/big-o-cheat-sheet/)
234 | 235 | _(Hier geht's zur deutschen Version → [O-Notation Cheat Sheet](https://www.happycoders.eu/de/o-notation-cheat-sheet/))_ 236 | 237 | 238 | ###
HappyCoders Newsletter 239 | 👉 Want to level up your Java skills? 240 | Sign up for the [HappyCoders newsletter](http://www.happycoders.eu/newsletter/) and get regular tips on programming, algorithms, and data structures! 241 | 242 | _(Hier geht's zur deutschen Version → [HappyCoders-Newsletter deutsch](https://www.happycoders.eu/de/newsletter/))_ 243 | 244 | 245 | ###
🇩🇪 An alle Java-Programmierer, die durch fundierte Kenntnisse über Datenstrukturen besseren Code schreiben wollen 246 | 247 | Trage dich jetzt auf die [Warteliste](https://www.happycoders.eu/de/mastering-data-structures-warteliste/) von „Mastering Data Structures in Java“ ein, und erhalte das beste Angebot! 248 | 249 | [Mastering Data Structures Mockup](https://www.happycoders.eu/de/mastering-data-structures-warteliste/) 250 | 251 | 👉 [Zur Warteliste](https://www.happycoders.eu/de/mastering-data-structures-warteliste/) 252 | -------------------------------------------------------------------------------- /adapter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | eu.happycoders.shop 9 | parent 10 | 1.0-SNAPSHOT 11 | 12 | 13 | adapter 14 | 15 | 16 | 17 | 18 | 19 | eu.happycoders.shop 20 | application 21 | ${project.version} 22 | 23 | 24 | 25 | 26 | jakarta.persistence 27 | jakarta.persistence-api 28 | 29 | 30 | jakarta.ws.rs 31 | jakarta.ws.rs-api 32 | 33 | 34 | 35 | 36 | mysql 37 | mysql-connector-java 38 | test 39 | 40 | 41 | io.rest-assured 42 | rest-assured 43 | test 44 | 45 | 46 | org.jboss.resteasy 47 | resteasy-jackson2-provider 48 | test 49 | 50 | 51 | org.glassfish 52 | jakarta.el 53 | test 54 | 55 | 56 | org.hibernate.orm 57 | hibernate-core 58 | test 59 | 60 | 61 | org.hibernate.validator 62 | hibernate-validator 63 | test 64 | 65 | 66 | org.jboss.resteasy 67 | resteasy-undertow 68 | test 69 | 70 | 71 | org.testcontainers 72 | mysql 73 | test 74 | 75 | 76 | 77 | 78 | eu.happycoders.shop 79 | model 80 | ${project.version} 81 | tests 82 | test-jar 83 | test 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | org.apache.maven.plugins 92 | maven-jar-plugin 93 | 94 | 95 | 96 | test-jar 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/cart/AddToCartController.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.ControllerCommons.clientErrorException; 4 | import static eu.happycoders.shop.adapter.in.rest.common.CustomerIdParser.parseCustomerId; 5 | import static eu.happycoders.shop.adapter.in.rest.common.ProductIdParser.parseProductId; 6 | 7 | import eu.happycoders.shop.application.port.in.cart.AddToCartUseCase; 8 | import eu.happycoders.shop.application.port.in.cart.ProductNotFoundException; 9 | import eu.happycoders.shop.model.cart.Cart; 10 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 11 | import eu.happycoders.shop.model.customer.CustomerId; 12 | import eu.happycoders.shop.model.product.ProductId; 13 | import jakarta.ws.rs.POST; 14 | import jakarta.ws.rs.Path; 15 | import jakarta.ws.rs.PathParam; 16 | import jakarta.ws.rs.Produces; 17 | import jakarta.ws.rs.QueryParam; 18 | import jakarta.ws.rs.core.MediaType; 19 | import jakarta.ws.rs.core.Response; 20 | 21 | /** 22 | * REST controller for all shopping cart use cases. 23 | * 24 | * @author Sven Woltmann 25 | */ 26 | @Path("/carts") 27 | @Produces(MediaType.APPLICATION_JSON) 28 | public class AddToCartController { 29 | 30 | private final AddToCartUseCase addToCartUseCase; 31 | 32 | public AddToCartController(AddToCartUseCase addToCartUseCase) { 33 | this.addToCartUseCase = addToCartUseCase; 34 | } 35 | 36 | @POST 37 | @Path("/{customerId}/line-items") 38 | public CartWebModel addLineItem( 39 | @PathParam("customerId") String customerIdString, 40 | @QueryParam("productId") String productIdString, 41 | @QueryParam("quantity") int quantity) { 42 | CustomerId customerId = parseCustomerId(customerIdString); 43 | ProductId productId = parseProductId(productIdString); 44 | 45 | try { 46 | Cart cart = addToCartUseCase.addToCart(customerId, productId, quantity); 47 | return CartWebModel.fromDomainModel(cart); 48 | } catch (ProductNotFoundException e) { 49 | throw clientErrorException( 50 | Response.Status.BAD_REQUEST, "The requested product does not exist"); 51 | } catch (NotEnoughItemsInStockException e) { 52 | throw clientErrorException( 53 | Response.Status.BAD_REQUEST, "Only %d items in stock".formatted(e.itemsInStock())); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/cart/CartLineItemWebModel.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import eu.happycoders.shop.model.cart.CartLineItem; 4 | import eu.happycoders.shop.model.money.Money; 5 | import eu.happycoders.shop.model.product.Product; 6 | 7 | /** 8 | * Model class for returning a shopping cart line item via REST API. 9 | * 10 | * @author Sven Woltmann 11 | */ 12 | public record CartLineItemWebModel( 13 | String productId, String productName, Money price, int quantity) { 14 | 15 | public static CartLineItemWebModel fromDomainModel(CartLineItem lineItem) { 16 | Product product = lineItem.product(); 17 | return new CartLineItemWebModel( 18 | product.id().value(), product.name(), product.price(), lineItem.quantity()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/cart/CartWebModel.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import eu.happycoders.shop.model.cart.Cart; 4 | import eu.happycoders.shop.model.money.Money; 5 | import java.util.List; 6 | 7 | /** 8 | * Model class for returning a shopping cart via REST API. 9 | * 10 | * @author Sven Woltmann 11 | */ 12 | public record CartWebModel( 13 | List lineItems, int numberOfItems, Money subTotal) { 14 | 15 | static CartWebModel fromDomainModel(Cart cart) { 16 | return new CartWebModel( 17 | cart.lineItems().stream().map(CartLineItemWebModel::fromDomainModel).toList(), 18 | cart.numberOfItems(), 19 | cart.subTotal()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/cart/EmptyCartController.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.CustomerIdParser.parseCustomerId; 4 | 5 | import eu.happycoders.shop.application.port.in.cart.EmptyCartUseCase; 6 | import eu.happycoders.shop.model.customer.CustomerId; 7 | import jakarta.ws.rs.DELETE; 8 | import jakarta.ws.rs.Path; 9 | import jakarta.ws.rs.PathParam; 10 | import jakarta.ws.rs.Produces; 11 | import jakarta.ws.rs.core.MediaType; 12 | 13 | /** 14 | * REST controller for all shopping cart use cases. 15 | * 16 | * @author Sven Woltmann 17 | */ 18 | @Path("/carts") 19 | @Produces(MediaType.APPLICATION_JSON) 20 | public class EmptyCartController { 21 | 22 | private final EmptyCartUseCase emptyCartUseCase; 23 | 24 | public EmptyCartController(EmptyCartUseCase emptyCartUseCase) { 25 | this.emptyCartUseCase = emptyCartUseCase; 26 | } 27 | 28 | @DELETE 29 | @Path("/{customerId}") 30 | public void deleteCart(@PathParam("customerId") String customerIdString) { 31 | CustomerId customerId = parseCustomerId(customerIdString); 32 | emptyCartUseCase.emptyCart(customerId); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/cart/GetCartController.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.CustomerIdParser.parseCustomerId; 4 | 5 | import eu.happycoders.shop.application.port.in.cart.GetCartUseCase; 6 | import eu.happycoders.shop.model.cart.Cart; 7 | import eu.happycoders.shop.model.customer.CustomerId; 8 | import jakarta.ws.rs.GET; 9 | import jakarta.ws.rs.Path; 10 | import jakarta.ws.rs.PathParam; 11 | import jakarta.ws.rs.Produces; 12 | import jakarta.ws.rs.core.MediaType; 13 | 14 | /** 15 | * REST controller for all shopping cart use cases. 16 | * 17 | * @author Sven Woltmann 18 | */ 19 | @Path("/carts") 20 | @Produces(MediaType.APPLICATION_JSON) 21 | public class GetCartController { 22 | 23 | private final GetCartUseCase getCartUseCase; 24 | 25 | public GetCartController(GetCartUseCase getCartUseCase) { 26 | this.getCartUseCase = getCartUseCase; 27 | } 28 | 29 | @GET 30 | @Path("/{customerId}") 31 | public CartWebModel getCart(@PathParam("customerId") String customerIdString) { 32 | CustomerId customerId = parseCustomerId(customerIdString); 33 | Cart cart = getCartUseCase.getCart(customerId); 34 | return CartWebModel.fromDomainModel(cart); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/common/ControllerCommons.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.common; 2 | 3 | import jakarta.ws.rs.ClientErrorException; 4 | import jakarta.ws.rs.core.Response; 5 | 6 | /** 7 | * Common functionality for all REST controllers. 8 | * 9 | * @author Sven Woltmann 10 | */ 11 | public final class ControllerCommons { 12 | 13 | private ControllerCommons() {} 14 | 15 | public static ClientErrorException clientErrorException(Response.Status status, String message) { 16 | return new ClientErrorException(errorResponse(status, message)); 17 | } 18 | 19 | public static Response errorResponse(Response.Status status, String message) { 20 | ErrorEntity errorEntity = new ErrorEntity(status.getStatusCode(), message); 21 | return Response.status(status).entity(errorEntity).build(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/common/CustomerIdParser.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.common; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.ControllerCommons.clientErrorException; 4 | 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import jakarta.ws.rs.core.Response; 7 | 8 | /** 9 | * A parser for customer IDs, throwing a {@link jakarta.ws.rs.ClientErrorException} for invalid 10 | * customer IDs. 11 | * 12 | * @author Sven Woltmann 13 | */ 14 | public final class CustomerIdParser { 15 | 16 | private CustomerIdParser() {} 17 | 18 | public static CustomerId parseCustomerId(String string) { 19 | try { 20 | return new CustomerId(Integer.parseInt(string)); 21 | } catch (IllegalArgumentException e) { 22 | throw clientErrorException(Response.Status.BAD_REQUEST, "Invalid 'customerId'"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/common/ErrorEntity.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.common; 2 | 3 | /** 4 | * An error entity with a status and message returned via REST API in case of an error. 5 | * 6 | * @author Sven Woltmann 7 | */ 8 | public record ErrorEntity(int httpStatus, String errorMessage) {} 9 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/common/ProductIdParser.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.common; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.ControllerCommons.clientErrorException; 4 | 5 | import eu.happycoders.shop.model.product.ProductId; 6 | import jakarta.ws.rs.core.Response; 7 | 8 | /** 9 | * A parser for product IDs, throwing a {@link jakarta.ws.rs.ClientErrorException} for invalid 10 | * product IDs. 11 | * 12 | * @author Sven Woltmann 13 | */ 14 | public final class ProductIdParser { 15 | 16 | private ProductIdParser() {} 17 | 18 | public static ProductId parseProductId(String string) { 19 | if (string == null) { 20 | throw clientErrorException(Response.Status.BAD_REQUEST, "Missing 'productId'"); 21 | } 22 | 23 | try { 24 | return new ProductId(string); 25 | } catch (IllegalArgumentException e) { 26 | throw clientErrorException(Response.Status.BAD_REQUEST, "Invalid 'productId'"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/product/FindProductsController.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.product; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.common.ControllerCommons.clientErrorException; 4 | 5 | import eu.happycoders.shop.application.port.in.product.FindProductsUseCase; 6 | import eu.happycoders.shop.model.product.Product; 7 | import jakarta.ws.rs.GET; 8 | import jakarta.ws.rs.Path; 9 | import jakarta.ws.rs.Produces; 10 | import jakarta.ws.rs.QueryParam; 11 | import jakarta.ws.rs.core.MediaType; 12 | import jakarta.ws.rs.core.Response; 13 | import java.util.List; 14 | 15 | /** 16 | * REST controller for all product use cases. 17 | * 18 | * @author Sven Woltmann 19 | */ 20 | @Path("/products") 21 | @Produces(MediaType.APPLICATION_JSON) 22 | public class FindProductsController { 23 | 24 | private final FindProductsUseCase findProductsUseCase; 25 | 26 | public FindProductsController(FindProductsUseCase findProductsUseCase) { 27 | this.findProductsUseCase = findProductsUseCase; 28 | } 29 | 30 | @GET 31 | public List findProducts(@QueryParam("query") String query) { 32 | if (query == null) { 33 | throw clientErrorException(Response.Status.BAD_REQUEST, "Missing 'query'"); 34 | } 35 | 36 | List products; 37 | 38 | try { 39 | products = findProductsUseCase.findByNameOrDescription(query); 40 | } catch (IllegalArgumentException e) { 41 | throw clientErrorException(Response.Status.BAD_REQUEST, "Invalid 'query'"); 42 | } 43 | 44 | return products.stream().map(ProductInListWebModel::fromDomainModel).toList(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/in/rest/product/ProductInListWebModel.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.product; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | import eu.happycoders.shop.model.product.Product; 5 | 6 | /** 7 | * Model class for returning a product (in a list ... that's without description) via REST API. 8 | * 9 | * @author Sven Woltmann 10 | */ 11 | public record ProductInListWebModel(String id, String name, Money price, int itemsInStock) { 12 | 13 | public static ProductInListWebModel fromDomainModel(Product product) { 14 | return new ProductInListWebModel( 15 | product.id().value(), product.name(), product.price(), product.itemsInStock()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/DemoProducts.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | import eu.happycoders.shop.model.product.Product; 5 | import eu.happycoders.shop.model.product.ProductId; 6 | import java.util.Currency; 7 | import java.util.List; 8 | 9 | /** 10 | * Demo products that are automatically stored in the product database (I tried to keep this demo 11 | * application as simple as possible, so it doesn't have an endpoint to add a product). 12 | * 13 | * @author Sven Woltmann 14 | */ 15 | public final class DemoProducts { 16 | 17 | private static final Currency EUR = Currency.getInstance("EUR"); 18 | 19 | public static final Product PLASTIC_SHEETING = 20 | new Product( 21 | new ProductId("TTKQ8NJZ"), 22 | "Plastic Sheeting", 23 | "Clear plastic sheeting, tear-resistant, tough, and durable", 24 | Money.of(EUR, 42, 99), 25 | 55); 26 | 27 | public static final Product COMPUTER_MONITOR = 28 | new Product( 29 | new ProductId("K3SR7PBX"), 30 | "27-Inch Curved Computer Monitor", 31 | "Enjoy big, bold and stunning panoramic views", 32 | Money.of(EUR, 159, 99), 33 | 24_081); 34 | public static final Product MONITOR_DESK_MOUNT = 35 | new Product( 36 | new ProductId("Q3W43CNC"), 37 | "Dual Monitor Desk Mount", 38 | "Ultra wide and longer arm fits most monitors", 39 | Money.of(EUR, 119, 90), 40 | 1_079); 41 | 42 | public static final Product LED_LIGHTS = 43 | new Product( 44 | new ProductId("WM3BPG3E"), 45 | "50ft Led Lights", 46 | "Enough lights to decorate an entire room", 47 | Money.of(EUR, 11, 69), 48 | 3_299); 49 | 50 | public static final List DEMO_PRODUCTS = 51 | List.of(PLASTIC_SHEETING, COMPUTER_MONITOR, MONITOR_DESK_MOUNT, LED_LIGHTS); 52 | 53 | private DemoProducts() {} 54 | } 55 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/inmemory/InMemoryCartRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.inmemory; 2 | 3 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 4 | import eu.happycoders.shop.model.cart.Cart; 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import java.util.Map; 7 | import java.util.Optional; 8 | import java.util.concurrent.ConcurrentHashMap; 9 | 10 | /** 11 | * Persistence adapter: Stores carts in memory. 12 | * 13 | * @author Sven Woltmann 14 | */ 15 | public class InMemoryCartRepository implements CartRepository { 16 | 17 | private final Map carts = new ConcurrentHashMap<>(); 18 | 19 | @Override 20 | public void save(Cart cart) { 21 | carts.put(cart.id(), cart); 22 | } 23 | 24 | @Override 25 | public Optional findByCustomerId(CustomerId customerId) { 26 | return Optional.ofNullable(carts.get(customerId)); 27 | } 28 | 29 | @Override 30 | public void deleteByCustomerId(CustomerId customerId) { 31 | carts.remove(customerId); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/inmemory/InMemoryProductRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.inmemory; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.DemoProducts; 4 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 5 | import eu.happycoders.shop.model.product.Product; 6 | import eu.happycoders.shop.model.product.ProductId; 7 | import java.util.List; 8 | import java.util.Locale; 9 | import java.util.Map; 10 | import java.util.Optional; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | 13 | /** 14 | * Persistence adapter: Stores products in memory. 15 | * 16 | * @author Sven Woltmann 17 | */ 18 | public class InMemoryProductRepository implements ProductRepository { 19 | 20 | private final Map products = new ConcurrentHashMap<>(); 21 | 22 | public InMemoryProductRepository() { 23 | createDemoProducts(); 24 | } 25 | 26 | private void createDemoProducts() { 27 | DemoProducts.DEMO_PRODUCTS.forEach(this::save); 28 | } 29 | 30 | @Override 31 | public void save(Product product) { 32 | products.put(product.id(), product); 33 | } 34 | 35 | @Override 36 | public Optional findById(ProductId productId) { 37 | return Optional.ofNullable(products.get(productId)); 38 | } 39 | 40 | @Override 41 | public List findByNameOrDescription(String query) { 42 | String queryLowerCase = query.toLowerCase(Locale.ROOT); 43 | return products.values().stream() 44 | .filter(product -> matchesQuery(product, queryLowerCase)) 45 | .toList(); 46 | } 47 | 48 | private boolean matchesQuery(Product product, String query) { 49 | return product.name().toLowerCase(Locale.ROOT).contains(query) 50 | || product.description().toLowerCase(Locale.ROOT).contains(query); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/CartJpaEntity.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import jakarta.persistence.CascadeType; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.OneToMany; 7 | import jakarta.persistence.Table; 8 | import java.util.List; 9 | import lombok.Getter; 10 | import lombok.Setter; 11 | 12 | /** 13 | * JPA entity class for a shopping cart. 14 | * 15 | * @author Sven Woltmann 16 | */ 17 | @Entity 18 | @Table(name = "Cart") 19 | @Getter 20 | @Setter 21 | public class CartJpaEntity { 22 | 23 | @Id private int customerId; 24 | 25 | @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true) 26 | private List lineItems; 27 | } 28 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/CartLineItemJpaEntity.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.ManyToOne; 7 | import jakarta.persistence.Table; 8 | import lombok.Getter; 9 | import lombok.Setter; 10 | 11 | /** 12 | * JPA entity class for a shopping cart line item. 13 | * 14 | * @author Sven Woltmann 15 | */ 16 | @Entity 17 | @Table(name = "CartLineItem") 18 | @Getter 19 | @Setter 20 | public class CartLineItemJpaEntity { 21 | 22 | @Id @GeneratedValue private Integer id; 23 | 24 | @ManyToOne private CartJpaEntity cart; 25 | 26 | @ManyToOne private ProductJpaEntity product; 27 | 28 | private int quantity; 29 | } 30 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/CartMapper.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.model.cart.Cart; 4 | import eu.happycoders.shop.model.cart.CartLineItem; 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import java.util.Optional; 7 | 8 | /** 9 | * Maps model carts and line items to JPA carts and line items - and vice versa. 10 | * 11 | * @author Sven Woltmann 12 | */ 13 | final class CartMapper { 14 | 15 | private CartMapper() {} 16 | 17 | static CartJpaEntity toJpaEntity(Cart cart) { 18 | CartJpaEntity cartJpaEntity = new CartJpaEntity(); 19 | cartJpaEntity.setCustomerId(cart.id().value()); 20 | 21 | cartJpaEntity.setLineItems( 22 | cart.lineItems().stream().map(lineItem -> toJpaEntity(cartJpaEntity, lineItem)).toList()); 23 | 24 | return cartJpaEntity; 25 | } 26 | 27 | static CartLineItemJpaEntity toJpaEntity(CartJpaEntity cartJpaEntity, CartLineItem lineItem) { 28 | ProductJpaEntity productJpaEntity = new ProductJpaEntity(); 29 | productJpaEntity.setId(lineItem.product().id().value()); 30 | 31 | CartLineItemJpaEntity entity = new CartLineItemJpaEntity(); 32 | entity.setCart(cartJpaEntity); 33 | entity.setProduct(productJpaEntity); 34 | entity.setQuantity(lineItem.quantity()); 35 | 36 | return entity; 37 | } 38 | 39 | static Optional toModelEntityOptional(CartJpaEntity cartJpaEntity) { 40 | if (cartJpaEntity == null) { 41 | return Optional.empty(); 42 | } 43 | 44 | CustomerId customerId = new CustomerId(cartJpaEntity.getCustomerId()); 45 | Cart cart = new Cart(customerId); 46 | 47 | for (CartLineItemJpaEntity lineItemJpaEntity : cartJpaEntity.getLineItems()) { 48 | cart.putProductIgnoringNotEnoughItemsInStock( 49 | ProductMapper.toModelEntity(lineItemJpaEntity.getProduct()), 50 | lineItemJpaEntity.getQuantity()); 51 | } 52 | 53 | return Optional.of(cart); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/EntityManagerFactoryFactory.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import jakarta.persistence.EntityManagerFactory; 4 | import jakarta.persistence.Persistence; 5 | import java.util.Map; 6 | 7 | /** 8 | * Factory for an EntityManagerFactory for connecting to a MySQL database. 9 | * 10 | * @author Sven Woltmann 11 | */ 12 | public final class EntityManagerFactoryFactory { 13 | 14 | private EntityManagerFactoryFactory() {} 15 | 16 | public static EntityManagerFactory createMySqlEntityManagerFactory( 17 | String jdbcUrl, String user, String password) { 18 | return Persistence.createEntityManagerFactory( 19 | "eu.happycoders.shop.adapter.out.persistence.jpa", 20 | Map.of( 21 | "hibernate.dialect", 22 | "org.hibernate.dialect.MySQLDialect", 23 | "hibernate.hbm2ddl.auto", 24 | "update", 25 | "jakarta.persistence.jdbc.driver", 26 | "com.mysql.jdbc.Driver", 27 | "jakarta.persistence.jdbc.url", 28 | jdbcUrl, 29 | "jakarta.persistence.jdbc.user", 30 | user, 31 | "jakarta.persistence.jdbc.password", 32 | password)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/JpaCartRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 4 | import eu.happycoders.shop.model.cart.Cart; 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import jakarta.persistence.EntityManager; 7 | import jakarta.persistence.EntityManagerFactory; 8 | import java.util.Optional; 9 | 10 | /** 11 | * Persistence adapter: Stores carts via JPA in a database. 12 | * 13 | * @author Sven Woltmann 14 | */ 15 | public class JpaCartRepository implements CartRepository { 16 | 17 | private final EntityManagerFactory entityManagerFactory; 18 | 19 | public JpaCartRepository(EntityManagerFactory entityManagerFactory) { 20 | this.entityManagerFactory = entityManagerFactory; 21 | } 22 | 23 | @Override 24 | public void save(Cart cart) { 25 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 26 | entityManager.getTransaction().begin(); 27 | entityManager.merge(CartMapper.toJpaEntity(cart)); 28 | entityManager.getTransaction().commit(); 29 | } 30 | } 31 | 32 | @Override 33 | public Optional findByCustomerId(CustomerId customerId) { 34 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 35 | CartJpaEntity cartJpaEntity = entityManager.find(CartJpaEntity.class, customerId.value()); 36 | return CartMapper.toModelEntityOptional(cartJpaEntity); 37 | } 38 | } 39 | 40 | @Override 41 | public void deleteByCustomerId(CustomerId customerId) { 42 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 43 | entityManager.getTransaction().begin(); 44 | 45 | CartJpaEntity cartJpaEntity = entityManager.find(CartJpaEntity.class, customerId.value()); 46 | 47 | if (cartJpaEntity != null) { 48 | entityManager.remove(cartJpaEntity); 49 | } 50 | 51 | entityManager.getTransaction().commit(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/JpaProductRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.DemoProducts; 4 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 5 | import eu.happycoders.shop.model.product.Product; 6 | import eu.happycoders.shop.model.product.ProductId; 7 | import jakarta.persistence.EntityManager; 8 | import jakarta.persistence.EntityManagerFactory; 9 | import jakarta.persistence.TypedQuery; 10 | import java.util.List; 11 | import java.util.Optional; 12 | 13 | /** 14 | * Persistence adapter: Stores products via JPA in a database. 15 | * 16 | * @author Sven Woltmann 17 | */ 18 | public class JpaProductRepository implements ProductRepository { 19 | 20 | private final EntityManagerFactory entityManagerFactory; 21 | 22 | public JpaProductRepository(EntityManagerFactory entityManagerFactory) { 23 | this.entityManagerFactory = entityManagerFactory; 24 | createDemoProducts(); 25 | } 26 | 27 | private void createDemoProducts() { 28 | DemoProducts.DEMO_PRODUCTS.forEach(this::save); 29 | } 30 | 31 | @Override 32 | public void save(Product product) { 33 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 34 | entityManager.getTransaction().begin(); 35 | entityManager.merge(ProductMapper.toJpaEntity(product)); 36 | entityManager.getTransaction().commit(); 37 | } 38 | } 39 | 40 | @Override 41 | public Optional findById(ProductId productId) { 42 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 43 | ProductJpaEntity jpaEntity = entityManager.find(ProductJpaEntity.class, productId.value()); 44 | return ProductMapper.toModelEntityOptional(jpaEntity); 45 | } 46 | } 47 | 48 | @Override 49 | public List findByNameOrDescription(String queryString) { 50 | try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { 51 | TypedQuery query = 52 | entityManager 53 | .createQuery( 54 | "from ProductJpaEntity where name like :query or description like :query", 55 | ProductJpaEntity.class) 56 | .setParameter("query", "%" + queryString + "%"); 57 | 58 | List entities = query.getResultList(); 59 | 60 | return ProductMapper.toModelEntities(entities); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/ProductJpaEntity.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import jakarta.persistence.Column; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.Table; 7 | import java.math.BigDecimal; 8 | import lombok.Getter; 9 | import lombok.Setter; 10 | 11 | /** 12 | * JPA entity class for a product. 13 | * 14 | * @author Sven Woltmann 15 | */ 16 | @Entity 17 | @Table(name = "Product") 18 | @Getter 19 | @Setter 20 | public class ProductJpaEntity { 21 | 22 | @Id private String id; 23 | 24 | @Column(nullable = false) 25 | private String name; 26 | 27 | @Column(nullable = false) 28 | private String description; 29 | 30 | @Column(nullable = false) 31 | private String priceCurrency; 32 | 33 | @Column(nullable = false) 34 | private BigDecimal priceAmount; 35 | 36 | private int itemsInStock; 37 | } 38 | -------------------------------------------------------------------------------- /adapter/src/main/java/eu/happycoders/shop/adapter/out/persistence/jpa/ProductMapper.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | import eu.happycoders.shop.model.product.Product; 5 | import eu.happycoders.shop.model.product.ProductId; 6 | import java.util.Currency; 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | /** 11 | * Maps a model product to a JPA product and vice versa. 12 | * 13 | * @author Sven Woltmann 14 | */ 15 | final class ProductMapper { 16 | 17 | private ProductMapper() {} 18 | 19 | static ProductJpaEntity toJpaEntity(Product product) { 20 | ProductJpaEntity jpaEntity = new ProductJpaEntity(); 21 | 22 | jpaEntity.setId(product.id().value()); 23 | jpaEntity.setName(product.name()); 24 | jpaEntity.setDescription(product.description()); 25 | jpaEntity.setPriceCurrency(product.price().currency().getCurrencyCode()); 26 | jpaEntity.setPriceAmount(product.price().amount()); 27 | jpaEntity.setItemsInStock(product.itemsInStock()); 28 | 29 | return jpaEntity; 30 | } 31 | 32 | static Optional toModelEntityOptional(ProductJpaEntity jpaEntity) { 33 | return Optional.ofNullable(jpaEntity).map(ProductMapper::toModelEntity); 34 | } 35 | 36 | static Product toModelEntity(ProductJpaEntity jpaEntity) { 37 | return new Product( 38 | new ProductId(jpaEntity.getId()), 39 | jpaEntity.getName(), 40 | jpaEntity.getDescription(), 41 | new Money(Currency.getInstance(jpaEntity.getPriceCurrency()), jpaEntity.getPriceAmount()), 42 | jpaEntity.getItemsInStock()); 43 | } 44 | 45 | static List toModelEntities(List jpaEntities) { 46 | return jpaEntities.stream().map(ProductMapper::toModelEntity).toList(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /adapter/src/main/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | eu.happycoders.shop.adapter.out.persistence.jpa.CartJpaEntity 4 | eu.happycoders.shop.adapter.out.persistence.jpa.CartLineItemJpaEntity 5 | eu.happycoders.shop.adapter.out.persistence.jpa.ProductJpaEntity 6 | true 7 | 8 | 9 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/in/rest/HttpTestCommons.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import io.restassured.path.json.JsonPath; 6 | import io.restassured.response.Response; 7 | 8 | public final class HttpTestCommons { 9 | 10 | // So the tests can run when the application runs on port 8080: 11 | public static final int TEST_PORT = 8082; 12 | 13 | private HttpTestCommons() {} 14 | 15 | public static void assertThatResponseIsError( 16 | Response response, 17 | jakarta.ws.rs.core.Response.Status expectedStatus, 18 | String expectedErrorMessage) { 19 | assertThat(response.getStatusCode()).isEqualTo(expectedStatus.getStatusCode()); 20 | 21 | JsonPath json = response.jsonPath(); 22 | 23 | assertThat(json.getInt("httpStatus")).isEqualTo(expectedStatus.getStatusCode()); 24 | assertThat(json.getString("errorMessage")).isEqualTo(expectedErrorMessage); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/in/rest/cart/CartsControllerAssertions.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import static jakarta.ws.rs.core.Response.Status.OK; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | 6 | import eu.happycoders.shop.model.cart.Cart; 7 | import eu.happycoders.shop.model.cart.CartLineItem; 8 | import io.restassured.path.json.JsonPath; 9 | import io.restassured.response.Response; 10 | 11 | public final class CartsControllerAssertions { 12 | 13 | private CartsControllerAssertions() {} 14 | 15 | public static void assertThatResponseIsCart(Response response, Cart cart) { 16 | assertThat(response.statusCode()).isEqualTo(OK.getStatusCode()); 17 | 18 | JsonPath json = response.jsonPath(); 19 | 20 | for (int i = 0; i < cart.lineItems().size(); i++) { 21 | CartLineItem lineItem = cart.lineItems().get(i); 22 | 23 | String lineItemPrefix = "lineItems[%d].".formatted(i); 24 | 25 | assertThat(json.getString(lineItemPrefix + "productId")) 26 | .isEqualTo(lineItem.product().id().value()); 27 | assertThat(json.getString(lineItemPrefix + "productName")) 28 | .isEqualTo(lineItem.product().name()); 29 | assertThat(json.getString(lineItemPrefix + "price.currency")) 30 | .isEqualTo(lineItem.product().price().currency().getCurrencyCode()); 31 | assertThat(json.getDouble(lineItemPrefix + "price.amount")) 32 | .isEqualTo(lineItem.product().price().amount().doubleValue()); 33 | assertThat(json.getInt(lineItemPrefix + "quantity")).isEqualTo(lineItem.quantity()); 34 | } 35 | 36 | assertThat(json.getInt("numberOfItems")).isEqualTo(cart.numberOfItems()); 37 | 38 | if (cart.subTotal() != null) { 39 | assertThat(json.getString("subTotal.currency")) 40 | .isEqualTo(cart.subTotal().currency().getCurrencyCode()); 41 | assertThat(json.getDouble("subTotal.amount")) 42 | .isEqualTo(cart.subTotal().amount().doubleValue()); 43 | } else { 44 | assertThat(json.getString("subTotal")).isNull(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/in/rest/cart/CartsControllerTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.cart; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.TEST_PORT; 4 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.assertThatResponseIsError; 5 | import static eu.happycoders.shop.adapter.in.rest.cart.CartsControllerAssertions.assertThatResponseIsCart; 6 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 7 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 8 | import static io.restassured.RestAssured.given; 9 | import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST; 10 | import static jakarta.ws.rs.core.Response.Status.NO_CONTENT; 11 | import static org.mockito.Mockito.mock; 12 | import static org.mockito.Mockito.verify; 13 | import static org.mockito.Mockito.when; 14 | 15 | import eu.happycoders.shop.application.port.in.cart.AddToCartUseCase; 16 | import eu.happycoders.shop.application.port.in.cart.EmptyCartUseCase; 17 | import eu.happycoders.shop.application.port.in.cart.GetCartUseCase; 18 | import eu.happycoders.shop.application.port.in.cart.ProductNotFoundException; 19 | import eu.happycoders.shop.model.cart.Cart; 20 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 21 | import eu.happycoders.shop.model.customer.CustomerId; 22 | import eu.happycoders.shop.model.product.Product; 23 | import eu.happycoders.shop.model.product.ProductId; 24 | import io.restassured.response.Response; 25 | import jakarta.ws.rs.core.Application; 26 | import java.util.Set; 27 | import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer; 28 | import org.junit.jupiter.api.AfterAll; 29 | import org.junit.jupiter.api.BeforeAll; 30 | import org.junit.jupiter.api.BeforeEach; 31 | import org.junit.jupiter.api.Test; 32 | import org.mockito.Mockito; 33 | 34 | class CartsControllerTest { 35 | 36 | private static final CustomerId TEST_CUSTOMER_ID = new CustomerId(61157); 37 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 38 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(25, 99)); 39 | 40 | private static final AddToCartUseCase addToCartUseCase = mock(AddToCartUseCase.class); 41 | private static final GetCartUseCase getCartUseCase = mock(GetCartUseCase.class); 42 | private static final EmptyCartUseCase emptyCartUseCase = mock(EmptyCartUseCase.class); 43 | 44 | private static UndertowJaxrsServer server; 45 | 46 | @BeforeAll 47 | static void init() { 48 | server = 49 | new UndertowJaxrsServer() 50 | .setPort(TEST_PORT) 51 | .start() 52 | .deploy( 53 | new Application() { 54 | @Override 55 | public Set getSingletons() { 56 | return Set.of( 57 | new AddToCartController(addToCartUseCase), 58 | new GetCartController(getCartUseCase), 59 | new EmptyCartController(emptyCartUseCase)); 60 | } 61 | }); 62 | } 63 | 64 | @AfterAll 65 | static void stop() { 66 | server.stop(); 67 | } 68 | 69 | @BeforeEach 70 | void resetMocks() { 71 | Mockito.reset(addToCartUseCase, getCartUseCase, emptyCartUseCase); 72 | } 73 | 74 | @Test 75 | void givenASyntacticallyInvalidCustomerId_getCart_returnsAnError() { 76 | String customerId = "foo"; 77 | 78 | Response response = 79 | given().port(TEST_PORT).get("/carts/" + customerId).then().extract().response(); 80 | 81 | assertThatResponseIsError(response, BAD_REQUEST, "Invalid 'customerId'"); 82 | } 83 | 84 | @Test 85 | void givenAValidCustomerIdAndACart_getCart_requestsCartFromUseCaseAndReturnsIt() 86 | throws NotEnoughItemsInStockException { 87 | CustomerId customerId = TEST_CUSTOMER_ID; 88 | 89 | Cart cart = new Cart(customerId); 90 | cart.addProduct(TEST_PRODUCT_1, 3); 91 | cart.addProduct(TEST_PRODUCT_2, 5); 92 | 93 | when(getCartUseCase.getCart(customerId)).thenReturn(cart); 94 | 95 | Response response = 96 | given().port(TEST_PORT).get("/carts/" + customerId.value()).then().extract().response(); 97 | 98 | assertThatResponseIsCart(response, cart); 99 | } 100 | 101 | @Test 102 | void givenSomeTestData_addLineItem_invokesAddToCartUseCaseAndReturnsUpdatedCart() 103 | throws NotEnoughItemsInStockException, ProductNotFoundException { 104 | CustomerId customerId = TEST_CUSTOMER_ID; 105 | ProductId productId = TEST_PRODUCT_1.id(); 106 | int quantity = 5; 107 | 108 | Cart cart = new Cart(customerId); 109 | cart.addProduct(TEST_PRODUCT_1, quantity); 110 | 111 | when(addToCartUseCase.addToCart(customerId, productId, quantity)).thenReturn(cart); 112 | 113 | Response response = 114 | given() 115 | .port(TEST_PORT) 116 | .queryParam("productId", productId.value()) 117 | .queryParam("quantity", quantity) 118 | .post("/carts/" + customerId.value() + "/line-items") 119 | .then() 120 | .extract() 121 | .response(); 122 | 123 | assertThatResponseIsCart(response, cart); 124 | } 125 | 126 | @Test 127 | void givenAnInvalidProductId_addLineItem_returnsAnError() { 128 | CustomerId customerId = TEST_CUSTOMER_ID; 129 | String productId = ""; 130 | int quantity = 5; 131 | 132 | Response response = 133 | given() 134 | .port(TEST_PORT) 135 | .queryParam("productId", productId) 136 | .queryParam("quantity", quantity) 137 | .post("/carts/" + customerId.value() + "/line-items") 138 | .then() 139 | .extract() 140 | .response(); 141 | 142 | assertThatResponseIsError(response, BAD_REQUEST, "Invalid 'productId'"); 143 | } 144 | 145 | @Test 146 | void givenProductNotFound_addLineItem_returnsAnError() 147 | throws NotEnoughItemsInStockException, ProductNotFoundException { 148 | CustomerId customerId = TEST_CUSTOMER_ID; 149 | ProductId productId = ProductId.randomProductId(); 150 | int quantity = 5; 151 | 152 | when(addToCartUseCase.addToCart(customerId, productId, quantity)) 153 | .thenThrow(new ProductNotFoundException()); 154 | 155 | Response response = 156 | given() 157 | .port(TEST_PORT) 158 | .queryParam("productId", productId.value()) 159 | .queryParam("quantity", quantity) 160 | .post("/carts/" + customerId.value() + "/line-items") 161 | .then() 162 | .extract() 163 | .response(); 164 | 165 | assertThatResponseIsError(response, BAD_REQUEST, "The requested product does not exist"); 166 | } 167 | 168 | @Test 169 | void givenNotEnoughItemsInStock_addLineItem_returnsAnError() 170 | throws NotEnoughItemsInStockException, ProductNotFoundException { 171 | CustomerId customerId = TEST_CUSTOMER_ID; 172 | ProductId productId = ProductId.randomProductId(); 173 | int quantity = 5; 174 | 175 | when(addToCartUseCase.addToCart(customerId, productId, quantity)) 176 | .thenThrow(new NotEnoughItemsInStockException("Not enough items in stock", 2)); 177 | 178 | Response response = 179 | given() 180 | .port(TEST_PORT) 181 | .queryParam("productId", productId.value()) 182 | .queryParam("quantity", quantity) 183 | .post("/carts/" + customerId.value() + "/line-items") 184 | .then() 185 | .extract() 186 | .response(); 187 | 188 | assertThatResponseIsError(response, BAD_REQUEST, "Only 2 items in stock"); 189 | } 190 | 191 | @Test 192 | void givenACustomerId_deleteCart_invokesDeleteCartUseCaseAndReturnsUpdatedCart() { 193 | CustomerId customerId = TEST_CUSTOMER_ID; 194 | 195 | given() 196 | .port(TEST_PORT) 197 | .delete("/carts/" + customerId.value()) 198 | .then() 199 | .statusCode(NO_CONTENT.getStatusCode()); 200 | 201 | verify(emptyCartUseCase).emptyCart(customerId); 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/in/rest/product/ProductsControllerAssertions.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.product; 2 | 3 | import static jakarta.ws.rs.core.Response.Status.OK; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | 6 | import eu.happycoders.shop.model.product.Product; 7 | import io.restassured.path.json.JsonPath; 8 | import io.restassured.response.Response; 9 | import java.util.List; 10 | 11 | public final class ProductsControllerAssertions { 12 | 13 | private ProductsControllerAssertions() {} 14 | 15 | public static void assertThatResponseIsProduct(Response response, Product product) { 16 | assertThat(response.statusCode()).isEqualTo(OK.getStatusCode()); 17 | 18 | JsonPath json = response.jsonPath(); 19 | 20 | assertThatJsonProductMatchesProduct(json, true, "", product); 21 | } 22 | 23 | public static void assertThatResponseIsProductList(Response response, List products) { 24 | assertThat(response.statusCode()).isEqualTo(OK.getStatusCode()); 25 | 26 | JsonPath json = response.jsonPath(); 27 | 28 | for (int i = 0; i < products.size(); i++) { 29 | String prefix = "[%d].".formatted(i); 30 | Product product = products.get(i); 31 | assertThatJsonProductMatchesProduct(json, false, prefix, product); 32 | } 33 | } 34 | 35 | static void assertThatJsonProductMatchesProduct( 36 | JsonPath json, boolean jsonHasDescription, String prefix, Product product) { 37 | assertThat(json.getString(prefix + "id")).isEqualTo(product.id().value()); 38 | assertThat(json.getString(prefix + "name")).isEqualTo(product.name()); 39 | 40 | if (jsonHasDescription) { 41 | assertThat(json.getString(prefix + "description")).isEqualTo(product.description()); 42 | } else { 43 | assertThat(json.getString(prefix + "description")).isNull(); 44 | } 45 | 46 | assertThat(json.getString(prefix + "price.currency")) 47 | .isEqualTo(product.price().currency().getCurrencyCode()); 48 | assertThat(json.getDouble(prefix + "price.amount")) 49 | .isEqualTo(product.price().amount().doubleValue()); 50 | 51 | assertThat(json.getInt(prefix + "itemsInStock")).isEqualTo(product.itemsInStock()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/in/rest/product/ProductsControllerTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.in.rest.product; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.TEST_PORT; 4 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.assertThatResponseIsError; 5 | import static eu.happycoders.shop.adapter.in.rest.product.ProductsControllerAssertions.assertThatResponseIsProductList; 6 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 7 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 8 | import static io.restassured.RestAssured.given; 9 | import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST; 10 | import static org.mockito.Mockito.mock; 11 | import static org.mockito.Mockito.when; 12 | 13 | import eu.happycoders.shop.application.port.in.product.FindProductsUseCase; 14 | import eu.happycoders.shop.model.product.Product; 15 | import io.restassured.response.Response; 16 | import jakarta.ws.rs.core.Application; 17 | import java.util.List; 18 | import java.util.Set; 19 | import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer; 20 | import org.junit.jupiter.api.AfterAll; 21 | import org.junit.jupiter.api.BeforeAll; 22 | import org.junit.jupiter.api.BeforeEach; 23 | import org.junit.jupiter.api.Test; 24 | import org.mockito.Mockito; 25 | 26 | class ProductsControllerTest { 27 | 28 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 29 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(25, 99)); 30 | 31 | private static final FindProductsUseCase findProductsUseCase = mock(FindProductsUseCase.class); 32 | 33 | private static UndertowJaxrsServer server; 34 | 35 | @BeforeAll 36 | static void init() { 37 | server = 38 | new UndertowJaxrsServer() 39 | .setPort(TEST_PORT) 40 | .start() 41 | .deploy( 42 | new Application() { 43 | @Override 44 | public Set getSingletons() { 45 | return Set.of(new FindProductsController(findProductsUseCase)); 46 | } 47 | }); 48 | } 49 | 50 | @AfterAll 51 | static void stop() { 52 | server.stop(); 53 | } 54 | 55 | @BeforeEach 56 | void resetMocks() { 57 | Mockito.reset(findProductsUseCase); 58 | } 59 | 60 | @Test 61 | void givenAQueryAndAListOfProducts_findProducts_requestsProductsViaQueryAndReturnsThem() { 62 | String query = "foo"; 63 | List productList = List.of(TEST_PRODUCT_1, TEST_PRODUCT_2); 64 | 65 | when(findProductsUseCase.findByNameOrDescription(query)).thenReturn(productList); 66 | 67 | Response response = 68 | given() 69 | .port(TEST_PORT) 70 | .queryParam("query", query) 71 | .get("/products") 72 | .then() 73 | .extract() 74 | .response(); 75 | 76 | assertThatResponseIsProductList(response, productList); 77 | } 78 | 79 | @Test 80 | void givenANullQuery_findProducts_returnsError() { 81 | Response response = given().port(TEST_PORT).get("/products").then().extract().response(); 82 | 83 | assertThatResponseIsError(response, BAD_REQUEST, "Missing 'query'"); 84 | } 85 | 86 | @Test 87 | void givenATooShortQuery_findProducts_returnsError() { 88 | String query = "e"; 89 | when(findProductsUseCase.findByNameOrDescription(query)) 90 | .thenThrow(IllegalArgumentException.class); 91 | 92 | Response response = 93 | given() 94 | .port(TEST_PORT) 95 | .queryParam("query", query) 96 | .get("/products") 97 | .then() 98 | .extract() 99 | .response(); 100 | 101 | assertThatResponseIsError(response, BAD_REQUEST, "Invalid 'query'"); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/AbstractCartRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence; 2 | 3 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 4 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 8 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 9 | import eu.happycoders.shop.model.cart.Cart; 10 | import eu.happycoders.shop.model.cart.CartLineItem; 11 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 12 | import eu.happycoders.shop.model.customer.CustomerId; 13 | import eu.happycoders.shop.model.product.Product; 14 | import java.util.Optional; 15 | import java.util.concurrent.atomic.AtomicInteger; 16 | import org.junit.jupiter.api.BeforeEach; 17 | import org.junit.jupiter.api.Test; 18 | 19 | public abstract class AbstractCartRepositoryTest< 20 | T extends CartRepository, U extends ProductRepository> { 21 | 22 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 23 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(1, 49)); 24 | 25 | private static final AtomicInteger CUSTOMER_ID_SEQUENCE_GENERATOR = new AtomicInteger(); 26 | 27 | private T cartRepository; 28 | 29 | @BeforeEach 30 | void initRepositories() { 31 | cartRepository = createCartRepository(); 32 | persistTestProducts(); 33 | } 34 | 35 | protected abstract T createCartRepository(); 36 | 37 | private void persistTestProducts() { 38 | U productRepository = createProductRepository(); 39 | productRepository.save(TEST_PRODUCT_1); 40 | productRepository.save(TEST_PRODUCT_2); 41 | } 42 | 43 | protected abstract U createProductRepository(); 44 | 45 | @Test 46 | void givenACustomerIdForWhichNoCartIsPersisted_findByCustomerId_returnsAnEmptyOptional() { 47 | CustomerId customerId = createUniqueCustomerId(); 48 | 49 | Optional cart = cartRepository.findByCustomerId(customerId); 50 | 51 | assertThat(cart).isEmpty(); 52 | } 53 | 54 | @Test 55 | void givenPersistedCartWithProduct_findByCustomerId_returnsTheAppropriateCart() 56 | throws NotEnoughItemsInStockException { 57 | CustomerId customerId = createUniqueCustomerId(); 58 | 59 | Cart persistedCart = new Cart(customerId); 60 | persistedCart.addProduct(TEST_PRODUCT_1, 1); 61 | cartRepository.save(persistedCart); 62 | 63 | Optional cart = cartRepository.findByCustomerId(customerId); 64 | 65 | assertThat(cart).isNotEmpty(); 66 | assertThat(cart.get().id()).isEqualTo(customerId); 67 | assertThat(cart.get().lineItems()).hasSize(1); 68 | assertThat(cart.get().lineItems().get(0).product()).isEqualTo(TEST_PRODUCT_1); 69 | assertThat(cart.get().lineItems().get(0).quantity()).isEqualTo(1); 70 | } 71 | 72 | @Test 73 | void 74 | givenExistingCartWithProduct_andGivenANewCartForTheSameCustomer_saveCart_overwritesTheExistingCart() 75 | throws NotEnoughItemsInStockException { 76 | CustomerId customerId = createUniqueCustomerId(); 77 | 78 | Cart existingCart = new Cart(customerId); 79 | existingCart.addProduct(TEST_PRODUCT_1, 1); 80 | cartRepository.save(existingCart); 81 | 82 | Cart newCart = new Cart(customerId); 83 | newCart.addProduct(TEST_PRODUCT_2, 2); 84 | cartRepository.save(newCart); 85 | 86 | Optional cart = cartRepository.findByCustomerId(customerId); 87 | assertThat(cart).isNotEmpty(); 88 | assertThat(cart.get().id()).isEqualTo(customerId); 89 | assertThat(cart.get().lineItems()).hasSize(1); 90 | assertThat(cart.get().lineItems().get(0).product()).isEqualTo(TEST_PRODUCT_2); 91 | assertThat(cart.get().lineItems().get(0).quantity()).isEqualTo(2); 92 | } 93 | 94 | @Test 95 | void givenExistingCartWithProduct_addProductAndSaveCart_updatesTheExistingCart() 96 | throws NotEnoughItemsInStockException { 97 | CustomerId customerId = createUniqueCustomerId(); 98 | 99 | Cart existingCart = new Cart(customerId); 100 | existingCart.addProduct(TEST_PRODUCT_1, 1); 101 | cartRepository.save(existingCart); 102 | 103 | existingCart = cartRepository.findByCustomerId(customerId).orElseThrow(); 104 | existingCart.addProduct(TEST_PRODUCT_2, 2); 105 | cartRepository.save(existingCart); 106 | 107 | Optional cart = cartRepository.findByCustomerId(customerId); 108 | assertThat(cart).isNotEmpty(); 109 | assertThat(cart.get().id()).isEqualTo(customerId); 110 | assertThat(cart.get().lineItems()) 111 | .map(CartLineItem::product) 112 | .containsExactlyInAnyOrder(TEST_PRODUCT_1, TEST_PRODUCT_2); 113 | } 114 | 115 | @Test 116 | void givenExistingCart_deleteByCustomerId_deletesTheCart() { 117 | CustomerId customerId = createUniqueCustomerId(); 118 | 119 | Cart existingCart = new Cart(customerId); 120 | cartRepository.save(existingCart); 121 | 122 | assertThat(cartRepository.findByCustomerId(customerId)).isNotEmpty(); 123 | 124 | cartRepository.deleteByCustomerId(customerId); 125 | 126 | assertThat(cartRepository.findByCustomerId(customerId)).isEmpty(); 127 | } 128 | 129 | @Test 130 | void givenNotExistingCart_deleteByCustomerId_doesNothing() { 131 | CustomerId customerId = createUniqueCustomerId(); 132 | assertThat(cartRepository.findByCustomerId(customerId)).isEmpty(); 133 | 134 | cartRepository.deleteByCustomerId(customerId); 135 | 136 | assertThat(cartRepository.findByCustomerId(customerId)).isEmpty(); 137 | } 138 | 139 | private static CustomerId createUniqueCustomerId() { 140 | return new CustomerId(CUSTOMER_ID_SEQUENCE_GENERATOR.incrementAndGet()); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/AbstractProductRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 6 | import eu.happycoders.shop.model.product.Product; 7 | import eu.happycoders.shop.model.product.ProductId; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import org.junit.jupiter.api.BeforeEach; 11 | import org.junit.jupiter.api.Test; 12 | 13 | public abstract class AbstractProductRepositoryTest { 14 | 15 | private T productRepository; 16 | 17 | @BeforeEach 18 | void initRepository() { 19 | productRepository = createProductRepository(); 20 | } 21 | 22 | protected abstract T createProductRepository(); 23 | 24 | @Test 25 | void givenTestProductsAndATestProductId_findById_returnsATestProduct() { 26 | ProductId productId = DemoProducts.COMPUTER_MONITOR.id(); 27 | 28 | Optional product = productRepository.findById(productId); 29 | 30 | assertThat(product).contains(DemoProducts.COMPUTER_MONITOR); 31 | } 32 | 33 | @Test 34 | void givenTheIdOfAProductNotPersisted_findById_returnsAnEmptyOptional() { 35 | ProductId productId = new ProductId("00000"); 36 | 37 | Optional product = productRepository.findById(productId); 38 | 39 | assertThat(product).isEmpty(); 40 | } 41 | 42 | @Test 43 | void 44 | givenTestProductsAndASearchQueryNotMatchingAndProduct_findByNameOrDescription_returnsAnEmptyList() { 45 | String query = "not matching any product"; 46 | 47 | List products = productRepository.findByNameOrDescription(query); 48 | 49 | assertThat(products).isEmpty(); 50 | } 51 | 52 | @Test 53 | void 54 | givenTestProductsAndASearchQueryMatchingOneProduct_findByNameOrDescription_returnsThatProduct() { 55 | String query = "lights"; 56 | 57 | List products = productRepository.findByNameOrDescription(query); 58 | 59 | assertThat(products).containsExactlyInAnyOrder(DemoProducts.LED_LIGHTS); 60 | } 61 | 62 | @Test 63 | void 64 | givenTestProductsAndASearchQueryMatchingTwoProducts_findByNameOrDescription_returnsThoseProducts() { 65 | String query = "monitor"; 66 | 67 | List products = productRepository.findByNameOrDescription(query); 68 | 69 | assertThat(products) 70 | .containsExactlyInAnyOrder(DemoProducts.COMPUTER_MONITOR, DemoProducts.MONITOR_DESK_MOUNT); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/inmemory/InMemoryCartRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.inmemory; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.AbstractCartRepositoryTest; 4 | 5 | class InMemoryCartRepositoryTest 6 | extends AbstractCartRepositoryTest { 7 | 8 | @Override 9 | protected InMemoryCartRepository createCartRepository() { 10 | return new InMemoryCartRepository(); 11 | } 12 | 13 | @Override 14 | protected InMemoryProductRepository createProductRepository() { 15 | return new InMemoryProductRepository(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/inmemory/InMemoryProductRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.inmemory; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.AbstractProductRepositoryTest; 4 | 5 | class InMemoryProductRepositoryTest 6 | extends AbstractProductRepositoryTest { 7 | 8 | @Override 9 | protected InMemoryProductRepository createProductRepository() { 10 | return new InMemoryProductRepository(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/jpa/JpaCartRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.AbstractCartRepositoryTest; 4 | import jakarta.persistence.EntityManagerFactory; 5 | import org.junit.jupiter.api.AfterAll; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.testcontainers.containers.MySQLContainer; 8 | import org.testcontainers.utility.DockerImageName; 9 | 10 | class JpaCartRepositoryTest 11 | extends AbstractCartRepositoryTest { 12 | 13 | private static MySQLContainer mysql; 14 | private static EntityManagerFactory entityManagerFactory; 15 | 16 | @BeforeAll 17 | static void startDatabase() { 18 | mysql = new MySQLContainer<>(DockerImageName.parse("mysql:8.0")); 19 | mysql.start(); 20 | 21 | entityManagerFactory = 22 | EntityManagerFactoryFactory.createMySqlEntityManagerFactory( 23 | mysql.getJdbcUrl(), "root", "test"); 24 | } 25 | 26 | @Override 27 | protected JpaCartRepository createCartRepository() { 28 | return new JpaCartRepository(entityManagerFactory); 29 | } 30 | 31 | @Override 32 | protected JpaProductRepository createProductRepository() { 33 | return new JpaProductRepository(entityManagerFactory); 34 | } 35 | 36 | @AfterAll 37 | static void stopDatabase() { 38 | entityManagerFactory.close(); 39 | mysql.stop(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /adapter/src/test/java/eu/happycoders/shop/adapter/out/persistence/jpa/JpaProductRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.adapter.out.persistence.jpa; 2 | 3 | import eu.happycoders.shop.adapter.out.persistence.AbstractProductRepositoryTest; 4 | import jakarta.persistence.EntityManagerFactory; 5 | import org.junit.jupiter.api.AfterAll; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.testcontainers.containers.MySQLContainer; 8 | import org.testcontainers.utility.DockerImageName; 9 | 10 | class JpaProductRepositoryTest extends AbstractProductRepositoryTest { 11 | 12 | private static MySQLContainer mysql; 13 | private static EntityManagerFactory entityManagerFactory; 14 | 15 | @BeforeAll 16 | static void startDatabase() { 17 | mysql = new MySQLContainer<>(DockerImageName.parse("mysql:8.1")); 18 | mysql.start(); 19 | 20 | entityManagerFactory = 21 | EntityManagerFactoryFactory.createMySqlEntityManagerFactory( 22 | mysql.getJdbcUrl(), "root", "test"); 23 | } 24 | 25 | @Override 26 | protected JpaProductRepository createProductRepository() { 27 | return new JpaProductRepository(entityManagerFactory); 28 | } 29 | 30 | @AfterAll 31 | static void stopDatabase() { 32 | entityManagerFactory.close(); 33 | mysql.stop(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /application/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | eu.happycoders.shop 9 | parent 10 | 1.0-SNAPSHOT 11 | 12 | 13 | application 14 | 15 | 16 | 17 | 18 | eu.happycoders.shop 19 | model 20 | ${project.version} 21 | 22 | 23 | 24 | 25 | eu.happycoders.shop 26 | model 27 | ${project.version} 28 | tests 29 | test-jar 30 | test 31 | 32 | 33 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/in/cart/AddToCartUseCase.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.in.cart; 2 | 3 | import eu.happycoders.shop.model.cart.Cart; 4 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import eu.happycoders.shop.model.product.ProductId; 7 | 8 | /** 9 | * Use case: Adding a product to a shopping cart. 10 | * 11 | * @author Sven Woltmann 12 | */ 13 | public interface AddToCartUseCase { 14 | 15 | Cart addToCart(CustomerId customerId, ProductId productId, int quantity) 16 | throws ProductNotFoundException, NotEnoughItemsInStockException; 17 | } 18 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/in/cart/EmptyCartUseCase.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.in.cart; 2 | 3 | import eu.happycoders.shop.model.customer.CustomerId; 4 | 5 | /** 6 | * Use case: Emptying a shopping cart. 7 | * 8 | * @author Sven Woltmann 9 | */ 10 | public interface EmptyCartUseCase { 11 | 12 | void emptyCart(CustomerId customerId); 13 | } 14 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/in/cart/GetCartUseCase.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.in.cart; 2 | 3 | import eu.happycoders.shop.model.cart.Cart; 4 | import eu.happycoders.shop.model.customer.CustomerId; 5 | 6 | /** 7 | * Use case: Retrieving a shopping cart. 8 | * 9 | * @author Sven Woltmann 10 | */ 11 | public interface GetCartUseCase { 12 | 13 | Cart getCart(CustomerId customerId); 14 | } 15 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/in/cart/ProductNotFoundException.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.in.cart; 2 | 3 | /** 4 | * An exception indicating that no product was found for the product ID specified by a customer. 5 | * 6 | * @author Sven Woltmann 7 | */ 8 | public class ProductNotFoundException extends Exception {} 9 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/in/product/FindProductsUseCase.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.in.product; 2 | 3 | import eu.happycoders.shop.model.product.Product; 4 | import java.util.List; 5 | 6 | /** 7 | * Use case: Finding products via a search query. 8 | * 9 | * @author Sven Woltmann 10 | */ 11 | public interface FindProductsUseCase { 12 | 13 | List findByNameOrDescription(String query); 14 | } 15 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/out/persistence/CartRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.out.persistence; 2 | 3 | import eu.happycoders.shop.model.cart.Cart; 4 | import eu.happycoders.shop.model.customer.CustomerId; 5 | import java.util.Optional; 6 | 7 | /** 8 | * Outgoing persistence port for carts. 9 | * 10 | * @author Sven Woltmann 11 | */ 12 | public interface CartRepository { 13 | 14 | void save(Cart cart); 15 | 16 | Optional findByCustomerId(CustomerId customerId); 17 | 18 | void deleteByCustomerId(CustomerId customerId); 19 | } 20 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/port/out/persistence/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.port.out.persistence; 2 | 3 | import eu.happycoders.shop.model.product.Product; 4 | import eu.happycoders.shop.model.product.ProductId; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | /** 9 | * Outgoing persistence port for products. 10 | * 11 | * @author Sven Woltmann 12 | */ 13 | public interface ProductRepository { 14 | 15 | void save(Product product); 16 | 17 | Optional findById(ProductId productId); 18 | 19 | List findByNameOrDescription(String query); 20 | } 21 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/service/cart/AddToCartService.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import eu.happycoders.shop.application.port.in.cart.AddToCartUseCase; 4 | import eu.happycoders.shop.application.port.in.cart.ProductNotFoundException; 5 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 6 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 7 | import eu.happycoders.shop.model.cart.Cart; 8 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 9 | import eu.happycoders.shop.model.customer.CustomerId; 10 | import eu.happycoders.shop.model.product.Product; 11 | import eu.happycoders.shop.model.product.ProductId; 12 | import java.util.Objects; 13 | 14 | /** 15 | * Use case implementation: Adding a product to a shopping cart. 16 | * 17 | * @author Sven Woltmann 18 | */ 19 | public class AddToCartService implements AddToCartUseCase { 20 | 21 | private final CartRepository cartRepository; 22 | private final ProductRepository productRepository; 23 | 24 | public AddToCartService( 25 | CartRepository cartRepository, ProductRepository productRepositoryVeryVeryLong) { 26 | this.cartRepository = cartRepository; 27 | this.productRepository = productRepositoryVeryVeryLong; 28 | } 29 | 30 | @Override 31 | public Cart addToCart(CustomerId customerIdVeryVeryLong, ProductId productId, int quantity) 32 | throws ProductNotFoundException, NotEnoughItemsInStockException { 33 | Objects.requireNonNull(customerIdVeryVeryLong, "'customerId' must not be null"); 34 | Objects.requireNonNull(productId, "'productId' must not be null"); 35 | if (quantity < 1) { 36 | throw new IllegalArgumentException("'quantity' must be greater than 0"); 37 | } 38 | 39 | Product product = 40 | productRepository.findById(productId).orElseThrow(ProductNotFoundException::new); 41 | 42 | Cart cart = 43 | cartRepository 44 | .findByCustomerId(customerIdVeryVeryLong) 45 | .orElseGet(() -> new Cart(customerIdVeryVeryLong)); 46 | 47 | cart.addProduct(product, quantity); 48 | 49 | cartRepository.save(cart); 50 | 51 | return cart; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/service/cart/EmptyCartService.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import eu.happycoders.shop.application.port.in.cart.EmptyCartUseCase; 4 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 5 | import eu.happycoders.shop.model.customer.CustomerId; 6 | import java.util.Objects; 7 | 8 | /** 9 | * Use case implementation: Emptying a shopping cart. 10 | * 11 | * @author Sven Woltmann 12 | */ 13 | public class EmptyCartService implements EmptyCartUseCase { 14 | 15 | private final CartRepository cartRepository; 16 | 17 | public EmptyCartService(CartRepository cartRepository) { 18 | this.cartRepository = cartRepository; 19 | } 20 | 21 | @Override 22 | public void emptyCart(CustomerId customerId) { 23 | Objects.requireNonNull(customerId, "'customerId' must not be null"); 24 | 25 | cartRepository.deleteByCustomerId(customerId); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/service/cart/GetCartService.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import eu.happycoders.shop.application.port.in.cart.GetCartUseCase; 4 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 5 | import eu.happycoders.shop.model.cart.Cart; 6 | import eu.happycoders.shop.model.customer.CustomerId; 7 | import java.util.Objects; 8 | 9 | /** 10 | * Use case implementation: Retrieving a shopping cart. 11 | * 12 | * @author Sven Woltmann 13 | */ 14 | public class GetCartService implements GetCartUseCase { 15 | 16 | private final CartRepository cartRepository; 17 | 18 | public GetCartService(CartRepository cartRepository) { 19 | this.cartRepository = cartRepository; 20 | } 21 | 22 | @Override 23 | public Cart getCart(CustomerId customerIdVeryLong) { 24 | Objects.requireNonNull(customerIdVeryLong, "'customerId' must not be null"); 25 | 26 | return cartRepository 27 | .findByCustomerId(customerIdVeryLong) 28 | .orElseGet(() -> new Cart(customerIdVeryLong)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /application/src/main/java/eu/happycoders/shop/application/service/product/FindProductsService.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.product; 2 | 3 | import eu.happycoders.shop.application.port.in.product.FindProductsUseCase; 4 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 5 | import eu.happycoders.shop.model.product.Product; 6 | import java.util.List; 7 | import java.util.Objects; 8 | 9 | /** 10 | * Use case implementation: Finding products via a search query. 11 | * 12 | * @author Sven Woltmann 13 | */ 14 | public class FindProductsService implements FindProductsUseCase { 15 | 16 | private final ProductRepository productRepository; 17 | 18 | public FindProductsService(ProductRepository productRepository) { 19 | this.productRepository = productRepository; 20 | } 21 | 22 | @Override 23 | public List findByNameOrDescription(String query) { 24 | Objects.requireNonNull(query, "'query' must not be null"); 25 | if (query.length() < 2) { 26 | throw new IllegalArgumentException("'query' must be at least two characters long"); 27 | } 28 | 29 | return productRepository.findByNameOrDescription(query); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /application/src/test/java/eu/happycoders/shop/application/service/cart/AddToCartServiceTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 4 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 7 | import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 8 | import static org.mockito.ArgumentMatchers.any; 9 | import static org.mockito.Mockito.mock; 10 | import static org.mockito.Mockito.never; 11 | import static org.mockito.Mockito.verify; 12 | import static org.mockito.Mockito.when; 13 | 14 | import eu.happycoders.shop.application.port.in.cart.ProductNotFoundException; 15 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 16 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 17 | import eu.happycoders.shop.model.cart.Cart; 18 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 19 | import eu.happycoders.shop.model.customer.CustomerId; 20 | import eu.happycoders.shop.model.product.Product; 21 | import eu.happycoders.shop.model.product.ProductId; 22 | import java.util.Optional; 23 | import org.assertj.core.api.ThrowableAssert.ThrowingCallable; 24 | import org.junit.jupiter.api.BeforeEach; 25 | import org.junit.jupiter.api.Test; 26 | 27 | class AddToCartServiceTest { 28 | 29 | private static final CustomerId TEST_CUSTOMER_ID = new CustomerId(61157); 30 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 31 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(25, 99)); 32 | 33 | private final CartRepository cartRepository = mock(CartRepository.class); 34 | private final ProductRepository productRepository = mock(ProductRepository.class); 35 | private final AddToCartService addToCartService = 36 | new AddToCartService(cartRepository, productRepository); 37 | 38 | @BeforeEach 39 | void initTestDoubles() { 40 | when(productRepository.findById(TEST_PRODUCT_1.id())).thenReturn(Optional.of(TEST_PRODUCT_1)); 41 | 42 | when(productRepository.findById(TEST_PRODUCT_2.id())).thenReturn(Optional.of(TEST_PRODUCT_2)); 43 | } 44 | 45 | @Test 46 | void givenExistingCart_addToCart_cartWithAddedProductIsSavedAndReturned() 47 | throws NotEnoughItemsInStockException, ProductNotFoundException { 48 | Cart persistedCart = new Cart(TEST_CUSTOMER_ID); 49 | persistedCart.addProduct(TEST_PRODUCT_1, 1); 50 | 51 | when(cartRepository.findByCustomerId(TEST_CUSTOMER_ID)).thenReturn(Optional.of(persistedCart)); 52 | 53 | Cart cart = addToCartService.addToCart(TEST_CUSTOMER_ID, TEST_PRODUCT_2.id(), 3); 54 | 55 | verify(cartRepository).save(cart); 56 | 57 | assertThat(cart.lineItems()).hasSize(2); 58 | assertThat(cart.lineItems().get(0).product()).isEqualTo(TEST_PRODUCT_1); 59 | assertThat(cart.lineItems().get(0).quantity()).isEqualTo(1); 60 | assertThat(cart.lineItems().get(1).product()).isEqualTo(TEST_PRODUCT_2); 61 | assertThat(cart.lineItems().get(1).quantity()).isEqualTo(3); 62 | } 63 | 64 | @Test 65 | void givenNoExistingCart_addToCart_cartWithAddedProductIsSavedAndReturned() 66 | throws NotEnoughItemsInStockException, ProductNotFoundException { 67 | Cart cart = addToCartService.addToCart(TEST_CUSTOMER_ID, TEST_PRODUCT_1.id(), 2); 68 | 69 | verify(cartRepository).save(cart); 70 | 71 | assertThat(cart.lineItems()).hasSize(1); 72 | assertThat(cart.lineItems().get(0).product()).isEqualTo(TEST_PRODUCT_1); 73 | assertThat(cart.lineItems().get(0).quantity()).isEqualTo(2); 74 | } 75 | 76 | @Test 77 | void givenAnUnknownProductId_addToCart_throwsException() { 78 | ProductId productId = ProductId.randomProductId(); 79 | 80 | ThrowingCallable invocation = () -> addToCartService.addToCart(TEST_CUSTOMER_ID, productId, 1); 81 | 82 | assertThatExceptionOfType(ProductNotFoundException.class).isThrownBy(invocation); 83 | verify(cartRepository, never()).save(any()); 84 | } 85 | 86 | @Test 87 | void givenQuantityLessThan1_addToCart_throwsException() { 88 | int quantity = 0; 89 | 90 | ThrowingCallable invocation = 91 | () -> addToCartService.addToCart(TEST_CUSTOMER_ID, TEST_PRODUCT_1.id(), quantity); 92 | 93 | assertThatIllegalArgumentException().isThrownBy(invocation); 94 | verify(cartRepository, never()).save(any()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /application/src/test/java/eu/happycoders/shop/application/service/cart/EmptyCartServiceTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import static org.mockito.Mockito.mock; 4 | import static org.mockito.Mockito.verify; 5 | 6 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 7 | import eu.happycoders.shop.model.customer.CustomerId; 8 | import org.junit.jupiter.api.Test; 9 | 10 | class EmptyCartServiceTest { 11 | 12 | private static final CustomerId TEST_CUSTOMER_ID = new CustomerId(61157); 13 | 14 | private final CartRepository cartRepository = mock(CartRepository.class); 15 | private final EmptyCartService emptyCartService = new EmptyCartService(cartRepository); 16 | 17 | @Test 18 | void emptyCart_invokesDeleteOnThePersistencePort() { 19 | emptyCartService.emptyCart(TEST_CUSTOMER_ID); 20 | 21 | verify(cartRepository).deleteByCustomerId(TEST_CUSTOMER_ID); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /application/src/test/java/eu/happycoders/shop/application/service/cart/GetCartServiceTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.cart; 2 | 3 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 4 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | import static org.mockito.Mockito.mock; 7 | 8 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 9 | import eu.happycoders.shop.model.cart.Cart; 10 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 11 | import eu.happycoders.shop.model.customer.CustomerId; 12 | import eu.happycoders.shop.model.product.Product; 13 | import java.util.Optional; 14 | import org.junit.jupiter.api.Test; 15 | import org.mockito.Mockito; 16 | 17 | class GetCartServiceTest { 18 | 19 | private static final CustomerId TEST_CUSTOMER_ID = new CustomerId(61157); 20 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 21 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(25, 99)); 22 | 23 | private final CartRepository cartRepository = mock(CartRepository.class); 24 | private final GetCartService getCartService = new GetCartService(cartRepository); 25 | 26 | @Test 27 | void givenCartIsPersisted_getCart_returnsPersistedCart() throws NotEnoughItemsInStockException { 28 | Cart persistedCart = new Cart(TEST_CUSTOMER_ID); 29 | persistedCart.addProduct(TEST_PRODUCT_1, 1); 30 | persistedCart.addProduct(TEST_PRODUCT_2, 5); 31 | 32 | Mockito.when(cartRepository.findByCustomerId(TEST_CUSTOMER_ID)) 33 | .thenReturn(Optional.of(persistedCart)); 34 | 35 | Cart cart = getCartService.getCart(TEST_CUSTOMER_ID); 36 | 37 | assertThat(cart).isSameAs(persistedCart); 38 | } 39 | 40 | @Test 41 | void givenCartIsNotPersisted_getCart_returnsAnEmptyCart() { 42 | Mockito.when(cartRepository.findByCustomerId(TEST_CUSTOMER_ID)).thenReturn(Optional.empty()); 43 | 44 | Cart cart = getCartService.getCart(TEST_CUSTOMER_ID); 45 | 46 | assertThat(cart).isNotNull(); 47 | assertThat(cart.lineItems()).isEmpty(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /application/src/test/java/eu/happycoders/shop/application/service/product/FindProductsServiceTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.application.service.product; 2 | 3 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 4 | import static eu.happycoders.shop.model.product.TestProductFactory.createTestProduct; 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 7 | import static org.mockito.Mockito.mock; 8 | import static org.mockito.Mockito.when; 9 | 10 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 11 | import eu.happycoders.shop.model.product.Product; 12 | import java.util.List; 13 | import org.assertj.core.api.ThrowableAssert.ThrowingCallable; 14 | import org.junit.jupiter.api.Test; 15 | 16 | class FindProductsServiceTest { 17 | 18 | private static final Product TEST_PRODUCT_1 = createTestProduct(euros(19, 99)); 19 | private static final Product TEST_PRODUCT_2 = createTestProduct(euros(25, 99)); 20 | 21 | private final ProductRepository productRepository = mock(ProductRepository.class); 22 | private final FindProductsService findProductsService = 23 | new FindProductsService(productRepository); 24 | 25 | @Test 26 | void givenASearchQuery_findByNameOrDescription_returnsTheProductsReturnedByThePersistencePort() { 27 | when(productRepository.findByNameOrDescription("one")).thenReturn(List.of(TEST_PRODUCT_1)); 28 | when(productRepository.findByNameOrDescription("two")).thenReturn(List.of(TEST_PRODUCT_2)); 29 | when(productRepository.findByNameOrDescription("one-two")) 30 | .thenReturn(List.of(TEST_PRODUCT_1, TEST_PRODUCT_2)); 31 | when(productRepository.findByNameOrDescription("empty")).thenReturn(List.of()); 32 | 33 | assertThat(findProductsService.findByNameOrDescription("one")).containsExactly(TEST_PRODUCT_1); 34 | assertThat(findProductsService.findByNameOrDescription("two")).containsExactly(TEST_PRODUCT_2); 35 | assertThat(findProductsService.findByNameOrDescription("one-two")) 36 | .containsExactly(TEST_PRODUCT_1, TEST_PRODUCT_2); 37 | assertThat(findProductsService.findByNameOrDescription("empty")).isEmpty(); 38 | } 39 | 40 | @Test 41 | void givenATooShortSearchQuery_findByNameOrDescription_throwsAnException() { 42 | String searchQuery = "x"; 43 | 44 | ThrowingCallable invocation = () -> findProductsService.findByNameOrDescription(searchQuery); 45 | 46 | assertThatIllegalArgumentException().isThrownBy(invocation); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bootstrap/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | eu.happycoders.shop 9 | parent 10 | 1.0-SNAPSHOT 11 | 12 | 13 | bootstrap 14 | 15 | 16 | 17 | 18 | eu.happycoders.shop 19 | adapter 20 | ${project.version} 21 | 22 | 24 | 25 | eu.happycoders.shop 26 | application 27 | ${project.version} 28 | 29 | 30 | eu.happycoders.shop 31 | model 32 | ${project.version} 33 | 34 | 35 | 36 | 37 | org.jboss.resteasy 38 | resteasy-undertow 39 | 40 | 41 | 42 | org.jboss 43 | jandex 44 | 45 | 46 | 47 | 48 | 49 | 50 | mysql 51 | mysql-connector-java 52 | runtime 53 | 54 | 55 | org.jboss.resteasy 56 | resteasy-jackson2-provider 57 | runtime 58 | 59 | 60 | org.glassfish 61 | jakarta.el 62 | runtime 63 | 64 | 65 | org.hibernate.orm 66 | hibernate-core 67 | runtime 68 | 69 | 70 | org.hibernate.validator 71 | hibernate-validator 72 | runtime 73 | 74 | 75 | 76 | 77 | com.tngtech.archunit 78 | archunit-junit5 79 | test 80 | 81 | 82 | io.rest-assured 83 | rest-assured 84 | test 85 | 86 | 87 | 88 | 89 | eu.happycoders.shop 90 | adapter 91 | ${project.version} 92 | tests 93 | test-jar 94 | test 95 | 96 | 97 | 98 | 99 | 100 | test-coverage 101 | 102 | 103 | 104 | org.jacoco 105 | jacoco-maven-plugin 106 | 107 | 110 | 111 | report-aggregate 112 | verify 113 | 114 | report-aggregate 115 | 116 | 117 | XML 118 | true 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /bootstrap/src/main/java/eu/happycoders/shop/bootstrap/Launcher.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap; 2 | 3 | import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer; 4 | 5 | /** 6 | * Launcher for the application: starts the Undertow server and deploys the shop application. 7 | * 8 | * @author Sven Woltmann 9 | */ 10 | public class Launcher { 11 | 12 | private static final int PORT = 8080; 13 | 14 | private UndertowJaxrsServer server; 15 | 16 | public static void main(String[] args) { 17 | new Launcher().startOnPort(PORT); 18 | } 19 | 20 | public void startOnPort(int port) { 21 | server = new UndertowJaxrsServer().setPort(port); 22 | startServer(); 23 | } 24 | 25 | private void startServer() { 26 | server.start(); 27 | server.deploy(RestEasyUndertowShopApplication.class); 28 | } 29 | 30 | public void stop() { 31 | server.stop(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /bootstrap/src/main/java/eu/happycoders/shop/bootstrap/RestEasyUndertowShopApplication.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap; 2 | 3 | import eu.happycoders.shop.adapter.in.rest.cart.AddToCartController; 4 | import eu.happycoders.shop.adapter.in.rest.cart.EmptyCartController; 5 | import eu.happycoders.shop.adapter.in.rest.cart.GetCartController; 6 | import eu.happycoders.shop.adapter.in.rest.product.FindProductsController; 7 | import eu.happycoders.shop.adapter.out.persistence.inmemory.InMemoryCartRepository; 8 | import eu.happycoders.shop.adapter.out.persistence.inmemory.InMemoryProductRepository; 9 | import eu.happycoders.shop.adapter.out.persistence.jpa.EntityManagerFactoryFactory; 10 | import eu.happycoders.shop.adapter.out.persistence.jpa.JpaCartRepository; 11 | import eu.happycoders.shop.adapter.out.persistence.jpa.JpaProductRepository; 12 | import eu.happycoders.shop.application.port.in.cart.AddToCartUseCase; 13 | import eu.happycoders.shop.application.port.in.cart.EmptyCartUseCase; 14 | import eu.happycoders.shop.application.port.in.cart.GetCartUseCase; 15 | import eu.happycoders.shop.application.port.in.product.FindProductsUseCase; 16 | import eu.happycoders.shop.application.port.out.persistence.CartRepository; 17 | import eu.happycoders.shop.application.port.out.persistence.ProductRepository; 18 | import eu.happycoders.shop.application.service.cart.AddToCartService; 19 | import eu.happycoders.shop.application.service.cart.EmptyCartService; 20 | import eu.happycoders.shop.application.service.cart.GetCartService; 21 | import eu.happycoders.shop.application.service.product.FindProductsService; 22 | import jakarta.persistence.EntityManagerFactory; 23 | import jakarta.ws.rs.core.Application; 24 | import java.util.Set; 25 | 26 | /** 27 | * The application configuration for the Undertow server. Evaluates the persistence configuration, 28 | * instantiates the appropriate adapters and use cases, and wires them. 29 | * 30 | * @author Sven Woltmann 31 | */ 32 | public class RestEasyUndertowShopApplication extends Application { 33 | 34 | private CartRepository cartRepository; 35 | private ProductRepository productRepository; 36 | 37 | // We're encouraged to use "automatic discovery of resources", but I want to define them manually. 38 | @SuppressWarnings("deprecation") 39 | @Override 40 | public Set getSingletons() { 41 | initPersistenceAdapters(); 42 | return Set.of( 43 | addToCartController(), 44 | getCartController(), 45 | emptyCartController(), 46 | findProductsController()); 47 | } 48 | 49 | private void initPersistenceAdapters() { 50 | String persistence = System.getProperty("persistence", "inmemory"); 51 | switch (persistence) { 52 | case "inmemory" -> initInMemoryAdapters(); 53 | case "mysql" -> initMySqlAdapters(); 54 | default -> throw new IllegalArgumentException( 55 | "Invalid 'persistence' property: '%s' (allowed: 'inmemory', 'mysql')" 56 | .formatted(persistence)); 57 | } 58 | } 59 | 60 | private void initInMemoryAdapters() { 61 | cartRepository = new InMemoryCartRepository(); 62 | productRepository = new InMemoryProductRepository(); 63 | } 64 | 65 | // The EntityManagerFactory doesn't need to get closed before the application is stopped 66 | @SuppressWarnings("PMD.CloseResource") 67 | private void initMySqlAdapters() { 68 | EntityManagerFactory entityManagerFactory = 69 | EntityManagerFactoryFactory.createMySqlEntityManagerFactory( 70 | "jdbc:mysql://localhost:3306/shop", "root", "test"); 71 | 72 | cartRepository = new JpaCartRepository(entityManagerFactory); 73 | productRepository = new JpaProductRepository(entityManagerFactory); 74 | } 75 | 76 | private AddToCartController addToCartController() { 77 | AddToCartUseCase addToCartUseCase = new AddToCartService(cartRepository, productRepository); 78 | return new AddToCartController(addToCartUseCase); 79 | } 80 | 81 | private GetCartController getCartController() { 82 | GetCartUseCase getCartUseCase = new GetCartService(cartRepository); 83 | return new GetCartController(getCartUseCase); 84 | } 85 | 86 | private EmptyCartController emptyCartController() { 87 | EmptyCartUseCase emptyCartUseCase = new EmptyCartService(cartRepository); 88 | return new EmptyCartController(emptyCartUseCase); 89 | } 90 | 91 | private FindProductsController findProductsController() { 92 | FindProductsUseCase findProductsUseCase = new FindProductsService(productRepository); 93 | return new FindProductsController(findProductsUseCase); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /bootstrap/src/test/java/eu/happycoders/shop/bootstrap/archunit/DependencyRuleTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap.archunit; 2 | 3 | import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; 4 | 5 | import com.tngtech.archunit.core.domain.JavaClasses; 6 | import com.tngtech.archunit.core.importer.ClassFileImporter; 7 | import org.junit.jupiter.api.Test; 8 | 9 | class DependencyRuleTest { 10 | 11 | private static final String ROOT_PACKAGE = "eu.happycoders.shop"; 12 | private static final String MODEL_PACKAGE = "model"; 13 | private static final String APPLICATION_PACKAGE = "application"; 14 | private static final String PORT_PACKAGE = "application.port"; 15 | private static final String SERVICE_PACKAGE = "application.service"; 16 | private static final String ADAPTER_PACKAGE = "adapter"; 17 | private static final String BOOTSTRAP_PACKAGE = "bootstrap"; 18 | 19 | @Test 20 | void checkDependencyRule() { 21 | String importPackages = ROOT_PACKAGE + ".."; 22 | JavaClasses classesToCheck = new ClassFileImporter().importPackages(importPackages); 23 | 24 | checkNoDependencyFromTo(MODEL_PACKAGE, APPLICATION_PACKAGE, classesToCheck); 25 | checkNoDependencyFromTo(MODEL_PACKAGE, ADAPTER_PACKAGE, classesToCheck); 26 | checkNoDependencyFromTo(MODEL_PACKAGE, BOOTSTRAP_PACKAGE, classesToCheck); 27 | 28 | checkNoDependencyFromTo(APPLICATION_PACKAGE, ADAPTER_PACKAGE, classesToCheck); 29 | checkNoDependencyFromTo(APPLICATION_PACKAGE, BOOTSTRAP_PACKAGE, classesToCheck); 30 | 31 | checkNoDependencyFromTo(PORT_PACKAGE, SERVICE_PACKAGE, classesToCheck); 32 | 33 | checkNoDependencyFromTo(ADAPTER_PACKAGE, SERVICE_PACKAGE, classesToCheck); 34 | checkNoDependencyFromTo(ADAPTER_PACKAGE, BOOTSTRAP_PACKAGE, classesToCheck); 35 | } 36 | 37 | private void checkNoDependencyFromTo( 38 | String fromPackage, String toPackage, JavaClasses classesToCheck) { 39 | noClasses() 40 | .that() 41 | .resideInAPackage(fullyQualified(fromPackage)) 42 | .should() 43 | .dependOnClassesThat() 44 | .resideInAPackage(fullyQualified(toPackage)) 45 | .check(classesToCheck); 46 | } 47 | 48 | private String fullyQualified(String packageName) { 49 | return ROOT_PACKAGE + '.' + packageName + ".."; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /bootstrap/src/test/java/eu/happycoders/shop/bootstrap/e2e/CartTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap.e2e; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.TEST_PORT; 4 | import static eu.happycoders.shop.adapter.in.rest.cart.CartsControllerAssertions.assertThatResponseIsCart; 5 | import static eu.happycoders.shop.adapter.out.persistence.DemoProducts.LED_LIGHTS; 6 | import static eu.happycoders.shop.adapter.out.persistence.DemoProducts.MONITOR_DESK_MOUNT; 7 | import static io.restassured.RestAssured.given; 8 | import static jakarta.ws.rs.core.Response.Status.NO_CONTENT; 9 | 10 | import eu.happycoders.shop.model.cart.Cart; 11 | import eu.happycoders.shop.model.cart.NotEnoughItemsInStockException; 12 | import eu.happycoders.shop.model.customer.CustomerId; 13 | import io.restassured.response.Response; 14 | import org.junit.jupiter.api.MethodOrderer; 15 | import org.junit.jupiter.api.Order; 16 | import org.junit.jupiter.api.Test; 17 | import org.junit.jupiter.api.TestMethodOrder; 18 | 19 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class) 20 | class CartTest extends EndToEndTest { 21 | 22 | private static final CustomerId TEST_CUSTOMER_ID = new CustomerId(61157); 23 | private static final String CARTS_PATH = "/carts/" + TEST_CUSTOMER_ID.value(); 24 | 25 | @Test 26 | @Order(1) 27 | void givenAnEmptyCart_addLineItem_addsTheLineItemAndReturnsTheCartWithTheAddedItem() 28 | throws NotEnoughItemsInStockException { 29 | Response response = 30 | given() 31 | .port(TEST_PORT) 32 | .queryParam("productId", LED_LIGHTS.id().value()) 33 | .queryParam("quantity", 3) 34 | .post(CARTS_PATH + "/line-items") 35 | .then() 36 | .extract() 37 | .response(); 38 | 39 | Cart expectedCart = new Cart(TEST_CUSTOMER_ID); 40 | expectedCart.addProduct(LED_LIGHTS, 3); 41 | 42 | assertThatResponseIsCart(response, expectedCart); 43 | } 44 | 45 | @Test 46 | @Order(2) 47 | void givenACartWithOneLineItem_addLineItem_addsTheLineItemAndReturnsACartWithTwoLineItems() 48 | throws NotEnoughItemsInStockException { 49 | Response response = 50 | given() 51 | .port(TEST_PORT) 52 | .queryParam("productId", MONITOR_DESK_MOUNT.id().value()) 53 | .queryParam("quantity", 1) 54 | .post(CARTS_PATH + "/line-items") 55 | .then() 56 | .extract() 57 | .response(); 58 | 59 | Cart expectedCart = new Cart(TEST_CUSTOMER_ID); 60 | expectedCart.addProduct(LED_LIGHTS, 3); 61 | expectedCart.addProduct(MONITOR_DESK_MOUNT, 1); 62 | 63 | assertThatResponseIsCart(response, expectedCart); 64 | } 65 | 66 | @Test 67 | @Order(3) 68 | void givenACartWithTwoLineItems_getCart_returnsTheCart() throws NotEnoughItemsInStockException { 69 | Response response = given().port(TEST_PORT).get(CARTS_PATH).then().extract().response(); 70 | 71 | Cart expectedCart = new Cart(TEST_CUSTOMER_ID); 72 | expectedCart.addProduct(LED_LIGHTS, 3); 73 | expectedCart.addProduct(MONITOR_DESK_MOUNT, 1); 74 | 75 | assertThatResponseIsCart(response, expectedCart); 76 | } 77 | 78 | @Test 79 | @Order(4) 80 | void givenACartWithTwoLineItems_delete_returnsStatusCodeNoContent() { 81 | given().port(TEST_PORT).delete(CARTS_PATH).then().statusCode(NO_CONTENT.getStatusCode()); 82 | } 83 | 84 | @Test 85 | @Order(5) 86 | void givenAnEmptiedCart_getCart_returnsAnEmptyCart() { 87 | Response response = given().port(TEST_PORT).get(CARTS_PATH).then().extract().response(); 88 | 89 | assertThatResponseIsCart(response, new Cart(TEST_CUSTOMER_ID)); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /bootstrap/src/test/java/eu/happycoders/shop/bootstrap/e2e/EndToEndTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap.e2e; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.TEST_PORT; 4 | 5 | import eu.happycoders.shop.bootstrap.Launcher; 6 | import org.junit.jupiter.api.AfterAll; 7 | import org.junit.jupiter.api.BeforeAll; 8 | 9 | abstract class EndToEndTest { 10 | 11 | private static Launcher launcher; 12 | 13 | @BeforeAll 14 | static void init() { 15 | launcher = new Launcher(); 16 | launcher.startOnPort(TEST_PORT); 17 | } 18 | 19 | @AfterAll 20 | static void stop() { 21 | launcher.stop(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bootstrap/src/test/java/eu/happycoders/shop/bootstrap/e2e/FindProductsTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.bootstrap.e2e; 2 | 3 | import static eu.happycoders.shop.adapter.in.rest.HttpTestCommons.TEST_PORT; 4 | import static eu.happycoders.shop.adapter.in.rest.product.ProductsControllerAssertions.assertThatResponseIsProductList; 5 | import static eu.happycoders.shop.adapter.out.persistence.DemoProducts.COMPUTER_MONITOR; 6 | import static eu.happycoders.shop.adapter.out.persistence.DemoProducts.MONITOR_DESK_MOUNT; 7 | import static io.restassured.RestAssured.given; 8 | 9 | import io.restassured.response.Response; 10 | import java.util.List; 11 | import org.junit.jupiter.api.Test; 12 | 13 | class FindProductsTest extends EndToEndTest { 14 | 15 | @Test 16 | void givenTestProductsAndAQuery_findProducts_returnsMatchingProducts() { 17 | String query = "monitor"; 18 | 19 | Response response = 20 | given() 21 | .port(TEST_PORT) 22 | .queryParam("query", query) 23 | .get("/products") 24 | .then() 25 | .extract() 26 | .response(); 27 | 28 | assertThatResponseIsProductList(response, List.of(COMPUTER_MONITOR, MONITOR_DESK_MOUNT)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /doc/architecture-components.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | [bootstrap]<> 3 | [bootstrap] -> [adapter] 4 | 5 | [adapter]<> 6 | [adapter] -> [application] 7 | 8 | [application]<> 9 | [application] -> [model] 10 | 11 | [model]<> 12 | @enduml -------------------------------------------------------------------------------- /doc/hexagonal-architecture-modules.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SvenWoltmann/hexagonal-architecture-java/d2240875673207bdea68717e4121a53efdd44277/doc/hexagonal-architecture-modules.png -------------------------------------------------------------------------------- /doc/persistence-tests.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | abstract class AbstractProductRepositoryTest { 3 | - productRepository : ProductRepository 4 | # {abstract} createProductRepository() : ProductRepository 5 | ~ test1() 6 | ~ test2() 7 | ~ test3() 8 | ~ {method} ... 9 | } 10 | 11 | abstract class AbstractCartRepositoryTest { 12 | - cartRepository : CartRepository 13 | - productRepository : ProductRepository 14 | # {abstract} createCartRepository() : CartRepository 15 | # {abstract} createProductRepository() : ProductRepository 16 | ~ test1() 17 | ~ test2() 18 | ~ test3() 19 | ~ {method} ... 20 | } 21 | 22 | class InMemoryProductRepositoryTest extends AbstractProductRepositoryTest { 23 | # createProductRepository() : ProductRepository 24 | } 25 | class InMemoryCartRepositoryTest extends AbstractCartRepositoryTest { 26 | # createCartRepository() : CartRepository 27 | # createProductRepository() : ProductRepository 28 | } 29 | 30 | class JpaProductRepositoryTest extends AbstractProductRepositoryTest { 31 | - {static} mysql : MySQLContainer 32 | - {static} entityManagerFactory : EntityManagerFactory 33 | # createProductRepository() : ProductRepository 34 | ~ {static} startDatabase() 35 | ~ {static} stopDatabase() 36 | } 37 | class JpaCartRepositoryTest extends AbstractCartRepositoryTest { 38 | # createCartRepository() : CartRepository 39 | # createProductRepository() : ProductRepository 40 | } 41 | 42 | @enduml -------------------------------------------------------------------------------- /doc/ports-and-services-and-adapters-alt.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | package "eu:happycoders:shop:adapter:in:rest" { 3 | package "cart" { 4 | class CartsController<> {} 5 | } 6 | package "product" { 7 | class ProductsController<> {} 8 | } 9 | } 10 | 11 | package "eu:happycoders:shop:application:port:in" { 12 | package "cart" { 13 | interface EmptyCartUseCase<> {} 14 | interface GetCartUseCase<> {} 15 | interface AddToCartUseCase<> {} 16 | 17 | CartsController --> EmptyCartUseCase 18 | CartsController --> GetCartUseCase 19 | CartsController --> AddToCartUseCase 20 | } 21 | package "product" { 22 | interface FindProductsUseCase<> 23 | 24 | ProductsController --> FindProductsUseCase 25 | } 26 | } 27 | 28 | package "eu:happycoders:shop:application:service" { 29 | package "cart" { 30 | EmptyCartUseCase <|.. EmptyCartService 31 | GetCartUseCase <|.. GetCartService 32 | AddToCartUseCase <|.. AddToCartService 33 | } 34 | package "product" { 35 | FindProductsUseCase <|.. FindProductsService 36 | } 37 | } 38 | 39 | package "eu:happycoders:shop:application:port:out:persistence" { 40 | interface CartRepository<> 41 | interface ProductRepository<> 42 | 43 | AddToCartService --> CartRepository 44 | AddToCartService --> ProductRepository 45 | EmptyCartService --> CartRepository 46 | GetCartService --> CartRepository 47 | 48 | FindProductsService --> ProductRepository 49 | } 50 | 51 | package "eu:happycoders:shop:adapter:out:persistence" { 52 | class InMemoryRepository<> {} 53 | 54 | CartRepository <|.. InMemoryRepository 55 | ProductRepository <|.. InMemoryRepository 56 | } 57 | @enduml -------------------------------------------------------------------------------- /doc/ports-and-services-and-adapters.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | package "eu:happycoders:shop:adapter:in:rest" { 3 | package "cart" { 4 | class EmptyCartController<> {} 5 | class GetCartController<> {} 6 | class AddToCartController<> {} 7 | } 8 | package "product" { 9 | class FindProductsController<> {} 10 | } 11 | } 12 | 13 | package "eu:happycoders:shop:application:port:in" { 14 | package "cart" { 15 | interface EmptyCartUseCase<> {} 16 | interface GetCartUseCase<> {} 17 | interface AddToCartUseCase<> {} 18 | 19 | EmptyCartController --> EmptyCartUseCase 20 | GetCartController --> GetCartUseCase 21 | AddToCartController --> AddToCartUseCase 22 | } 23 | package "product" { 24 | interface FindProductsUseCase<> 25 | 26 | FindProductsController --> FindProductsUseCase 27 | } 28 | } 29 | 30 | package "eu:happycoders:shop:application:service" { 31 | package "cart" { 32 | EmptyCartUseCase <|.. EmptyCartService 33 | GetCartUseCase <|.. GetCartService 34 | AddToCartUseCase <|.. AddToCartService 35 | } 36 | package "product" { 37 | FindProductsUseCase <|.. FindProductsService 38 | } 39 | } 40 | 41 | package "eu:happycoders:shop:application:port:out:persistence" { 42 | interface CartRepository<> 43 | interface ProductRepository<> 44 | 45 | AddToCartService --> CartRepository 46 | AddToCartService --> ProductRepository 47 | EmptyCartService --> CartRepository 48 | GetCartService --> CartRepository 49 | 50 | FindProductsService --> ProductRepository 51 | } 52 | 53 | package "eu:happycoders:shop:adapter:out:persistence" { 54 | class InMemoryCartRepository<> {} 55 | class InMemoryProductRepository<> {} 56 | 57 | CartRepository <|.. InMemoryCartRepository 58 | ProductRepository <|.. InMemoryProductRepository 59 | } 60 | @enduml -------------------------------------------------------------------------------- /doc/ports-and-services.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | package "eu:happycoders:shop:application:port:in" { 3 | package "cart" { 4 | interface EmptyCartUseCase<> {} 5 | interface GetCartUseCase<> {} 6 | interface AddToCartUseCase<> {} 7 | } 8 | package "product" { 9 | interface FindProductsUseCase<> {} 10 | } 11 | } 12 | 13 | package "eu:happycoders:shop:application:service" { 14 | package "cart" { 15 | EmptyCartUseCase <|.. EmptyCartService 16 | GetCartUseCase <|.. GetCartService 17 | AddToCartUseCase <|.. AddToCartService 18 | } 19 | package "product" { 20 | FindProductsUseCase <|.. FindProductsService 21 | } 22 | } 23 | 24 | package "eu:happycoders:shop:application:port:out:persistence" { 25 | interface CartRepository<> 26 | interface ProductRepository<> 27 | 28 | AddToCartService --> CartRepository 29 | AddToCartService --> ProductRepository 30 | EmptyCartService --> CartRepository 31 | GetCartService --> CartRepository 32 | 33 | FindProductsService --> ProductRepository 34 | } 35 | @enduml -------------------------------------------------------------------------------- /doc/sample-requests.http: -------------------------------------------------------------------------------- 1 | ### Search for products containing "plastic" 2 | GET http://localhost:8080/products/?query=plastic 3 | 4 | ### Search for products containing "monitor" 5 | GET http://localhost:8080/products/?query=monitor 6 | 7 | ### Invalid search (search query too short) 8 | GET http://localhost:8080/products/?query=x 9 | 10 | ### Get cart 11 | GET http://localhost:8080/carts/61157 12 | 13 | ### Add "Plastic Sheeting" to cart 14 | POST http://localhost:8080/carts/61157/line-items?productId=TTKQ8NJZ&quantity=20 15 | 16 | ### Add "27-Inch Curved Computer Monitor" to cart 17 | POST http://localhost:8080/carts/61157/line-items?productId=K3SR7PBX&quantity=2 18 | 19 | ### Add "Dual Monitor Desk Mount" to cart 20 | POST http://localhost:8080/carts/61157/line-items?productId=Q3W43CNC&quantity=1 21 | 22 | ### Add "50ft Led Lights" to cart 23 | POST http://localhost:8080/carts/61157/line-items?productId=WM3BPG3E&quantity=3 24 | 25 | ### Empty cart 26 | DELETE http://localhost:8080/carts/61157 -------------------------------------------------------------------------------- /doc/shop-model-iteration-1.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | class Cart { 3 | } 4 | 5 | Cart *- CartLineItem 6 | 7 | class CartLineItem { 8 | -quantity : int 9 | } 10 | 11 | CartLineItem -> Product 12 | 13 | class Product { 14 | } 15 | @enduml -------------------------------------------------------------------------------- /doc/shop-model-iteration-2.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | class Cart { 3 | -id : CustomerId 4 | } 5 | 6 | Cart *- CartLineItem 7 | 8 | class CartLineItem { 9 | -quantity : int 10 | } 11 | 12 | CartLineItem -> Product 13 | 14 | class Product { 15 | -id : ProductId 16 | } 17 | @enduml -------------------------------------------------------------------------------- /doc/shop-model-iteration-3.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | class Cart { 3 | -id : CustomerId 4 | } 5 | 6 | Cart *- CartLineItem 7 | 8 | class CartLineItem { 9 | -quantity : int 10 | } 11 | 12 | CartLineItem -> Product 13 | 14 | class Product { 15 | -id : ProductId 16 | -name : String 17 | -description : String 18 | } 19 | 20 | Product --> Money : price 21 | 22 | class Money { 23 | -currency : Currency 24 | -amount : BigDecimal 25 | } 26 | 27 | @enduml -------------------------------------------------------------------------------- /doc/shop-model-iteration-4.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | class Cart { 3 | -id : CustomerId 4 | +addProduct(product : Product, quantity : int) 5 | } 6 | 7 | Cart *- CartLineItem 8 | 9 | class CartLineItem { 10 | -quantity : int 11 | +increaseQuantityBy(value : int) 12 | } 13 | 14 | CartLineItem -> Product 15 | 16 | class Product { 17 | -id : ProductId 18 | -name : String 19 | -description : String 20 | -itemsInStock : int 21 | } 22 | 23 | Product --> Money : price 24 | 25 | class Money { 26 | -currency : Currency 27 | -amount : BigDecimal 28 | } 29 | @enduml -------------------------------------------------------------------------------- /doc/shop-model-iteration-5.plantuml: -------------------------------------------------------------------------------- 1 | @startuml 2 | class Cart { 3 | -id : CustomerId 4 | +addProduct(product : Product, quantity : int) 5 | +numberOfItems() : int 6 | +subTotal() : Money 7 | } 8 | 9 | Cart *- CartLineItem 10 | 11 | class CartLineItem { 12 | -quantity : int 13 | +increaseQuantityBy(value : int) 14 | +subTotal() : Money 15 | } 16 | 17 | CartLineItem -> Product 18 | 19 | class Product { 20 | -id : ProductId 21 | -name : String 22 | -description : String 23 | -itemsInStock : int 24 | } 25 | 26 | Product --> Money : price 27 | 28 | class Money { 29 | -currency : Currency 30 | -amount : BigDecimal 31 | } 32 | @enduml -------------------------------------------------------------------------------- /google_checks.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 57 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 74 | 75 | 76 | 78 | 79 | 80 | 86 | 87 | 88 | 89 | 92 | 93 | 94 | 95 | 96 | 100 | 101 | 102 | 103 | 104 | 106 | 107 | 108 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 129 | 132 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 180 | 181 | 182 | 184 | 186 | 187 | 188 | 189 | 191 | 192 | 193 | 194 | 196 | 197 | 198 | 199 | 201 | 202 | 203 | 204 | 206 | 207 | 208 | 209 | 211 | 212 | 213 | 214 | 216 | 217 | 218 | 219 | 221 | 222 | 223 | 224 | 226 | 227 | 228 | 229 | 231 | 232 | 233 | 234 | 236 | 237 | 238 | 239 | 241 | 242 | 243 | 244 | 246 | 248 | 250 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 282 | 283 | 284 | 287 | 288 | 289 | 290 | 296 | 297 | 298 | 299 | 303 | 304 | 305 | 306 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 321 | 322 | 323 | 324 | 325 | 326 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 345 | 346 | 347 | 350 | 351 | 352 | 353 | 354 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | -------------------------------------------------------------------------------- /img/Java_Versions_PDF_Cheat_Sheet_Mockup_936.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SvenWoltmann/hexagonal-architecture-java/d2240875673207bdea68717e4121a53efdd44277/img/Java_Versions_PDF_Cheat_Sheet_Mockup_936.png -------------------------------------------------------------------------------- /img/big-o-cheat-sheet-pdf-en-transp_936.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SvenWoltmann/hexagonal-architecture-java/d2240875673207bdea68717e4121a53efdd44277/img/big-o-cheat-sheet-pdf-en-transp_936.png -------------------------------------------------------------------------------- /img/mastering-data-structures-product-mockup-cropped-1600.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SvenWoltmann/hexagonal-architecture-java/d2240875673207bdea68717e4121a53efdd44277/img/mastering-data-structures-product-mockup-cropped-1600.png -------------------------------------------------------------------------------- /model/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | eu.happycoders.shop 9 | parent 10 | 1.0-SNAPSHOT 11 | 12 | 13 | model 14 | 15 | 16 | 17 | 18 | 19 | org.apache.maven.plugins 20 | maven-jar-plugin 21 | 22 | 23 | 24 | test-jar 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/cart/Cart.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.cart; 2 | 3 | import eu.happycoders.shop.model.customer.CustomerId; 4 | import eu.happycoders.shop.model.money.Money; 5 | import eu.happycoders.shop.model.product.Product; 6 | import eu.happycoders.shop.model.product.ProductId; 7 | import java.util.LinkedHashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | import lombok.Getter; 11 | import lombok.RequiredArgsConstructor; 12 | import lombok.experimental.Accessors; 13 | 14 | /** 15 | * A shopping cart of a particular customer, containing several line items. 16 | * 17 | * @author Sven Woltmann 18 | */ 19 | @Accessors(fluent = true) 20 | @RequiredArgsConstructor 21 | public class Cart { 22 | 23 | @Getter private final CustomerId id; // cart ID = customer ID 24 | 25 | private final Map lineItems = new LinkedHashMap<>(); 26 | 27 | public void addProduct(Product product, int quantity) throws NotEnoughItemsInStockException { 28 | lineItems 29 | .computeIfAbsent(product.id(), ignored -> new CartLineItem(product)) 30 | .increaseQuantityBy(quantity, product.itemsInStock()); 31 | } 32 | 33 | // Use only for reconstituting a Cart entity from the database 34 | public void putProductIgnoringNotEnoughItemsInStock(Product product, int quantity) { 35 | lineItems.put(product.id(), new CartLineItem(product, quantity)); 36 | } 37 | 38 | public List lineItems() { 39 | return List.copyOf(lineItems.values()); 40 | } 41 | 42 | public int numberOfItems() { 43 | return lineItems.values().stream().mapToInt(CartLineItem::quantity).sum(); 44 | } 45 | 46 | public Money subTotal() { 47 | return lineItems.values().stream().map(CartLineItem::subTotal).reduce(Money::add).orElse(null); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/cart/CartLineItem.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.cart; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | import eu.happycoders.shop.model.product.Product; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Getter; 7 | import lombok.RequiredArgsConstructor; 8 | import lombok.experimental.Accessors; 9 | 10 | /** 11 | * A shopping cart line item with a product and quantity. 12 | * 13 | * @author Sven Woltmann 14 | */ 15 | @Getter 16 | @Accessors(fluent = true) 17 | @RequiredArgsConstructor 18 | @AllArgsConstructor 19 | public class CartLineItem { 20 | 21 | private final Product product; 22 | private int quantity; 23 | 24 | public void increaseQuantityBy(int augend, int itemsInStock) 25 | throws NotEnoughItemsInStockException { 26 | if (augend < 1) { 27 | throw new IllegalArgumentException("You must add at least one item"); 28 | } 29 | 30 | int newQuantity = quantity + augend; 31 | if (itemsInStock < newQuantity) { 32 | throw new NotEnoughItemsInStockException( 33 | "Product %s has less items in stock (%d) than the requested total quantity (%d)" 34 | .formatted(product.id(), product.itemsInStock(), newQuantity), 35 | product.itemsInStock()); 36 | } 37 | 38 | this.quantity = newQuantity; 39 | } 40 | 41 | public Money subTotal() { 42 | return product.price().multiply(quantity); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/cart/NotEnoughItemsInStockException.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.cart; 2 | 3 | /** 4 | * An exception indicating that a customer wanted to add more items of a product to the cart than 5 | * were available. 6 | * 7 | * @author Sven Woltmann 8 | */ 9 | public class NotEnoughItemsInStockException extends Exception { 10 | 11 | private final int itemsInStock; 12 | 13 | public NotEnoughItemsInStockException(String message, int itemsInStock) { 14 | super(message); 15 | this.itemsInStock = itemsInStock; 16 | } 17 | 18 | public int itemsInStock() { 19 | return itemsInStock; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/customer/CustomerId.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.customer; 2 | 3 | /** 4 | * A customer ID value object (enabling type-safety and validation). 5 | * 6 | * @author Sven Woltmann 7 | */ 8 | public record CustomerId(int value) { 9 | 10 | public CustomerId { 11 | if (value < 1) { 12 | throw new IllegalArgumentException("'value' must be a positive integer"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/money/Money.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.money; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.Currency; 5 | import java.util.Objects; 6 | 7 | /** 8 | * A money value object consisting of a currency and an amount. 9 | * 10 | * @author Sven Woltmann 11 | */ 12 | public record Money(Currency currency, BigDecimal amount) { 13 | 14 | public Money { 15 | Objects.requireNonNull(currency, "'currency' must not be null"); 16 | Objects.requireNonNull(amount, "'amount' must not be null"); 17 | if (amount.scale() > currency.getDefaultFractionDigits()) { 18 | throw new IllegalArgumentException( 19 | "Scale of amount %s is greater than the number of fraction digits used with currency %s" 20 | .formatted(amount, currency)); 21 | } 22 | } 23 | 24 | public static Money of(Currency currency, int mayor, int minor) { 25 | int scale = currency.getDefaultFractionDigits(); 26 | return new Money(currency, BigDecimal.valueOf(mayor).add(BigDecimal.valueOf(minor, scale))); 27 | } 28 | 29 | public Money multiply(int multiplicand) { 30 | return new Money(currency, amount.multiply(BigDecimal.valueOf(multiplicand))); 31 | } 32 | 33 | public Money add(Money augend) { 34 | if (!this.currency.equals(augend.currency())) { 35 | throw new IllegalArgumentException( 36 | "Currency %s of augend does not match this money's currency %s" 37 | .formatted(augend.currency(), this.currency)); 38 | } 39 | 40 | return new Money(currency, amount.add(augend.amount())); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/product/Product.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.product; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.experimental.Accessors; 7 | 8 | /** 9 | * A product listed in the shop. 10 | * 11 | * @author Sven Woltmann 12 | */ 13 | @Data 14 | @Accessors(fluent = true) 15 | @AllArgsConstructor 16 | public class Product { 17 | 18 | private final ProductId id; 19 | private String name; 20 | private String description; 21 | private Money price; 22 | private int itemsInStock; 23 | } 24 | -------------------------------------------------------------------------------- /model/src/main/java/eu/happycoders/shop/model/product/ProductId.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.product; 2 | 3 | import java.util.Objects; 4 | import java.util.concurrent.ThreadLocalRandom; 5 | 6 | /** 7 | * A product ID value object (enabling type-safety and validation). 8 | * 9 | * @author Sven Woltmann 10 | */ 11 | public record ProductId(String value) { 12 | 13 | private static final String ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; 14 | private static final int LENGTH_OF_NEW_PRODUCT_IDS = 8; 15 | 16 | public ProductId { 17 | Objects.requireNonNull(value, "'value' must not be null"); 18 | if (value.isEmpty()) { 19 | throw new IllegalArgumentException("'value' must not be empty"); 20 | } 21 | } 22 | 23 | public static ProductId randomProductId() { 24 | ThreadLocalRandom random = ThreadLocalRandom.current(); 25 | char[] chars = new char[LENGTH_OF_NEW_PRODUCT_IDS]; 26 | for (int i = 0; i < LENGTH_OF_NEW_PRODUCT_IDS; i++) { 27 | chars[i] = ALPHABET.charAt(random.nextInt(ALPHABET.length())); 28 | } 29 | return new ProductId(new String(chars)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/cart/CartTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.cart; 2 | 3 | import static eu.happycoders.shop.model.cart.TestCartFactory.emptyCartForRandomCustomer; 4 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 7 | import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 8 | import static org.assertj.core.api.Assertions.assertThatNoException; 9 | 10 | import eu.happycoders.shop.model.product.Product; 11 | import eu.happycoders.shop.model.product.TestProductFactory; 12 | import org.assertj.core.api.ThrowableAssert.ThrowingCallable; 13 | import org.junit.jupiter.api.Test; 14 | import org.junit.jupiter.params.ParameterizedTest; 15 | import org.junit.jupiter.params.provider.ValueSource; 16 | 17 | class CartTest { 18 | 19 | @Test 20 | void givenEmptyCart_addTwoProducts_productsAreInCart() throws NotEnoughItemsInStockException { 21 | Cart cart = emptyCartForRandomCustomer(); 22 | 23 | Product product1 = TestProductFactory.createTestProduct(euros(12, 99)); 24 | Product product2 = TestProductFactory.createTestProduct(euros(5, 97)); 25 | 26 | cart.addProduct(product1, 3); 27 | cart.addProduct(product2, 5); 28 | 29 | assertThat(cart.lineItems()).hasSize(2); 30 | assertThat(cart.lineItems().get(0).product()).isEqualTo(product1); 31 | assertThat(cart.lineItems().get(0).quantity()).isEqualTo(3); 32 | assertThat(cart.lineItems().get(1).product()).isEqualTo(product2); 33 | assertThat(cart.lineItems().get(1).quantity()).isEqualTo(5); 34 | } 35 | 36 | @Test 37 | void givenEmptyCart_addTwoProducts_numberOfItemsAndSubTotalIsCalculatedCorrectly() 38 | throws NotEnoughItemsInStockException { 39 | Cart cart = emptyCartForRandomCustomer(); 40 | 41 | Product product1 = TestProductFactory.createTestProduct(euros(12, 99)); 42 | Product product2 = TestProductFactory.createTestProduct(euros(5, 97)); 43 | 44 | cart.addProduct(product1, 3); 45 | cart.addProduct(product2, 5); 46 | 47 | assertThat(cart.numberOfItems()).isEqualTo(8); 48 | assertThat(cart.subTotal()).isEqualTo(euros(68, 82)); 49 | } 50 | 51 | @Test 52 | void givenAProductWithAFewItemsAvailable_addMoreItemsThanAvailableToTheCart_throwsException() { 53 | Cart cart = emptyCartForRandomCustomer(); 54 | Product product = TestProductFactory.createTestProduct(euros(9, 97), 3); 55 | 56 | ThrowingCallable invocation = () -> cart.addProduct(product, 4); 57 | 58 | assertThatExceptionOfType(NotEnoughItemsInStockException.class) 59 | .isThrownBy(invocation) 60 | .satisfies(ex -> assertThat(ex.itemsInStock()).isEqualTo(product.itemsInStock())); 61 | } 62 | 63 | @Test 64 | void givenAProductWithAFewItemsAvailable_addAllAvailableItemsToTheCart_succeeds() { 65 | Cart cart = emptyCartForRandomCustomer(); 66 | Product product = TestProductFactory.createTestProduct(euros(9, 97), 3); 67 | 68 | ThrowingCallable invocation = () -> cart.addProduct(product, 3); 69 | 70 | assertThatNoException().isThrownBy(invocation); 71 | } 72 | 73 | @ParameterizedTest 74 | @ValueSource(ints = {-100, -1, 0}) 75 | void givenEmptyCart_addLessThanOneItemOfAProduct_throwsException(int quantity) { 76 | Cart cart = emptyCartForRandomCustomer(); 77 | Product product = TestProductFactory.createTestProduct(euros(1, 49)); 78 | 79 | ThrowingCallable invocation = () -> cart.addProduct(product, quantity); 80 | 81 | assertThatIllegalArgumentException().isThrownBy(invocation); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/cart/TestCartFactory.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.cart; 2 | 3 | import eu.happycoders.shop.model.customer.CustomerId; 4 | import java.util.concurrent.ThreadLocalRandom; 5 | 6 | public class TestCartFactory { 7 | 8 | public static Cart emptyCartForRandomCustomer() { 9 | return new Cart(new CustomerId(ThreadLocalRandom.current().nextInt(1_000_000))); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/customer/CustomerIdTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.customer; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 5 | 6 | import org.assertj.core.api.ThrowableAssert; 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.ValueSource; 9 | 10 | class CustomerIdTest { 11 | @ParameterizedTest 12 | @ValueSource(ints = {-100, -1, 0}) 13 | void givenAValueLessThan1_newCustomerId_throwsException(int value) { 14 | ThrowableAssert.ThrowingCallable invocation = () -> new CustomerId(value); 15 | 16 | assertThatIllegalArgumentException().isThrownBy(invocation); 17 | } 18 | 19 | @ParameterizedTest 20 | @ValueSource(ints = {1, 8_765, 2_000_000_000}) 21 | void givenAValueGreatThanOrEqualTo1_newCustomerId_succeeds(int value) { 22 | CustomerId customerId = new CustomerId(value); 23 | 24 | assertThat(customerId.value()).isEqualTo(value); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/money/MoneyTest.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.money; 2 | 3 | import static eu.happycoders.shop.model.money.TestMoneyFactory.euros; 4 | import static eu.happycoders.shop.model.money.TestMoneyFactory.usDollars; 5 | import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 6 | 7 | import java.math.BigDecimal; 8 | import java.math.BigInteger; 9 | import java.util.Currency; 10 | import org.assertj.core.api.ThrowableAssert.ThrowingCallable; 11 | import org.junit.jupiter.api.Test; 12 | 13 | class MoneyTest { 14 | 15 | private static final Currency EUR = Currency.getInstance("EUR"); 16 | 17 | @Test 18 | void givenAmountWithAnInvalidScale_newMoney_throwsIllegalArgumentException() { 19 | BigDecimal amountWithScale3 = new BigDecimal(BigInteger.valueOf(12999), 3); 20 | 21 | ThrowingCallable invocation = () -> new Money(EUR, amountWithScale3); 22 | 23 | assertThatIllegalArgumentException().isThrownBy(invocation); 24 | } 25 | 26 | @Test 27 | void givenAEuroAmount_addADollarAmount_throwsIllegalArgumentException() { 28 | Money euros = euros(11, 99); 29 | Money dollars = usDollars(11, 99); 30 | 31 | ThrowingCallable invocation = () -> euros.add(dollars); 32 | 33 | assertThatIllegalArgumentException().isThrownBy(invocation); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/money/TestMoneyFactory.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.money; 2 | 3 | import java.util.Currency; 4 | 5 | public class TestMoneyFactory { 6 | 7 | private static final Currency EUR = Currency.getInstance("EUR"); 8 | private static final Currency USD = Currency.getInstance("USD"); 9 | 10 | public static Money euros(int euros, int cents) { 11 | return Money.of(EUR, euros, cents); 12 | } 13 | 14 | public static Money usDollars(int dollars, int cents) { 15 | return Money.of(USD, dollars, cents); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /model/src/test/java/eu/happycoders/shop/model/product/TestProductFactory.java: -------------------------------------------------------------------------------- 1 | package eu.happycoders.shop.model.product; 2 | 3 | import eu.happycoders.shop.model.money.Money; 4 | 5 | public class TestProductFactory { 6 | 7 | private static final int ENOUGH_ITEMS_IN_STOCK = Integer.MAX_VALUE; 8 | 9 | public static Product createTestProduct(Money price) { 10 | return createTestProduct(price, ENOUGH_ITEMS_IN_STOCK); 11 | } 12 | 13 | public static Product createTestProduct(Money price, int itemsInStock) { 14 | return new Product( 15 | ProductId.randomProductId(), // 16 | "any name", 17 | "any description", 18 | price, 19 | itemsInStock); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | PMD ruleset for HappyCoders.eu (relaxed for Hexagonal Architecture tutorial) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | eu.happycoders.shop 8 | parent 9 | 1.0-SNAPSHOT 10 | 11 | pom 12 | 13 | 14 | model 15 | application 16 | adapter 17 | bootstrap 18 | 19 | 20 | 21 | 20 22 | 20 23 | UTF-8 24 | 25 | 6.55.0 26 | 27 | 28 | SvenWoltmann_hexagonal-architecture-java 29 | hexagonal-architecture-java:${project.artifactId} 30 | svenwoltmann 31 | https://sonarcloud.io 32 | 33 | target/spotbugsXml.xml 34 | target/pmd.xml 35 | target/checkstyle-result.xml 36 | ${project.basedir}/../bootstrap/target/site/jacoco-aggregate/jacoco.xml 37 | 38 | 39 | 40 | 41 | 42 | org.projectlombok 43 | lombok 44 | 1.18.30 45 | provided 46 | 47 | 48 | 49 | 50 | org.junit.jupiter 51 | junit-jupiter 52 | 5.10.0 53 | test 54 | 55 | 56 | org.assertj 57 | assertj-core 58 | 3.24.2 59 | test 60 | 61 | 62 | org.mockito 63 | mockito-core 64 | 5.5.0 65 | test 66 | 67 | 68 | 69 | 70 | 71 | 72 | com.tngtech.archunit 73 | archunit-junit5 74 | 1.1.0 75 | 76 | 77 | mysql 78 | mysql-connector-java 79 | 8.0.33 80 | 81 | 82 | io.rest-assured 83 | rest-assured 84 | 5.3.2 85 | 86 | 87 | jakarta.persistence 88 | jakarta.persistence-api 89 | 3.1.0 90 | 91 | 92 | jakarta.ws.rs 93 | jakarta.ws.rs-api 94 | 3.1.0 95 | 96 | 97 | org.glassfish 98 | jakarta.el 99 | 5.0.0-M1 100 | 101 | 102 | org.hibernate.orm 103 | hibernate-core 104 | 6.3.1.Final 105 | 106 | 107 | org.hibernate.validator 108 | hibernate-validator 109 | 8.0.1.Final 110 | 111 | 112 | org.jboss.resteasy 113 | resteasy-undertow 114 | 6.2.5.Final 115 | 116 | 117 | org.jboss.resteasy 118 | resteasy-jackson2-provider 119 | 6.2.5.Final 120 | 121 | 122 | org.testcontainers 123 | mysql 124 | 1.19.0 125 | 126 | 127 | 128 | 129 | 130 | 131 | 133 | 134 | org.apache.maven.plugins 135 | maven-compiler-plugin 136 | 3.11.0 137 | 138 | 139 | org.apache.maven.plugins 140 | maven-surefire-plugin 141 | 3.1.0 142 | 143 | 144 | com.diffplug.spotless 145 | spotless-maven-plugin 146 | 2.36.0 147 | 148 | 149 | 150 | 151 | 1.17.0 152 | 153 | 154 | UNIX 155 | 156 | 157 | 158 | 159 | 160 | check 161 | 162 | validate 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | org.apache.maven.plugins 172 | maven-jar-plugin 173 | 3.3.0 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | test-coverage 183 | 184 | 185 | 186 | 187 | org.jacoco 188 | jacoco-maven-plugin 189 | 0.8.10 190 | 191 | 192 | prepare-agent 193 | 194 | prepare-agent 195 | 196 | 197 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | code-analysis 208 | 209 | 210 | 211 | 212 | com.github.spotbugs 213 | spotbugs-maven-plugin 214 | 4.7.3.4 215 | 216 | spotbugs-exclude.xml 217 | 218 | 219 | 220 | 221 | spotbugs 222 | 223 | verify 224 | 225 | 226 | 227 | 228 | 229 | 230 | org.apache.maven.plugins 231 | maven-pmd-plugin 232 | 3.21.0 233 | 234 | 19 235 | 236 | pmd-ruleset.xml 237 | 238 | 239 | 240 | 241 | net.sourceforge.pmd 242 | pmd-core 243 | ${pmd.version} 244 | 245 | 246 | net.sourceforge.pmd 247 | pmd-java 248 | ${pmd.version} 249 | 250 | 251 | 252 | 253 | 254 | pmd 255 | 256 | verify 257 | 258 | 259 | 260 | 261 | 262 | 263 | org.apache.maven.plugins 264 | maven-checkstyle-plugin 265 | 3.3.0 266 | 267 | ./google_checks.xml 268 | 269 | 270 | 271 | com.puppycrawl.tools 272 | checkstyle 273 | 10.12.0 274 | 275 | 276 | 277 | 278 | 279 | check 280 | 281 | verify 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | -------------------------------------------------------------------------------- /spotbugs-exclude.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------