diff --git a/.all-contributorsrc b/.all-contributorsrc index b2fef6640890..ccc740df15e1 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -2891,7 +2891,7 @@ "login": "ved-asole", "name": "Ved Asole", "avatar_url": "https://avatars.githubusercontent.com/u/77259804?v=4", - "profile": "http://vedasole.cloud", + "profile": "https://github.com/ved-asole", "contributions": [ "code" ] @@ -3493,6 +3493,313 @@ "contributions": [ "code" ] + }, + { + "login": "ssrijan-007-sys", + "name": "ssrijan-007-sys", + "avatar_url": "https://avatars.githubusercontent.com/u/137605821?v=4", + "profile": "https://github.com/ssrijan-007-sys", + "contributions": [ + "code" + ] + }, + { + "login": "e5LA", + "name": "e5LA", + "avatar_url": "https://avatars.githubusercontent.com/u/208197507?v=4", + "profile": "https://github.com/e5LA", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "maziyar-gerami", + "name": "Maziyar Gerami", + "avatar_url": "https://avatars.githubusercontent.com/u/122622721?v=4", + "profile": "http://maziyar-gerami.github.io/portfolio/", + "contributions": [ + "translation" + ] + }, + { + "login": "yybmion", + "name": "yoobin_mion", + "avatar_url": "https://avatars.githubusercontent.com/u/113106136?v=4", + "profile": "https://github.com/yybmion", + "contributions": [ + "code" + ] + }, + { + "login": "ronodhirSoumik", + "name": "Soumik Sarker", + "avatar_url": "https://avatars.githubusercontent.com/u/46843689?v=4", + "profile": "https://ronodhirsoumik.github.io", + "contributions": [ + "doc" + ] + }, + { + "login": "naman-sriv", + "name": "Naman Srivastava", + "avatar_url": "https://avatars.githubusercontent.com/u/82610773?v=4", + "profile": "https://github.com/naman-sriv", + "contributions": [ + "code" + ] + }, + { + "login": "letdtcode", + "name": "Thanh Nguyen Duc", + "avatar_url": "https://avatars.githubusercontent.com/u/92111552?v=4", + "profile": "https://github.com/letdtcode", + "contributions": [ + "code" + ] + }, + { + "login": "skamble2", + "name": "Soham Kamble", + "avatar_url": "https://avatars.githubusercontent.com/u/121136639?v=4", + "profile": "https://github.com/skamble2", + "contributions": [ + "code" + ] + }, + { + "login": "Olexandr88", + "name": "Olexandr88", + "avatar_url": "https://avatars.githubusercontent.com/u/93856062?v=4", + "profile": "https://github.com/Olexandr88", + "contributions": [ + "doc" + ] + }, + { + "login": "nilsreichardt", + "name": "Nils Reichardt", + "avatar_url": "https://avatars.githubusercontent.com/u/24459435?v=4", + "profile": "https://github.com/nilsreichardt", + "contributions": [ + "security" + ] + }, + { + "login": "north-echo", + "name": "Christopher Lusk", + "avatar_url": "https://avatars.githubusercontent.com/u/122107484?v=4", + "profile": "http://www.northecho.dev", + "contributions": [ + "security" + ] + }, + { + "login": "dagecko", + "name": "dagecko", + "avatar_url": "https://avatars.githubusercontent.com/u/6371704?v=4", + "profile": "https://github.com/dagecko", + "contributions": [ + "security" + ] + }, + { + "login": "jackmisbach", + "name": "jackmisbach", + "avatar_url": "https://avatars.githubusercontent.com/u/183796460?v=4", + "profile": "https://github.com/jackmisbach", + "contributions": [ + "security" + ] + }, + { + "login": "avivdon", + "name": "avivdon", + "avatar_url": "https://avatars.githubusercontent.com/u/74790003?v=4", + "profile": "https://github.com/avivdon", + "contributions": [ + "security" + ] + }, + { + "login": "quantdevv", + "name": "Aditya Kumawat", + "avatar_url": "https://avatars.githubusercontent.com/u/56085648?v=4", + "profile": "https://github.com/quantdevv", + "contributions": [ + "code" + ] + }, + { + "login": "devch37", + "name": "devch37", + "avatar_url": "https://avatars.githubusercontent.com/u/72903623?v=4", + "profile": "https://github.com/devch37", + "contributions": [ + "code" + ] + }, + { + "login": "HY-love-sleep", + "name": "HY-love-sleep", + "avatar_url": "https://avatars.githubusercontent.com/u/73268470?v=4", + "profile": "https://github.com/HY-love-sleep", + "contributions": [ + "code" + ] + }, + { + "login": "CMD137", + "name": "CMD137", + "avatar_url": "https://avatars.githubusercontent.com/u/56242956?v=4", + "profile": "http://www.cmd137blog.top/", + "contributions": [ + "code" + ] + }, + { + "login": "QuantumRange", + "name": "QuantumRange", + "avatar_url": "https://avatars.githubusercontent.com/u/49843948?v=4", + "profile": "https://github.com/QuantumRange", + "contributions": [ + "doc" + ] + }, + { + "login": "Dhiraj-birajdar", + "name": "Dhiraj Birajdar", + "avatar_url": "https://avatars.githubusercontent.com/u/114354331?v=4", + "profile": "https://github.com/Dhiraj-birajdar", + "contributions": [ + "doc" + ] + }, + { + "login": "sieberss", + "name": "Stefan Siebers", + "avatar_url": "https://avatars.githubusercontent.com/u/178474619?v=4", + "profile": "https://github.com/sieberss", + "contributions": [ + "translation" + ] + }, + { + "login": "orbisai0security", + "name": "OrbisAI Security", + "avatar_url": "https://avatars.githubusercontent.com/u/242526317?v=4", + "profile": "https://orbisappsec.com/", + "contributions": [ + "security" + ] + }, + { + "login": "rranjangupta", + "name": "Raju Gupta", + "avatar_url": "https://avatars.githubusercontent.com/u/64011583?v=4", + "profile": "https://www.rajugupta.com/portfolio/", + "contributions": [ + "code" + ] + }, + { + "login": "alex052525", + "name": "김정모", + "avatar_url": "https://avatars.githubusercontent.com/u/116088682?v=4", + "profile": "https://github.com/alex052525", + "contributions": [ + "code" + ] + }, + { + "login": "AnakinYen0329", + "name": "Anakin Yen", + "avatar_url": "https://avatars.githubusercontent.com/u/122139183?v=4", + "profile": "https://github.com/AnakinYen0329", + "contributions": [ + "translation" + ] + }, + { + "login": "SrGiuliano77", + "name": "Giuliano Oliveira", + "avatar_url": "https://avatars.githubusercontent.com/u/128543464?v=4", + "profile": "https://github.com/SrGiuliano77", + "contributions": [ + "translation" + ] + }, + { + "login": "priyanshuvishwakarma273403", + "name": "Priyanshu", + "avatar_url": "https://avatars.githubusercontent.com/u/222148451?v=4", + "profile": "https://www.priyanshu-portfolio.co.in", + "contributions": [ + "code" + ] + }, + { + "login": "arnabnandy7", + "name": "Arnab Nandy", + "avatar_url": "https://avatars.githubusercontent.com/u/5053648?v=4", + "profile": "https://github.com/arnabnandy-cognizant", + "contributions": [ + "doc" + ] + }, + { + "login": "MohamedMBG", + "name": "BAGHDAD Mohamed", + "avatar_url": "https://avatars.githubusercontent.com/u/123114744?v=4", + "profile": "https://github.com/MohamedMBG", + "contributions": [ + "code" + ] + }, + { + "login": "AnveshSrivastava", + "name": "Anvesh Srivastava", + "avatar_url": "https://avatars.githubusercontent.com/u/170334970?v=4", + "profile": "https://github.com/AnveshSrivastava", + "contributions": [ + "code" + ] + }, + { + "login": "Mukul-Howale", + "name": "Mukul Howale", + "avatar_url": "https://avatars.githubusercontent.com/u/110479646?v=4", + "profile": "https://github.com/Mukul-Howale", + "contributions": [ + "code" + ] + }, + { + "login": "SandhyaDevadiga", + "name": "Sandhya", + "avatar_url": "https://avatars.githubusercontent.com/u/128058717?v=4", + "profile": "https://github.com/SandhyaDevadiga", + "contributions": [ + "code" + ] + }, + { + "login": "devikae", + "name": "dev-ikae", + "avatar_url": "https://avatars.githubusercontent.com/u/98100047?v=4", + "profile": "https://github.com/devikae", + "contributions": [ + "code" + ] + }, + { + "login": "zanarellidev", + "name": "zanarelli", + "avatar_url": "https://avatars.githubusercontent.com/u/268068569?v=4", + "profile": "https://github.com/zanarellidev", + "contributions": [ + "translation" + ] } ], "contributorsPerLine": 6, diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml index 5d2812e72fb7..00ad59c7dab2 100644 --- a/.github/workflows/maven-ci.yml +++ b/.github/workflows/maven-ci.yml @@ -50,4 +50,9 @@ jobs: env: # These two env variables are needed for sonar analysis GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} \ No newline at end of file + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index 99ee85152962..149733343781 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -1,7 +1,7 @@ name: Java PR Builder on: - pull_request_target: + pull_request: branches: [ master ] types: [ opened, reopened, synchronize ] @@ -17,8 +17,6 @@ jobs: - name: Checkout Code uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.sha }} - name: Set up JDK 21 uses: actions/setup-java@v4 @@ -35,23 +33,14 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - # Cache Sonar packages which are used to run analysis and collect metrics - - name: Cache SonarCloud packages - uses: actions/cache@v4 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - # Some tests need screen access - name: Install xvfb run: sudo apt-get install -y xvfb - - name: Build with Maven and run SonarQube analysis - env: - # Intermediate variable - HEAD_REF: ${{ github.head_ref }} - # These two env variables are needed for sonar analysis - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: xvfb-run ./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=iluwatar -Dsonar.projectKey=iluwatar_java-design-patterns -Dsonar.pullrequest.branch=$HEAD_REF -Dsonar.pullrequest.base=${{ github.base_ref }} -Dsonar.pullrequest.key=${{ github.event.pull_request.number }} \ No newline at end of file + - name: Build with Maven + run: xvfb-run ./mvnw clean verify + + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/presubmit.yml b/.github/workflows/presubmit.yml index cac1250b70e8..bb0ed7e116ae 100644 --- a/.github/workflows/presubmit.yml +++ b/.github/workflows/presubmit.yml @@ -1,35 +1,28 @@ name: Presubmit.ai permissions: - contents: read - pull-requests: write - issues: write + contents: read + pull-requests: write + issues: write on: - pull_request_target: # Handle forked repository PRs in the base repository context - types: [opened, synchronize] - pull_request_review_comment: # Handle review comments - types: [created] + pull_request_target: + types: [opened, synchronize] + pull_request_review_comment: + types: [created] jobs: - review: - runs-on: ubuntu-latest - steps: - - name: Check required secrets - run: | - if [ -z "${{ secrets.LLM_API_KEY }}" ]; then - echo "Error: LLM_API_KEY secret is not configured" - exit 1 - fi - - - name: Check out PR code - uses: actions/checkout@v3 - with: - ref: ${{ github.event.pull_request.head.sha }} - - - name: Run AI Reviewer - uses: presubmit/ai-reviewer@latest - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - LLM_API_KEY: ${{ secrets.LLM_API_KEY }} - LLM_MODEL: "gemini-1.5-flash" + review: + runs-on: ubuntu-latest + steps: + - name: Check required secrets + run: | + if [ -z "${{ secrets.LLM_API_KEY }}" ]; then + echo "Error: LLM_API_KEY secret is not configured" + exit 1 + fi + - uses: presubmit/ai-reviewer@latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + LLM_API_KEY: ${{ secrets.LLM_API_KEY }} + LLM_MODEL: "gpt-5-nano" \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000000..b30cbdd19b06 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,51 @@ +# Java Design Patterns - Priming Context for AI Agents + +## Quick Overview +- This repository is a comprehensive collection of design patterns implemented in Java. +- The project demonstrates how to solve common software design problems using standard patterns. +- The code for each pattern lives directly in this repository, alongside its explanatory README. +- These readmes are published on the java-design-patterns.com website. +- Another repository (https://github.com/iluwatar/java-design-patterns-vuepress-web) handles the deployment of the website. + +## Stack +- **Java 21**: The primary programming language used for pattern implementations. +- **Maven**: Dependency management and build tool. +- **JUnit 5**: The testing framework used to verify pattern behaviors. +- **Mockito**: Used for mocking dependencies in unit tests. +- **Lombok**: Used to reduce boilerplate code (getters, setters, etc.). +- **Spotless**: Enforces consistent code formatting via Google Java Format. + +## Trusted Sources +- [Java SE 21 Documentation](https://docs.oracle.com/en/java/javase/21/docs/api/) +- [Maven Official Documentation](https://maven.apache.org/guides/index.html) +- [JUnit 5 User Guide](https://junit.org/junit5/docs/current/user-guide/) +- [Project Wiki](https://github.com/iluwatar/java-design-patterns/wiki) + +## Structure +- `/pom.xml`: The root Maven configuration file that defines global dependencies and lists all pattern modules. +- `/[pattern-name]/`: Individual folders for each design pattern (e.g., `/abstract-factory`, `/builder`), acting as standalone Maven modules. +- `/[pattern-name]/src/main/java/`: Contains the actual Java implementation classes of the specific design pattern. +- `/[pattern-name]/src/test/java/`: Contains the JUnit tests verifying the pattern's behavior. +- `/[pattern-name]/README.md`: The documentation for the pattern, which gets published to the main website. + +## Patterns +- Keep pattern implementations simple, atomic, and easy to understand. +- Write descriptive and meaningful names for classes, interfaces, and methods. +- Always include comprehensive unit tests for every new pattern or code modification. +- Follow the Google Java Format strictly (enforced by Spotless). +- Document the intent, explanation, and real-world usage clearly in each module's `README.md`. + +## Anti-patterns +- Avoid overcomplicating patterns with unnecessary external dependencies or complex frameworks. +- Do not introduce business logic that distracts from the core mechanism of the design pattern itself. +- Submitting new patterns or features without corresponding unit tests is strictly discouraged. +- Avoid large monolithic packages; each pattern should reside in its own isolated module. + +## Example Design Pattern +When a new design pattern is added to the repository, it generally follows these steps: +- **Create a Module**: Create a new folder for the pattern in the root directory (e.g., `/my-new-pattern`). +- **Update root pom.xml**: Add `my-new-pattern` to the `` section of the root `pom.xml`. +- **Add Module pom.xml**: Create a `pom.xml` inside the new folder that inherits from the parent project. +- **Write the Code**: Implement the pattern logic under `src/main/java/com/iluwatar/mynewpattern`, usually including an `App.java` class to demonstrate its usage. +- **Write the Tests**: Add comprehensive unit tests under `src/test/java/com/iluwatar/mynewpattern`. +- **Document**: Create a `README.md` at the root of the new module, structured with standard sections like Intent, Explanation, Class diagram, Applicability, and Real world examples. diff --git a/README.md b/README.md index 881563902e26..eb821177e73e 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,18 @@ # Design Patterns Implemented in Java -![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg)](https://github.com/iluwatar/java-design-patterns/actions/workflows/maven-ci.yml) [![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) [![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-383-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-417-orange.svg?style=flat-square)](#contributors-)
-Read in different language : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md), [**da**](localization/da/README.md) +Read in different language : [**zh**](localization/zh/README.md), [**zh-TW**](localization/zh-TW/README.md) +,[**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md), [**da**](localization/da/README.md)
# Introduction @@ -45,7 +46,7 @@ If you are willing to contribute to the project you will find the relevant infor # The Book -The design patterns are now available as an e-book. Find out more about "Open Source Java Design Patterns" here: https://payhip.com/b/kcaF9 +The design patterns are now available as an e-book. Find out more about "Open Source Java Design Patterns" here: https://payhip.com/b/bNQFX The project contributors can get the book for free. Contact the maintainer via [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns) or email (iluwatar (at) gmail (dot) com ). Send a message that contains your email address, Github username, and a link to an accepted pull request. @@ -481,7 +482,7 @@ This project is licensed under the terms of the MIT license. Jakub Klimek
Jakub Klimek

💻 believe
believe

🌍 egg0102030405
egg0102030405

🌍 📖 - Ved Asole
Ved Asole

💻 + Ved Asole
Ved Asole

💻 NewMorning
NewMorning

🌍 @@ -570,6 +571,52 @@ This project is licensed under the terms of the MIT license. Sanura Hettiarachchi
Sanura Hettiarachchi

💻 Kim Gi Uk
Kim Gi Uk

💻 Suchismita Deb
Suchismita Deb

💻 + ssrijan-007-sys
ssrijan-007-sys

💻 + + + e5LA
e5LA

💻 📖 + Maziyar Gerami
Maziyar Gerami

🌍 + yoobin_mion
yoobin_mion

💻 + Soumik Sarker
Soumik Sarker

📖 + Naman Srivastava
Naman Srivastava

💻 + Thanh Nguyen Duc
Thanh Nguyen Duc

💻 + + + Soham Kamble
Soham Kamble

💻 + Olexandr88
Olexandr88

📖 + Nils Reichardt
Nils Reichardt

🛡️ + Christopher Lusk
Christopher Lusk

🛡️ + dagecko
dagecko

🛡️ + jackmisbach
jackmisbach

🛡️ + + + avivdon
avivdon

🛡️ + Aditya Kumawat
Aditya Kumawat

💻 + devch37
devch37

💻 + HY-love-sleep
HY-love-sleep

💻 + CMD137
CMD137

💻 + QuantumRange
QuantumRange

📖 + + + Dhiraj Birajdar
Dhiraj Birajdar

📖 + Stefan Siebers
Stefan Siebers

🌍 + OrbisAI Security
OrbisAI Security

🛡️ + Raju Gupta
Raju Gupta

💻 + 김정모
김정모

💻 + Anakin Yen
Anakin Yen

🌍 + + + Giuliano Oliveira
Giuliano Oliveira

🌍 + Priyanshu
Priyanshu

💻 + Arnab Nandy
Arnab Nandy

📖 + BAGHDAD Mohamed
BAGHDAD Mohamed

💻 + Anvesh Srivastava
Anvesh Srivastava

💻 + Mukul Howale
Mukul Howale

💻 + + + Sandhya
Sandhya

💻 + dev-ikae
dev-ikae

💻 + zanarelli
zanarelli

🌍 diff --git a/actor-model/README.md b/actor-model/README.md new file mode 100644 index 000000000000..be8065ffefef --- /dev/null +++ b/actor-model/README.md @@ -0,0 +1,201 @@ +--- +title: "Actor Model Pattern in Java: Building Concurrent Systems with Elegance" +shortTitle: Actor Model +description: "Explore the Actor Model pattern in Java with real-world examples and practical implementation. Learn how to build scalable, message-driven systems using actors, messages, and asynchronous communication." +category: Concurrency +language: en +tag: + - Concurrency + - Messaging + - Isolation + - Asynchronous + - Distributed Systems + - Actor Model +--- + +## Also Known As + +- Message-passing concurrency +- Actor-based concurrency + +--- + +## Intent of Actor Model Pattern + +The Actor Model pattern enables the construction of highly concurrent, distributed, and fault-tolerant systems by using isolated components (actors) that interact exclusively through asynchronous message passing. + +--- + +## Detailed Explanation of Actor Model Pattern with Real-World Examples + +### 📦 Real-world Example + +Imagine a customer service system: +- Each **customer support agent** is an **actor**. +- Customers **send questions (messages)** to agents. +- Each agent handles one request at a time and can **respond asynchronously** without interfering with other agents. + +--- + +### 🧠 In Plain Words + +> "Actors are like independent workers that never share memory and only communicate through messages." + +--- + +### 📖 Wikipedia Says + +> [Actor model](https://en.wikipedia.org/wiki/Actor_model) is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation. + +--- + +### 🧹 Architecture Diagram + +![UML Class Diagram](./etc/Actor_Model_UML_Class_Diagram.png) + +--- + +## Programmatic Example of Actor Model Pattern in Java + +### Actor.java + +```java +public abstract class Actor implements Runnable { + + @Setter @Getter private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = true; + + + public void send(Message message) { + mailbox.add(message); + } + + public void stop() { + active = false; + } + + @Override + public void run() { + + } + + protected abstract void onReceive(Message message); +} + +``` + +### Message.java + +```java + +@AllArgsConstructor +@Getter +@Setter +public class Message { + private final String content; + private final String senderId; +} +``` + +### ActorSystem.java + +```java +public class ActorSystem { + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} +``` + +### App.java + +```java +public class App { + public static void main(String[] args) { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} +``` + +--- + +## When to Use the Actor Model Pattern in Java + +- When building **concurrent or distributed systems** +- When you want **no shared mutable state** +- When you need **asynchronous, message-driven communication** +- When components should be **isolated and loosely coupled** + +--- + +## Actor Model Pattern Java Tutorials + +- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka) +- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143) + +--- + +## Real-World Applications of Actor Model Pattern in Java + +- [Akka Framework](https://akka.io/) +- [Erlang and Elixir concurrency](https://www.erlang.org/) +- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/) +- JVM-based game engines and simulators + +--- + +## Benefits and Trade-offs of Actor Model Pattern + +### ✅ Benefits +- High concurrency support +- Easy scaling across threads or machines +- Fault isolation and recovery +- Message ordering within actors + +### ⚠️ Trade-offs +- Harder to debug due to asynchronous behavior +- Slight performance overhead due to message queues +- More complex to design than simple method calls + +--- + +## Related Java Design Patterns + +- [Command Pattern](../command) +- [Mediator Pattern](../mediator) +- [Event-Driven Architecture](../event-driven-architecture) +- [Observer Pattern](../observer) + +--- + +## References and Credits + +- *Programming Erlang*, Joe Armstrong +- *Reactive Design Patterns*, Roland Kuhn +- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/) +- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html) + diff --git a/actor-model/etc/Actor_Model_UML_Class_Diagram.png b/actor-model/etc/Actor_Model_UML_Class_Diagram.png new file mode 100644 index 000000000000..a4c34d7a75fd Binary files /dev/null and b/actor-model/etc/Actor_Model_UML_Class_Diagram.png differ diff --git a/actor-model/etc/actor-model.urm.puml b/actor-model/etc/actor-model.urm.puml new file mode 100644 index 000000000000..020c1fc735a4 --- /dev/null +++ b/actor-model/etc/actor-model.urm.puml @@ -0,0 +1,35 @@ +@startuml actor-model + +title Actor Model - UML Class Diagram + +class ActorSystem { + +actorOf(actor: Actor): Actor + +shutdown(): void +} + +class Actor { + -mailbox: BlockingQueue + -active: boolean + +send(message: Message): void + +stop(): void + +run(): void + #onReceive(message: Message): void +} + +class ExampleActor { + +onReceive(message: Message): void +} + +class Message { + -content: String + -sender: Actor + +getContent(): String + +getSender(): Actor +} + +ActorSystem --> Actor : creates +Actor <|-- ExampleActor : extends +Actor --> Message : processes +ExampleActor --> Message : uses + +@enduml diff --git a/actor-model/pom.xml b/actor-model/pom.xml new file mode 100644 index 000000000000..76c288829b8d --- /dev/null +++ b/actor-model/pom.xml @@ -0,0 +1,114 @@ + + + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + actor-model + Actor Model + + + + + + org.junit + junit-bom + 5.11.0 + pom + import + + + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-launcher + test + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + jar-with-dependencies + + + + com.iluwatar.actormodel.App + + + + + + make-assembly + package + + single + + + + + + + + + diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java b/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java new file mode 100644 index 000000000000..6e2aaccd1937 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actormodel; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import lombok.Getter; +import lombok.Setter; + +public abstract class Actor implements Runnable { + + @Setter @Getter private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = + true; // always read from main memory and written back to main memory, + + // rather than being cached in a thread's local memory. To make it consistent to all Actors + + public void send(Message message) { + mailbox.add(message); // Add message to queue + } + + public void stop() { + active = false; // Stop the actor loop + } + + @Override + public void run() { + while (active) { + try { + Message message = mailbox.take(); // Wait for a message + onReceive(message); // Process it + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + // Child classes must define what to do with a message + protected abstract void onReceive(Message message); +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java b/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java new file mode 100644 index 000000000000..db7c21cb6088 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actormodel; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class ActorSystem { + private final ExecutorService executor = Executors.newCachedThreadPool(); + private final ConcurrentHashMap actorRegister = new ConcurrentHashMap<>(); + private final AtomicInteger idCounter = new AtomicInteger(0); + + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/App.java b/actor-model/src/main/java/com/iluwatar/actormodel/App.java new file mode 100644 index 000000000000..79fe79e48a6f --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/App.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * The Actor Model is a design pattern used to handle concurrency in a safe, scalable, and + * message-driven way. + * + *

In the Actor Model: - An **Actor** is an independent unit that has its own state and behavior. + * - Actors **communicate only through messages** — they do not share memory. - An **ActorSystem** + * is responsible for creating, starting, and managing the lifecycle of actors. - Messages are + * delivered asynchronously, and each actor processes them one at a time. + * + *

💡 Key benefits: - No shared memory = no need for complex thread-safety - Easy to scale with + * many actors - Suitable for highly concurrent or distributed systems + * + *

🔍 This example demonstrates the Actor Model: - `ActorSystem` starts two actors: `srijan` and + * `ansh`. - `ExampleActor` and `ExampleActor2` extend the `Actor` class and override the + * `onReceive()` method to handle messages. - Actors communicate using `send()` to pass `Message` + * objects that include the message content and sender's ID. - The actors process messages + * **asynchronously in separate threads**, and we allow a short delay (`Thread.sleep`) to let them + * run. - The system is shut down gracefully at the end. + */ +package com.iluwatar.actormodel; + +public class App { + public static void main(String[] args) throws InterruptedException { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java new file mode 100644 index 000000000000..fd49325f44bd --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actormodel; + +import java.util.ArrayList; +import java.util.List; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class ExampleActor extends Actor { + private final ActorSystem actorSystem; + @Getter private final List receivedMessages = new ArrayList<>(); + + public ExampleActor(ActorSystem actorSystem) { + this.actorSystem = actorSystem; + } + + // Logger log = Logger.getLogger(getClass().getName()); + + @Override + protected void onReceive(Message message) { + LOGGER.info( + "[{}]Received : {} from : [{}]", getActorId(), message.getContent(), message.getSenderId()); + Actor sender = actorSystem.getActorById(message.getSenderId()); // sender actor id + // Reply of the message + if (sender != null && !message.getSenderId().equals(getActorId())) { + sender.send(new Message("I got your message ", getActorId())); + } + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java new file mode 100644 index 000000000000..037f96716558 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actormodel; + +import java.util.ArrayList; +import java.util.List; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class ExampleActor2 extends Actor { + private final ActorSystem actorSystem; + @Getter private final List receivedMessages = new ArrayList<>(); + + public ExampleActor2(ActorSystem actorSystem) { + this.actorSystem = actorSystem; + } + + @Override + protected void onReceive(Message message) { + receivedMessages.add(message.getContent()); + LOGGER.info("[{}]Received : {}", getActorId(), message.getContent()); + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/Message.java b/actor-model/src/main/java/com/iluwatar/actormodel/Message.java new file mode 100644 index 000000000000..03ca6e02cac0 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/Message.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actormodel; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor +@Getter +public class Message { + private final String content; + private final String senderId; +} diff --git a/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java b/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java new file mode 100644 index 000000000000..a4a0dee569ab --- /dev/null +++ b/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.actor; + +import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.actormodel.ActorSystem; +import com.iluwatar.actormodel.App; +import com.iluwatar.actormodel.ExampleActor; +import com.iluwatar.actormodel.ExampleActor2; +import com.iluwatar.actormodel.Message; +import org.junit.jupiter.api.Test; + +public class ActorModelTest { + @Test + void testMainMethod() throws InterruptedException { + App.main(new String[] {}); + } + + @Test + public void testMessagePassing() throws InterruptedException { + ActorSystem system = new ActorSystem(); + + ExampleActor srijan = new ExampleActor(system); + ExampleActor2 ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + + // Ansh recieves a message from Srijan + ansh.send(new Message("Hello ansh", srijan.getActorId())); + + // Wait briefly to allow async processing + Thread.sleep(200); + + // Check that Srijan received the message + assertTrue( + ansh.getReceivedMessages().contains("Hello ansh"), + "ansh should receive the message from Srijan"); + } +} diff --git a/backends-for-frontends/README.md b/backends-for-frontends/README.md new file mode 100644 index 000000000000..12038e821e38 --- /dev/null +++ b/backends-for-frontends/README.md @@ -0,0 +1,148 @@ +--- +title: "Backends For Frontends Pattern in Java: Tailoring APIs to Client Needs" +shortTitle: Backends For Frontends +description: "Learn the Backends For Frontends (BFF) design pattern in Java. Understand how to give each client type its own dedicated backend service, with real-world examples, code, and diagrams." +category: Architectural +language: en +tag: + - API design + - Architecture + - Client-server + - Decoupling + - Microservices +--- + +## Also known as + +* Backend For Frontend +* BFF Pattern + +## Intent of Backends For Frontends Pattern + +Provide each client-side application (mobile, desktop, chatbot, and so on) with its own dedicated +backend service, so every client gets an API shaped exactly for its own needs instead of sharing +one general-purpose backend with every other client. + +## Detailed Explanation of Backends For Frontends Pattern with Real-World Examples + +Real-world example + +> Imagine a retail company whose mobile app, desktop back-office tool, and support chatbot all +> need customer, cart, order and supplier data -- but a phone screen wants a short summary while +> the back-office desktop tool wants full order and stock detail. Rather than exposing one shared +> API that every client has to filter or over-fetch from, the company stands up a small BFF service +> for the mobile clients and a separate BFF service for the intranet clients. Each BFF calls only +> the downstream microservices its client needs and returns a payload shaped for that client. + +In plain words + +> Give every kind of client its own tailor-made backend, instead of forcing all clients through one +> one-size-fits-all API. + +Sam Newman, who popularized the pattern, says + +> Create separate backend services to be consumed by specific frontend applications or interfaces. + +## Architecture Diagram + +``` +node mobile{ + component iosapp as "ios app" + component androidapp as "android app" +} +node intranet{ + component desktop as "desktop app" + component chatbot +} +component bff as "BFF server"{ + component iosbff as "ios BFF" + component androidbff as "android BFF" + component chatbotbff as "chatbot BFF" + component desktopbff as "desktop BFF" +} +node intranetserv as "intranet services server"{ + component ss as "supplier service API" +} +cloud onlypublic as "public cloud"{ + component cas as "customer authentication service API" + component cs as "cart service API" +} +cloud cloudserv as "managed cloud"{ + component os as "order service API" +} +iosapp -- iosbff +androidapp -- androidbff +chatbot -- chatbotbff +desktop -- desktopbff +iosbff -- cas +androidbff -- cas +iosbff -- cs +androidbff -- cs +iosbff -- os +androidbff -- os +chatbotbff -- os +desktopbff -- os +chatbotbff -- ss +desktopbff -- ss +``` + +This example implements a simplified version of the diagram above with two client-facing BFFs +instead of four, to keep the demo focused: a **Mobile BFF** standing in for the ios/android BFFs, +and a **Desktop BFF** standing in for the desktop/chatbot BFFs. Both call into the same shared +downstream services (`AuthService`, `OrderService`), while `CartService` is only used by the +Mobile BFF and `SupplierService` is only reachable from the Desktop BFF, matching the fan-out +shown in the diagram. + +## Class Diagram + +![Backends For Frontends class diagram](./etc/backends-for-frontends.png) + +## When to Use the Backends For Frontends Pattern in Java + +* Different client types (mobile, web, desktop, voice/chat) need meaningfully different shapes, + granularity, or aggregation of the same underlying data. +* A single shared API has grown a large number of client-specific conditional branches, optional + fields, or query parameters to accommodate every consumer. +* Different client teams need to iterate on their own API independently without coordinating + changes through one shared backend team. +* Some clients (e.g. mobile) need aggressively trimmed payloads for bandwidth/latency reasons, + while others (e.g. an internal desktop tool) need much richer data. + +## Benefits and Trade-offs of Backends For Frontends Pattern + +Benefits: + +* Each client gets an API optimized for its own needs, improving performance and simplicity on + the client side. +* Client teams can evolve their BFF independently, reducing cross-team coordination. +* Downstream microservices stay generic and reusable; client-specific logic lives in the BFF + layer instead of leaking into shared services. + +Trade-offs: + +* Introduces additional services to build, deploy, and operate. +* Logic that is genuinely shared across clients can end up duplicated across BFFs if not + carefully factored out. +* Adds an extra network hop between the client and the downstream services. + +## How to Implement Backends For Frontends Pattern in Java + +1. Identify the distinct client types that need meaningfully different data shapes. +2. Define the downstream services each client's data actually depends on (`AuthService`, + `CartService`, `OrderService`, `SupplierService` in this example). +3. Create one BFF per client type, implementing a shared `ClientBff` contract, where each BFF + only depends on the downstream services its client needs. +4. Have each BFF aggregate and reshape the downstream data into a response DTO tailored to its + client (`MobileDashboardResponse`, `DesktopDashboardResponse`). +5. Wire the client applications to call their own BFF rather than the downstream services + directly. + +## Source Code + +* [Pattern: Backends For Frontends](https://samnewman.io/patterns/architectural/bff/) by Sam Newman +* [Microservices Patterns: With examples in Java](https://www.amazon.com/Microservices-Patterns-examples-Chris-Richardson/dp/1617294543) by Chris Richardson + +## References and Credits + +* [Building Microservices](https://www.oreilly.com/library/view/building-microservices-2nd/9781492034018/) by Sam Newman +* [Pattern: Backend for frontend (microservices.io)](https://microservices.io/patterns/apigateway.html) diff --git a/backends-for-frontends/etc/backends-for-frontends.png b/backends-for-frontends/etc/backends-for-frontends.png new file mode 100644 index 000000000000..f42c786fecf4 Binary files /dev/null and b/backends-for-frontends/etc/backends-for-frontends.png differ diff --git a/backends-for-frontends/etc/backends-for-frontends.urm.puml b/backends-for-frontends/etc/backends-for-frontends.urm.puml new file mode 100644 index 000000000000..b09c06742d27 --- /dev/null +++ b/backends-for-frontends/etc/backends-for-frontends.urm.puml @@ -0,0 +1,130 @@ +@startuml +package com.iluwatar.bff { + class App { + - LOGGER : Logger {static} + - USER_ID : String {static} + - PRODUCT_ID : String {static} + - DEMO_PRICE_USD : double {static} + - DEMO_STOCK_LEVEL : int {static} + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.bff.bff { + interface ClientBff { + + getDashboard(userId : String) : T {abstract} + } + class DesktopBff { + - authService : AuthService + - orderService : OrderService + - supplierService : SupplierService + + DesktopBff(auth : AuthService, orders : OrderService, suppliers : SupplierService) + + getDashboard(userId : String) : DesktopDashboardResponse + } + class MobileBff { + - MAX_RECENT_ORDERS : int {static} + - authService : AuthService + - cartService : CartService + - orderService : OrderService + + MobileBff(auth : AuthService, cart : CartService, orders : OrderService) + + getDashboard(userId : String) : MobileDashboardResponse + } +} +package com.iluwatar.bff.dto { + class DesktopDashboardResponse { + - greeting : String + - loyaltyTier : String + - orderStatuses : List + - supplierStockSummaries : List + + DesktopDashboardResponse(greeting : String, loyaltyTier : String, orderStatuses : List, supplierStockSummaries : List) + } + class MobileDashboardResponse { + - greeting : String + - cartItemCount : int + - cartTotalUsd : double + - recentOrderSummaries : List + + MobileDashboardResponse(greeting : String, cartItemCount : int, cartTotalUsd : double, recentOrderSummaries : List) + } +} +package com.iluwatar.bff.model { + class CartItem { + - product : Product + - quantity : int + + CartItem(product : Product, quantity : int) + + lineTotal() : double + } + class Order { + - id : String + - productName : String + - status : String + + Order(id : String, productName : String, status : String) + } + class Product { + - id : String + - name : String + - priceUsd : double + + Product(id : String, name : String, priceUsd : double) + } + class SupplierRecord { + - productId : String + - supplierName : String + - stockLevel : int + + SupplierRecord(productId : String, supplierName : String, stockLevel : int) + } + class User { + - id : String + - displayName : String + - loyaltyTier : String + + User(id : String, displayName : String, loyaltyTier : String) + } +} +package com.iluwatar.bff.service { + interface AuthService { + + getUser(userId : String) : User {abstract} + } + interface CartService { + + getCart(userId : String) : List {abstract} + } + interface OrderService { + + getOrders(userId : String) : List {abstract} + } + interface SupplierService { + + getSupplierRecords(productId : String) : List {abstract} + } +} +package com.iluwatar.bff.service.impl { + class InMemoryAuthService { + - users : Map + + InMemoryAuthService(userData : Map) + + getUser(userId : String) : User + } + class InMemoryCartService { + - cartsByUserId : Map> + + InMemoryCartService(carts : Map>) + + getCart(userId : String) : List + } + class InMemoryOrderService { + - ordersByUserId : Map> + + InMemoryOrderService(orders : Map>) + + getOrders(userId : String) : List + } + class InMemorySupplierService { + - recordsByProductId : Map> + + InMemorySupplierService(records : Map>) + + getSupplierRecords(productId : String) : List + } +} +DesktopBff ..|> ClientBff +MobileBff ..|> ClientBff +DesktopBff --> "-authService" AuthService +DesktopBff --> "-orderService" OrderService +DesktopBff --> "-supplierService" SupplierService +MobileBff --> "-authService" AuthService +MobileBff --> "-cartService" CartService +MobileBff --> "-orderService" OrderService +InMemoryAuthService ..|> AuthService +InMemoryCartService ..|> CartService +InMemoryOrderService ..|> OrderService +InMemorySupplierService ..|> SupplierService +CartItem --> "-product" Product +@enduml diff --git a/backends-for-frontends/pom.xml b/backends-for-frontends/pom.xml new file mode 100644 index 000000000000..8f1e454fa646 --- /dev/null +++ b/backends-for-frontends/pom.xml @@ -0,0 +1,67 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + backends-for-frontends + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.slf4j + slf4j-api + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.iluwatar.bff.App + + + + + + + diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/App.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/App.java new file mode 100644 index 000000000000..b76939c53fd4 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/App.java @@ -0,0 +1,109 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff; + +import com.iluwatar.bff.bff.DesktopBff; +import com.iluwatar.bff.bff.MobileBff; +import com.iluwatar.bff.model.CartItem; +import com.iluwatar.bff.model.Order; +import com.iluwatar.bff.model.Product; +import com.iluwatar.bff.model.SupplierRecord; +import com.iluwatar.bff.model.User; +import com.iluwatar.bff.service.impl.InMemoryAuthService; +import com.iluwatar.bff.service.impl.InMemoryCartService; +import com.iluwatar.bff.service.impl.InMemoryOrderService; +import com.iluwatar.bff.service.impl.InMemorySupplierService; +import java.util.List; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link App} demonstrates the Backends For Frontends (BFF) pattern. + * + *

A single set of downstream microservices (customer authentication, cart, order and supplier + * services) is shared by every client. Two different client-facing gateways -- {@link MobileBff} + * for the mobile apps and {@link DesktopBff} for the intranet desktop/chatbot clients -- each call + * a different subset of those services and reshape the results into a response tailored to what + * their own client actually needs, rather than exposing one one-size-fits-all API to every client. + */ +public final class App { + + /** Logger for this class. */ + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** User id used in the demonstration. */ + private static final String USER_ID = "u-1"; + + /** Product id used in the demonstration. */ + private static final String PRODUCT_ID = "p-42"; + + /** Unit price of the demo product in US dollars. */ + private static final double DEMO_PRICE_USD = 79.99; + + /** Supplier stock level used in the demonstration. */ + private static final int DEMO_STOCK_LEVEL = 120; + + private App() { + // utility class + } + + /** + * Program entry point. + * + * @param args no argument sent + */ + public static void main(final String[] args) { + // shared downstream microservices, as drawn in the pattern diagram + var authService = new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Alice", "GOLD"))); + + var product = new Product(PRODUCT_ID, "Wireless Headphones", DEMO_PRICE_USD); + var cartService = new InMemoryCartService(Map.of(USER_ID, List.of(new CartItem(product, 2)))); + + var orderService = + new InMemoryOrderService( + Map.of( + USER_ID, + List.of( + new Order("o-1", "Wireless Headphones", "DELIVERED"), + new Order("o-2", "USB-C Cable", "IN_TRANSIT")))); + + var supplierService = + new InMemorySupplierService( + Map.of( + "Wireless Headphones", + List.of(new SupplierRecord(PRODUCT_ID, "Acme Audio Co.", DEMO_STOCK_LEVEL)))); + + // client-specific BFFs, each calling only the services their client needs + var mobileBff = new MobileBff(authService, cartService, orderService); + var desktopBff = new DesktopBff(authService, orderService, supplierService); + + var mobileResponse = mobileBff.getDashboard(USER_ID); + LOGGER.info("Mobile BFF response: {}", mobileResponse); + + var desktopResponse = desktopBff.getDashboard(USER_ID); + LOGGER.info("Desktop BFF response: {}", desktopResponse); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/ClientBff.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/ClientBff.java new file mode 100644 index 000000000000..4c1d8d768ecb --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/ClientBff.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.bff; + +/** + * Common contract every client-specific Backend For Frontend implements: given a user id, build + * whatever response shape ({@code T}) that particular client needs. Each implementation is free to + * call a different subset of downstream services and aggregate them differently -- that freedom is + * the entire point of the pattern. + * + * @param the response DTO shape this BFF returns to its client + */ +public interface ClientBff { + + /** + * Builds the dashboard response for a given user, tailored to this BFF's client. + * + * @param userId identifier of the user requesting their dashboard + * @return the client-specific response + */ + T getDashboard(String userId); +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/DesktopBff.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/DesktopBff.java new file mode 100644 index 000000000000..1073f4556558 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/DesktopBff.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.bff; + +import com.iluwatar.bff.dto.DesktopDashboardResponse; +import com.iluwatar.bff.service.AuthService; +import com.iluwatar.bff.service.OrderService; +import com.iluwatar.bff.service.SupplierService; +import java.util.ArrayList; +import java.util.List; + +/** + * Backend For Frontend serving the intranet clients (desktop app, chatbot) from the diagram. It + * aggregates the auth, order and supplier services and reshapes the results into a richer, + * back-office style payload. Unlike {@link MobileBff}, it does not touch the cart service at all + * and it does reach into the intranet-only supplier service, matching the fan-out drawn in the + * pattern diagram. + */ +public final class DesktopBff implements ClientBff { + + /** The customer authentication service. */ + private final AuthService authService; + + /** The order service. */ + private final OrderService orderService; + + /** The supplier service (intranet-only). */ + private final SupplierService supplierService; + + /** + * Creates a desktop BFF wired to the downstream services it depends on. + * + * @param auth the customer authentication service + * @param orders the order service + * @param suppliers the supplier service + */ + public DesktopBff( + final AuthService auth, final OrderService orders, final SupplierService suppliers) { + this.authService = auth; + this.orderService = orders; + this.supplierService = suppliers; + } + + @Override + public DesktopDashboardResponse getDashboard(final String userId) { + var user = authService.getUser(userId); + var orders = orderService.getOrders(userId); + + var orderStatuses = + orders.stream() + .map(order -> order.id() + ": " + order.productName() + " [" + order.status() + "]") + .toList(); + + var supplierStockSummaries = new ArrayList(); + for (var order : orders) { + for (var supplierRecord : supplierService.getSupplierRecords(order.productName())) { + supplierStockSummaries.add( + supplierRecord.supplierName() + + ": " + + supplierRecord.stockLevel() + + " units of " + + order.productName()); + } + } + + return new DesktopDashboardResponse( + "Welcome back, " + user.displayName(), + user.loyaltyTier(), + List.copyOf(orderStatuses), + List.copyOf(supplierStockSummaries)); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/MobileBff.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/MobileBff.java new file mode 100644 index 000000000000..a51a7c8a8201 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/MobileBff.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.bff; + +import com.iluwatar.bff.dto.MobileDashboardResponse; +import com.iluwatar.bff.service.AuthService; +import com.iluwatar.bff.service.CartService; +import com.iluwatar.bff.service.OrderService; +import java.util.List; + +/** + * Backend For Frontend serving the mobile clients (iOS app, Android app) from the diagram. It + * aggregates the auth, cart and order services and reshapes the results into a small payload suited + * to a phone screen and a limited-bandwidth connection. It never calls the supplier service: a + * mobile shopper has no use for back-office stock data, so this BFF simply does not expose it, + * rather than sending it and letting the client ignore it. + */ +public final class MobileBff implements ClientBff { + + /** Maximum number of recent order summaries to include in the mobile response. */ + private static final int MAX_RECENT_ORDERS = 3; + + /** The customer authentication service. */ + private final AuthService authService; + + /** The cart service. */ + private final CartService cartService; + + /** The order service. */ + private final OrderService orderService; + + /** + * Creates a mobile BFF wired to the downstream services it depends on. + * + * @param auth the customer authentication service + * @param cart the cart service + * @param orders the order service + */ + public MobileBff(final AuthService auth, final CartService cart, final OrderService orders) { + this.authService = auth; + this.cartService = cart; + this.orderService = orders; + } + + @Override + public MobileDashboardResponse getDashboard(final String userId) { + var user = authService.getUser(userId); + var cart = cartService.getCart(userId); + var orders = orderService.getOrders(userId); + + var cartTotal = cart.stream().mapToDouble(item -> item.lineTotal()).sum(); + var recentOrderSummaries = + orders.stream() + .limit(MAX_RECENT_ORDERS) + .map(order -> order.productName() + " (" + order.status() + ")") + .toList(); + + return new MobileDashboardResponse( + "Hi " + user.displayName() + "!", + cart.size(), + cartTotal, + List.copyOf(recentOrderSummaries)); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/package-info.java new file mode 100644 index 000000000000..c338c3158023 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/bff/package-info.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Client-specific Backend For Frontend implementations: one per client type (mobile, desktop) that + * each aggregate a different subset of downstream services. + */ +package com.iluwatar.bff.bff; diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/DesktopDashboardResponse.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/DesktopDashboardResponse.java new file mode 100644 index 000000000000..434e1f1cc088 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/DesktopDashboardResponse.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.dto; + +import java.util.List; + +/** + * The shape of data the desktop back-office client renders: richer than the mobile payload, + * including full order status and supplier stock levels that a mobile shopper never needs. + * + * @param greeting a short personalized greeting for the user + * @param loyaltyTier the user's loyalty program tier + * @param orderStatuses detailed "id: productName [status]" lines for every order + * @param supplierStockSummaries "supplierName: stockLevel units" lines for relevant products + */ +public record DesktopDashboardResponse( + String greeting, + String loyaltyTier, + List orderStatuses, + List supplierStockSummaries) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/MobileDashboardResponse.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/MobileDashboardResponse.java new file mode 100644 index 000000000000..d6d27619c36d --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/MobileDashboardResponse.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.dto; + +import java.util.List; + +/** + * The shape of data the mobile (iOS/Android) client actually renders: a lean payload with just + * enough for a small screen, deliberately excluding fields the desktop client needs. + * + * @param greeting a short personalized greeting for the user + * @param cartItemCount number of items currently in the user's cart + * @param cartTotalUsd total value of the user's cart in US dollars + * @param recentOrderSummaries short human-readable summaries of the user's most recent orders + */ +public record MobileDashboardResponse( + String greeting, int cartItemCount, double cartTotalUsd, List recentOrderSummaries) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/package-info.java new file mode 100644 index 000000000000..43a23d0dbc4e --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/dto/package-info.java @@ -0,0 +1,28 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Response DTOs shaped by each BFF for its specific client (mobile dashboard, desktop dashboard). + */ +package com.iluwatar.bff.dto; diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/CartItem.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/CartItem.java new file mode 100644 index 000000000000..a71c4848c791 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/CartItem.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.model; + +/** + * A single line item inside a user's shopping cart, as returned by the cart service API. + * + * @param product the product being purchased + * @param quantity number of units of the product + */ +public record CartItem(Product product, int quantity) { + + /** + * Computes the line total for this cart item. + * + * @return quantity multiplied by unit price + */ + public double lineTotal() { + return quantity * product.priceUsd(); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Order.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Order.java new file mode 100644 index 000000000000..02a2026695b0 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Order.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.model; + +/** + * A past order returned by the order service API. + * + * @param id order identifier + * @param productName name of the ordered product + * @param status current fulfillment status, e.g. "DELIVERED", "IN_TRANSIT" + */ +public record Order(String id, String productName, String status) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Product.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Product.java new file mode 100644 index 000000000000..ae4176860b6e --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/Product.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.model; + +/** + * Simple product record returned by the downstream Cart/Order services. Represents the data a + * catalog or cart entry carries before each BFF trims or reshapes it for its own client. + * + * @param id product identifier + * @param name display name of the product + * @param priceUsd unit price in US dollars + */ +public record Product(String id, String name, double priceUsd) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/SupplierRecord.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/SupplierRecord.java new file mode 100644 index 000000000000..f7dfa38fe89d --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/SupplierRecord.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.model; + +/** + * A supplier stock record returned by the supplier service API, used by the desktop back-office + * client to show inventory information that mobile customers never need to see. + * + * @param productId identifier of the product this record refers to + * @param supplierName name of the supplying vendor + * @param stockLevel units currently available from this supplier + */ +public record SupplierRecord(String productId, String supplierName, int stockLevel) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/User.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/User.java new file mode 100644 index 000000000000..5c59c7f963ec --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/User.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.model; + +/** + * Authenticated user profile returned by the customer authentication service API. Kept + * intentionally minimal; each BFF decides which of these fields its client actually needs. + * + * @param id unique user identifier + * @param displayName human-readable name of the user + * @param loyaltyTier loyalty program tier, e.g. "GOLD", "SILVER", "STANDARD" + */ +public record User(String id, String displayName, String loyaltyTier) {} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/model/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/package-info.java new file mode 100644 index 000000000000..37d2855a8671 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/model/package-info.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Domain model records shared across downstream services: User, Product, CartItem, Order, and + * SupplierRecord. Each BFF consumes these raw domain objects and reshapes them into its own + * client-specific DTO. + */ +package com.iluwatar.bff.model; diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/package-info.java new file mode 100644 index 000000000000..ede18f2b22f9 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/package-info.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Backends For Frontends pattern: a dedicated gateway per client type (mobile, desktop) that + * aggregates only the downstream services each client actually needs. + */ +package com.iluwatar.bff; diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/AuthService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/AuthService.java new file mode 100644 index 000000000000..a87b75b48bb6 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/AuthService.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service; + +import com.iluwatar.bff.model.User; + +/** + * Represents the customer authentication service API from the diagram: a downstream microservice + * shared by every client-specific BFF. Each BFF calls this the same way; only what they do with the + * result differs. + */ +public interface AuthService { + + /** + * Looks up the authenticated user profile for the given id. + * + * @param userId identifier of the user to look up + * @return the matching {@link User} + */ + User getUser(String userId); +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/CartService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/CartService.java new file mode 100644 index 000000000000..7ae24fba64bc --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/CartService.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service; + +import com.iluwatar.bff.model.CartItem; +import java.util.List; + +/** + * Represents the cart service API from the diagram. In this example only the mobile and android + * clients need cart data, so only {@link com.iluwatar.bff.bff.MobileBff} calls this service. + */ +public interface CartService { + + /** + * Retrieves the current cart contents for a user. + * + * @param userId identifier of the user whose cart is requested + * @return the list of items currently in the user's cart + */ + List getCart(String userId); +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/OrderService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/OrderService.java new file mode 100644 index 000000000000..b8e6ee8fa03e --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/OrderService.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service; + +import com.iluwatar.bff.model.Order; +import java.util.List; + +/** + * Represents the order service API from the diagram. This downstream service is shared by every + * client-specific BFF, matching the fan-out shown for "order service API" in the pattern diagram. + */ +public interface OrderService { + + /** + * Retrieves the order history for a user. + * + * @param userId identifier of the user whose orders are requested + * @return the list of past orders for the user + */ + List getOrders(String userId); +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/SupplierService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/SupplierService.java new file mode 100644 index 000000000000..ac7c2dfbc849 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/SupplierService.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service; + +import com.iluwatar.bff.model.SupplierRecord; +import java.util.List; + +/** + * Represents the supplier service API from the diagram, reachable only from the intranet services + * server. Only back-office style clients (desktop app, chatbot) call this service. + */ +public interface SupplierService { + + /** + * Retrieves supplier stock records for a product. + * + * @param productName name of the product to check stock for + * @return the list of supplier stock records for the product + */ + List getSupplierRecords(String productName); +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryAuthService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryAuthService.java new file mode 100644 index 000000000000..5c2ffc35958f --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryAuthService.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import com.iluwatar.bff.model.User; +import com.iluwatar.bff.service.AuthService; +import java.util.Map; + +/** + * In-memory stand-in for the real customer authentication service API. Real deployments would + * replace this with an HTTP/gRPC client; the BFFs are written against the {@link AuthService} + * interface, so swapping the implementation later requires no change to any BFF. + */ +public final class InMemoryAuthService implements AuthService { + + /** Users stored in memory, keyed by user id. */ + private final Map users; + + /** + * Creates the service with a fixed backing map of users, keyed by user id. + * + * @param userData the user data this service serves + */ + public InMemoryAuthService(final Map userData) { + this.users = userData; + } + + @Override + public User getUser(final String userId) { + var user = users.get(userId); + if (user == null) { + throw new IllegalArgumentException("Unknown user id: " + userId); + } + return user; + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryCartService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryCartService.java new file mode 100644 index 000000000000..fed3b59da2c8 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryCartService.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import com.iluwatar.bff.model.CartItem; +import com.iluwatar.bff.service.CartService; +import java.util.List; +import java.util.Map; + +/** In-memory stand-in for the real cart service API. */ +public final class InMemoryCartService implements CartService { + + /** Carts stored in memory, keyed by user id. */ + private final Map> cartsByUserId; + + /** + * Creates the service with a fixed backing map of carts, keyed by user id. + * + * @param carts the cart data this service serves + */ + public InMemoryCartService(final Map> carts) { + this.cartsByUserId = carts; + } + + @Override + public List getCart(final String userId) { + return cartsByUserId.getOrDefault(userId, List.of()); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryOrderService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryOrderService.java new file mode 100644 index 000000000000..979956d06244 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemoryOrderService.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import com.iluwatar.bff.model.Order; +import com.iluwatar.bff.service.OrderService; +import java.util.List; +import java.util.Map; + +/** In-memory stand-in for the real order service API. */ +public final class InMemoryOrderService implements OrderService { + + /** Order histories stored in memory, keyed by user id. */ + private final Map> ordersByUserId; + + /** + * Creates the service with a fixed backing map of order histories, keyed by user id. + * + * @param orders the order data this service serves + */ + public InMemoryOrderService(final Map> orders) { + this.ordersByUserId = orders; + } + + @Override + public List getOrders(final String userId) { + return ordersByUserId.getOrDefault(userId, List.of()); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemorySupplierService.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemorySupplierService.java new file mode 100644 index 000000000000..ac2d351db3a5 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/InMemorySupplierService.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import com.iluwatar.bff.model.SupplierRecord; +import com.iluwatar.bff.service.SupplierService; +import java.util.List; +import java.util.Map; + +/** In-memory stand-in for the real supplier service API, reachable only from the intranet. */ +public final class InMemorySupplierService implements SupplierService { + + /** Supplier records stored in memory, keyed by product name. */ + private final Map> recordsByProductName; + + /** + * Creates the service with a fixed backing map of supplier records, keyed by product name. + * + * @param records the supplier data this service serves + */ + public InMemorySupplierService(final Map> records) { + this.recordsByProductName = records; + } + + @Override + public List getSupplierRecords(final String productName) { + return recordsByProductName.getOrDefault(productName, List.of()); + } +} diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/package-info.java new file mode 100644 index 000000000000..fbdb5d026bc8 --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/impl/package-info.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * In-memory implementations of the downstream service API interfaces, used for the pattern + * demonstration. Production deployments would replace these with real HTTP/gRPC clients. + */ +package com.iluwatar.bff.service.impl; diff --git a/backends-for-frontends/src/main/java/com/iluwatar/bff/service/package-info.java b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/package-info.java new file mode 100644 index 000000000000..05bfcb3911df --- /dev/null +++ b/backends-for-frontends/src/main/java/com/iluwatar/bff/service/package-info.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Downstream service API interfaces shared by all BFFs: AuthService, CartService, OrderService, and + * SupplierService. Each BFF wires in only the services its client requires. + */ +package com.iluwatar.bff.service; diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/AppTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/AppTest.java new file mode 100644 index 000000000000..d06d945c8c33 --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/AppTest.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** + * Tests that {@link App}'s demo entry point runs end-to-end without throwing, following the + * convention used throughout this repository for pattern demo apps. + */ +class AppTest { + + @Test + void mainShouldRunWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/DesktopBffTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/DesktopBffTest.java new file mode 100644 index 000000000000..d4a2331b101b --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/DesktopBffTest.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.bff; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.bff.model.Order; +import com.iluwatar.bff.model.SupplierRecord; +import com.iluwatar.bff.model.User; +import com.iluwatar.bff.service.impl.InMemoryAuthService; +import com.iluwatar.bff.service.impl.InMemoryOrderService; +import com.iluwatar.bff.service.impl.InMemorySupplierService; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link DesktopBff}. */ +class DesktopBffTest { + + private static final String USER_ID = "u-1"; + + @Test + void shouldAggregateOrdersAndSupplierStockIntoDesktopShape() { + var authService = new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Alice", "GOLD"))); + var orderService = + new InMemoryOrderService( + Map.of(USER_ID, List.of(new Order("o-1", "Headphones", "DELIVERED")))); + var supplierService = + new InMemorySupplierService( + Map.of("Headphones", List.of(new SupplierRecord("p-1", "Acme Audio", 30)))); + + var bff = new DesktopBff(authService, orderService, supplierService); + var response = bff.getDashboard(USER_ID); + + assertEquals("Welcome back, Alice", response.greeting()); + assertEquals("GOLD", response.loyaltyTier()); + assertTrue(response.orderStatuses().get(0).contains("Headphones")); + assertTrue(response.supplierStockSummaries().get(0).contains("Acme Audio")); + } + + @Test + void shouldReturnNoSupplierSummariesWhenNoOrdersExist() { + var authService = + new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Carol", "STANDARD"))); + var orderService = new InMemoryOrderService(Map.of(USER_ID, List.of())); + var supplierService = new InMemorySupplierService(Map.of()); + + var bff = new DesktopBff(authService, orderService, supplierService); + var response = bff.getDashboard(USER_ID); + + assertEquals(0, response.orderStatuses().size()); + assertEquals(0, response.supplierStockSummaries().size()); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/MobileBffTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/MobileBffTest.java new file mode 100644 index 000000000000..f05a0be99b61 --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/bff/MobileBffTest.java @@ -0,0 +1,83 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.bff; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.bff.model.CartItem; +import com.iluwatar.bff.model.Order; +import com.iluwatar.bff.model.Product; +import com.iluwatar.bff.model.User; +import com.iluwatar.bff.service.impl.InMemoryAuthService; +import com.iluwatar.bff.service.impl.InMemoryCartService; +import com.iluwatar.bff.service.impl.InMemoryOrderService; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link MobileBff}. */ +class MobileBffTest { + + private static final String USER_ID = "u-1"; + + @Test + void shouldAggregateCartAndOrdersIntoMobileShape() { + var authService = new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Alice", "GOLD"))); + var product = new Product("p-1", "Headphones", 50.0); + var cartService = new InMemoryCartService(Map.of(USER_ID, List.of(new CartItem(product, 2)))); + var orderService = + new InMemoryOrderService( + Map.of(USER_ID, List.of(new Order("o-1", "Headphones", "DELIVERED")))); + + var bff = new MobileBff(authService, cartService, orderService); + var response = bff.getDashboard(USER_ID); + + assertEquals("Hi Alice!", response.greeting()); + assertEquals(1, response.cartItemCount()); + assertEquals(100.0, response.cartTotalUsd()); + assertTrue(response.recentOrderSummaries().get(0).contains("Headphones")); + } + + @Test + void shouldCapRecentOrderSummariesAtThree() { + var authService = new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Bob", "SILVER"))); + var cartService = new InMemoryCartService(Map.of(USER_ID, List.of())); + var orderService = + new InMemoryOrderService( + Map.of( + USER_ID, + List.of( + new Order("o-1", "A", "DELIVERED"), + new Order("o-2", "B", "DELIVERED"), + new Order("o-3", "C", "DELIVERED"), + new Order("o-4", "D", "DELIVERED")))); + + var bff = new MobileBff(authService, cartService, orderService); + var response = bff.getDashboard(USER_ID); + + assertEquals(3, response.recentOrderSummaries().size()); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryAuthServiceTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryAuthServiceTest.java new file mode 100644 index 000000000000..db4da0c0ba0d --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryAuthServiceTest.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.iluwatar.bff.model.User; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link InMemoryAuthService}. */ +class InMemoryAuthServiceTest { + + private static final String USER_ID = "u-1"; + + @Test + void shouldReturnUserForKnownId() { + var expected = new User(USER_ID, "Alice", "GOLD"); + var service = new InMemoryAuthService(Map.of(USER_ID, expected)); + + var actual = service.getUser(USER_ID); + + assertEquals(expected, actual); + } + + @Test + void shouldThrowForUnknownId() { + var service = new InMemoryAuthService(Map.of(USER_ID, new User(USER_ID, "Alice", "GOLD"))); + + assertThrows(IllegalArgumentException.class, () -> service.getUser("unknown-id")); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryCartServiceTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryCartServiceTest.java new file mode 100644 index 000000000000..19e54841fa44 --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryCartServiceTest.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.bff.model.CartItem; +import com.iluwatar.bff.model.Product; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link InMemoryCartService}. */ +class InMemoryCartServiceTest { + + private static final String USER_ID = "u-1"; + + @Test + void shouldReturnCartItemsForKnownUser() { + var product = new Product("p-1", "Headphones", 49.99); + var item = new CartItem(product, 2); + var service = new InMemoryCartService(Map.of(USER_ID, List.of(item))); + + var cart = service.getCart(USER_ID); + + assertEquals(1, cart.size()); + assertEquals(item, cart.get(0)); + } + + @Test + void shouldReturnEmptyListForUnknownUser() { + var service = new InMemoryCartService(Map.of()); + + var cart = service.getCart("unknown-user"); + + assertTrue(cart.isEmpty()); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryOrderServiceTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryOrderServiceTest.java new file mode 100644 index 000000000000..26b7d82be105 --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemoryOrderServiceTest.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.bff.model.Order; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link InMemoryOrderService}. */ +class InMemoryOrderServiceTest { + + private static final String USER_ID = "u-1"; + + @Test + void shouldReturnOrdersForKnownUser() { + var order = new Order("o-1", "Headphones", "DELIVERED"); + var service = new InMemoryOrderService(Map.of(USER_ID, List.of(order))); + + var orders = service.getOrders(USER_ID); + + assertEquals(1, orders.size()); + assertEquals(order, orders.get(0)); + } + + @Test + void shouldReturnEmptyListForUnknownUser() { + var service = new InMemoryOrderService(Map.of()); + + var orders = service.getOrders("unknown-user"); + + assertTrue(orders.isEmpty()); + } +} diff --git a/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemorySupplierServiceTest.java b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemorySupplierServiceTest.java new file mode 100644 index 000000000000..ce5d39041033 --- /dev/null +++ b/backends-for-frontends/src/test/java/com/iluwatar/bff/service/impl/InMemorySupplierServiceTest.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bff.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.bff.model.SupplierRecord; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests for {@link InMemorySupplierService}. */ +class InMemorySupplierServiceTest { + + private static final String PRODUCT_NAME = "Headphones"; + + @Test + void shouldReturnSupplierRecordsForKnownProductName() { + var record = new SupplierRecord("p-1", "Acme Audio", 30); + var service = new InMemorySupplierService(Map.of(PRODUCT_NAME, List.of(record))); + + var records = service.getSupplierRecords(PRODUCT_NAME); + + assertEquals(1, records.size()); + assertEquals(record, records.get(0)); + } + + @Test + void shouldReturnEmptyListForUnknownProductName() { + var service = new InMemorySupplierService(Map.of()); + + var records = service.getSupplierRecords("unknown-product"); + + assertTrue(records.isEmpty()); + } +} diff --git a/backpressure/pom.xml b/backpressure/pom.xml index fcc15892fb8a..8f6a54178799 100644 --- a/backpressure/pom.xml +++ b/backpressure/pom.xml @@ -55,7 +55,7 @@ io.projectreactor reactor-test - 3.8.0-M1 + 3.8.0-RC1 test diff --git a/bloc/pom.xml b/bloc/pom.xml index cc52a3b99dc2..021fbaafeb8d 100644 --- a/bloc/pom.xml +++ b/bloc/pom.xml @@ -50,7 +50,7 @@ org.assertj assertj-core - 3.27.3 + 3.27.7 test diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index 7b630f8da247..9afaa3fc33fa 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -39,6 +39,11 @@ private App() {} /** Program entry point. */ public static void main(final String[] args) { var task = new SimpleTask(); - task.executeWith(() -> LOGGER.info("I'm done now.")); + + LOGGER.info("=== Synchronous callback ==="); + task.executeWith(() -> LOGGER.info("Sync callback executed.")); + + LOGGER.info("=== Asynchronous callback ==="); + task.executeAsyncWith(() -> LOGGER.info("Async callback executed.")).join(); } } diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java index 7b75b5c71077..67b2880e1681 100644 --- a/callback/src/main/java/com/iluwatar/callback/Callback.java +++ b/callback/src/main/java/com/iluwatar/callback/Callback.java @@ -25,6 +25,7 @@ package com.iluwatar.callback; /** Callback interface. */ +@FunctionalInterface public interface Callback { void call(); diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index d69697454dff..d58d55540f52 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -25,15 +25,30 @@ package com.iluwatar.callback; import java.util.Optional; +import java.util.concurrent.CompletableFuture; -/** Template-method class for callback hook execution. */ +/** + * Template-method class for callback hook execution. + * + *

Provides both synchronous and asynchronous execution with callback support. + */ public abstract class Task { - /** Execute with callback. */ + /** Execute the task and call the callback method synchronously upon completion. */ final void executeWith(Callback callback) { execute(); Optional.ofNullable(callback).ifPresent(Callback::call); } + /** Execute the task and asynchronously call the callback method upon completion. */ + final CompletableFuture executeAsyncWith(Callback callback) { + return CompletableFuture.runAsync( + () -> { + execute(); + Optional.ofNullable(callback).ifPresent(Callback::call); + }); + } + + /** Actual work to be implemented by subclasses. */ public abstract void execute(); } diff --git a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java index 99939d491f4e..64780babec84 100644 --- a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java +++ b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -26,6 +26,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; /** @@ -39,19 +42,44 @@ class CallbackTest { private Integer callingCount = 0; @Test - void test() { - Callback callback = () -> callingCount++; - + void testSynchronousCallback() { + var counter = new AtomicInteger(); + Callback callback = counter::incrementAndGet; var task = new SimpleTask(); - assertEquals(Integer.valueOf(0), callingCount, "Initial calling count of 0"); - + assertEquals(0, counter.get(), "Initial count should be 0"); task.executeWith(callback); + assertEquals(1, counter.get(), "Callback should be called once"); + task.executeWith(callback); + assertEquals(2, counter.get(), "Callback should be called twice"); + } - assertEquals(Integer.valueOf(1), callingCount, "Callback called once"); + @Test + void testAsynchronousCallback() { + var task = new SimpleTask(); - task.executeWith(callback); + var counter1 = new AtomicInteger(); + final CompletableFuture future1 = new CompletableFuture<>(); + Callback callback1 = + () -> { + counter1.incrementAndGet(); + future1.complete(null); + }; + var f1 = task.executeAsyncWith(callback1); + future1.orTimeout(1, TimeUnit.SECONDS).join(); + f1.join(); + assertEquals(1, counter1.get(), "Async callback should increment once"); - assertEquals(Integer.valueOf(2), callingCount, "Callback called twice"); + var counter2 = new AtomicInteger(); + final CompletableFuture future2 = new CompletableFuture<>(); + Callback callback2 = + () -> { + counter2.incrementAndGet(); + future2.complete(null); + }; + var f2 = task.executeAsyncWith(callback2); + future2.orTimeout(1, TimeUnit.SECONDS).join(); + f2.join(); + assertEquals(1, counter2.get(), "Async callback should increment once again"); } } diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md index 99c1b7b4d398..b1baf416fc86 100644 --- a/circuit-breaker/README.md +++ b/circuit-breaker/README.md @@ -193,7 +193,7 @@ The Circuit Breaker pattern is applicable: * Cloud-based services to gracefully handle the failure of external services * E-commerce platforms to manage high volumes of transactions and dependency on external APIs * Microservices architectures for maintaining system stability and responsiveness -* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Spring Circuit Breaker module](https://spring.io/guides/gs/cloud-circuit-breaker) * [Netflix Hystrix API](https://github.com/Netflix/Hystrix) ## Benefits and Trade-offs of Circuit Breaker Pattern diff --git a/commander/pom.xml b/commander/pom.xml index 1dbe2dc89de5..526bb1c42ecc 100644 --- a/commander/pom.xml +++ b/commander/pom.xml @@ -34,7 +34,7 @@ commander - 2.0.17 + 2.0.18 1.5.6 diff --git a/dao-factory/README.md b/dao-factory/README.md new file mode 100644 index 000000000000..c3ee3c5e893d --- /dev/null +++ b/dao-factory/README.md @@ -0,0 +1,360 @@ +--- +title: "DAO Factory Pattern: Flexible Data Access Layer for Seamless Data Source Switching" +shortTitle: DAO Factory +description: "Learn the Data Access Object Pattern combine with Abstract Factory Pattern in Java with real-world examples, class diagrams, and tutorials. Understand its intent, applicability, benefits, and known uses to enhance your design pattern knowledge." +category: Structural +language: en +tag: + - Abstraction + - Data access + - Layer architecture + - Persistence +--- + +## Also known as + +* DAO Factory +* Factory for Data Access Object strategy using Abstract Factory + + +## Intent of Data Access Object Factory Design Pattern + +The DAO Factory combines the Data Access Object and Abstract Factory patterns to seperate business logic from data access logic, while increasing flexibility when switching between different data sources. + +## Detailed Explanation of Data Access Object Factory Pattern with Real-World Examples + +Real-world example + +> A real-world analogy for the DAO Factory pattern is a multilingual customer service center. Imagine a bank that serves customers speaking different languages—English, French, and Spanish. When a customer calls, an automated system first detects the customer's preferred language, then routes the call to the appropriate support team that speaks that language. Each team follows the same company policies (standard procedures), but handles interactions in a language-specific way. +> +> In the same way, the DAO Factory pattern uses a factory to determine the correct set of DAO implementations based on the data source (e.g., MySQL, MongoDB). Each DAO factory returns a group of DAOs tailored to a specific data source, all conforming to the same interfaces. This allows the application to interact with any supported database in a consistent manner, without changing the business logic—just like how the customer service system handles multiple languages while following the same support protocols. + +In plain words + +> The DAO Factory pattern abstracts the creation of Data Access Objects (DAOs), allowing you to request a specific DAO from a central factory without worrying about its underlying implementation. This makes the code easier to maintain and flexible to change, especially when switching between databases or storage mechanisms. + +Wikipedia says + +> The Data Access Object (DAO) design pattern is a structural pattern that provides an abstract interface to some type of database or other persistence mechanism. By mapping application calls to the persistence layer, the DAO provides some specific data operations without exposing details of the database. The DAO Factory is an extension of this concept, responsible for generating the required DAO implementations. + +Class diagram + +![Data Access Object Factory class diagram](./etc/dao-factory.png "Data Access Object Factory class diagram") + +## Programmatic Example of Data Access Object Factory in Java + +In this example, the persistence object represents a Customer. + +We are considering a flexible storage strategy where the application should be able to work with three different types of data sources: an H2 in-memory relational database (RDBMS), a MongoDB (object-oriented database), and a JSON flat file (flat file storage). + +``` java +public enum DataSourceType { +H2, +Mongo, +FlatFile +} +``` + +First, we define a Customer class that will be persisted in different storage systems. The ID field is generic to maintain compatibility with both relational and object-oriented databases. + +``` java +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class Customer implements Serializable { +private T id; +private String name; +} +``` + +Next, we define a CustomerDAO interface that outlines the standard CRUD operations on the Customer model. This interface will have three concrete implementations, each corresponding to a specific data source: H2 in-memory database, MongoDB, and JSON file. + +``` java +public interface CustomerDAO { + + void save(Customer customer); + + void update(Customer customer); + + void delete(T id); + + List> findAll(); + + Optional> findById(T id); +} +``` + +Here is the implementations + +``` java +@Slf4j +@RequiredArgsConstructor +public class H2CustomerDAO implements CustomerDAO { +private final DataSource dataSource; +private final String INSERT_CUSTOMER = "INSERT INTO customer(id, name) VALUES (?, ?)"; +private final String UPDATE_CUSTOMER = "UPDATE customer SET name = ? WHERE id = ?"; +private final String DELETE_CUSTOMER = "DELETE FROM customer WHERE id = ?"; +private final String SELECT_CUSTOMER_BY_ID = "SELECT * FROM customer WHERE id= ?"; +private final String SELECT_ALL_CUSTOMERS = "SELECT * FROM customer"; +private final String CREATE_SCHEMA = +"CREATE TABLE IF NOT EXISTS customer (id BIGINT PRIMARY KEY, name VARCHAR(255))"; +private final String DROP_SCHEMA = "DROP TABLE IF EXISTS customer"; + + @Override + public void save(Customer customer) { + // Implement operation save for H2 + } + + @Override + public void update(Customer customer) { + // Implement operation save for H2 + } + + @Override + public void delete(Long id) { + // Implement operation delete for H2 + } + + @Override + public List> findAll() { + // Implement operation find all for H2 + } + + @Override + public Optional> findById(Long id) { + // Implement operation find by id for H2 + } +} +``` + +``` java +@Slf4j +@RequiredArgsConstructor +public class MongoCustomerDAO implements CustomerDAO { +private final MongoCollection customerCollection; + + // Implement CRUD operation with MongoDB data source +} +``` + +``` java +@Slf4j +@RequiredArgsConstructor +public class FlatFileCustomerDAO implements CustomerDAO { + private final Path filePath; + private final Gson gson; + Type customerListType = new TypeToken>>() { + }.getType(); + + // Implement CRUD operation with Flat file data source +} +``` + +After that, we create an abstract class DAOFactory that defines two key methods: a static method getDataSource() and an abstract method createCustomerDAO(). + +- The getDataSource() method is a factory selector—it returns a concrete DAOFactory instance based on the type of data source requested. + +- Each subclass of DAOFactory will implement the createCustomerDAO() method to provide the corresponding CustomerDAO implementation. + +``` java +public abstract class DAOFactory { + public static DAOFactory getDataSource(DataSourceType dataSourceType) { + return switch (dataSourceType) { + case H2 -> new H2DataSourceFactory(); + case Mongo -> new MongoDataSourceFactory(); + case FlatFile -> new FlatFileDataSourceFactory(); + }; + } + + public abstract CustomerDAO createCustomerDAO(); +} +``` + +We then implement three specific factory classes: + +H2DataSourceFactory for H2 in-memory RDBMS +``` java +public class H2DataSourceFactory extends DAOFactory { + private final String DB_URL = "jdbc:h2:~/test"; + private final String USER = "sa"; + private final String PASS = ""; + + @Override + public CustomerDAO createCustomerDAO() { + return new H2CustomerDAO(createDataSource()); + } + + private DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dataSource.setUser(USER); + dataSource.setPassword(PASS); + return dataSource; + } +} +``` + +MongoDataSourceFactory for MongoDB +``` java +public class MongoDataSourceFactory extends DAOFactory { + private final String CONN_STR = "mongodb://localhost:27017/"; + private final String DB_NAME = "dao_factory"; + private final String COLLECTION_NAME = "customer"; + + @Override + public CustomerDAO createCustomerDAO() { + try { + MongoClient mongoClient = MongoClients.create(CONN_STR); + MongoDatabase database = mongoClient.getDatabase(DB_NAME); + MongoCollection customerCollection = database.getCollection(COLLECTION_NAME); + return new MongoCustomerDAO(customerCollection); + } catch (RuntimeException e) { + throw new RuntimeException("Error: " + e); + } + } +} +``` + +FlatFileDataSourceFactory for flat file storage using JSON +``` java +public class FlatFileDataSourceFactory extends DAOFactory { + private final String FILE_PATH = System.getProperty("user.home") + "/Desktop/customer.json"; + @Override + public CustomerDAO createCustomerDAO() { + Path filePath = Paths.get(FILE_PATH); + Gson gson = new GsonBuilder() + .setPrettyPrinting() + .serializeNulls() + .create(); + return new FlatFileCustomerDAO(filePath, gson); + } +} +``` + +Finally, in the main function of client code, we will demonstrate CRUD operations on the Customer using three data source type. +``` java + // Perform CRUD H2 Database + LOGGER.debug("H2 - Create customer"); + performCreateCustomer(customerDAO, + List.of(customerInmemory1, customerInmemory2, customerInmemory3)); + LOGGER.debug("H2 - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateInmemory); + LOGGER.debug("H2 - Delete customer"); + performDeleteCustomer(customerDAO, 3L); + deleteSchema(customerDAO); + + // Perform CRUD MongoDb + daoFactory = DAOFactory.getDataSource(DataSourceType.Mongo); + customerDAO = daoFactory.createCustomerDAO(); + LOGGER.debug("Mongo - Create customer"); + performCreateCustomer(customerDAO, List.of(customer4, customer5)); + LOGGER.debug("Mongo - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateMongo); + LOGGER.debug("Mongo - Delete customer"); + performDeleteCustomer(customerDAO, idCustomerMongo2); + deleteSchema(customerDAO); + + // Perform CRUD Flat file + daoFactory = DAOFactory.getDataSource(DataSourceType.FlatFile); + customerDAO = daoFactory.createCustomerDAO(); + LOGGER.debug("Flat file - Create customer"); + performCreateCustomer(customerDAO, + List.of(customerFlatFile1, customerFlatFile2, customerFlatFile3)); + LOGGER.debug("Flat file - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateFlatFile); + LOGGER.debug("Flat file - Delete customer"); + performDeleteCustomer(customerDAO, 3L); + deleteSchema(customerDAO); +``` + +The program output +``` java +17:17:24.368 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Create customer +17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Green) +17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red) +17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Blue) +17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Update customer +17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Yellow) +17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red) +17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Blue) +17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Delete customer +17:17:24.632 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Yellow) +17:17:24.632 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red) +17:17:24.747 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Create customer +17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca) +17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c2, name=Elliot) +17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Update customer +17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca) +17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c2, name=Henry) +17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Delete customer +17:17:24.850 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca) +17:17:24.876 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Create customer +17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Duc) +17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang) +17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Nhat) +17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Update customer +17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Thanh) +17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang) +17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Nhat) +17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Delete customer +17:17:24.898 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Thanh) +17:17:24.898 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang) +``` +## When to Use the Data Access Object Factory Pattern in Java + +Use the DAO Factory Pattern when: + +* The application needs to support multiple types of storage (RDBMS, NoSQL, file system, etc.) with minimal changes to business logic. +* You want to abstract and isolate persistence logic from the core application logic. +* You aim to make your data access layer pluggable and easy to extend with new storage technologies. +* You want to enable easier unit testing and dependency injection by providing mock implementations of DAOs. +* Runtime configuration (e.g., via environment variables or application settings) determines which data source to use. + +## Data Access Object Factory Pattern Java Tutorials + +* [Core J2EE Patterns - Data Access Object (Oracle)](https://www.oracle.com/java/technologies/dataaccessobject.html) +* [DAO Factories: Java Design Patterns (Youtube)](https://www.youtube.com/watch?v=5HGe9s9qM-o) +* [Java Design Patterns and Architecture (CaveofProgramming)](https://caveofprogramming.teachable.com/courses/2084/lectures/39549) + +## Real-World Applications of Data Access Object Factory Pattern in Java + +* Enterprise Java Applications: Where switching between test, dev, and production databases is common (e.g., MySQL ↔ MongoDB ↔ In-Memory). +* Spring Data JPA & Repository Abstraction: Though Spring provides its own abstraction, the concept is similar to DAO factory for modular and pluggable persistence. +* Microservices with Varying Storage Backends: Different microservices might store data in SQL, NoSQL, or even flat files; using a DAO Factory per service ensures consistency. +* Data Integration Tools: Tools that support importing/exporting from various formats (CSV, JSON, databases) often use DAO factories behind the scenes. +* Framework-Level Implementations: Custom internal frameworks where persistence layers need to support multiple database types. + +## Benefits and Trade-offs of Data Access Object Factory Pattern + +Benefits: + +* Abstraction of Data Source Logic: Client code interacts only with DAO interfaces, completely decoupled from how and where the data is stored. +* Flexibility in Persistence Strategy: Easily switch between databases (e.g., H2, MongoDB, flat files) by changing the factory configuration. +* Improved Maintainability: Storage logic for each data source is encapsulated within its own DAO implementation and factory, making it easier to update or extend. +* Code Reusability: Common data access logic (e.g., CRUD operations) can be reused across different implementations and projects. +* Testability: DAOs and factories can be mocked or stubbed easily, which supports unit testing and dependency injection. + +Trade-offs: +* Increased Complexity: Introducing abstract DAOs and multiple factory classes adds structural complexity to the codebase. +* Boilerplate Code: Requires defining many interfaces and implementations, even for simple data access needs. +* Less Transparent Behavior: Since clients access DAOs indirectly via factories, understanding the concrete data source behavior may require deeper inspection. + +## Related Java Design Patterns + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): DAO Factory is a concrete application of the Factory Pattern, used to create DAO objects in a flexible way. +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): When supporting multiple data sources (e.g., MySQLDAO, OracleDAO), DAO Factory can act as an Abstract Factory. +* [Data Access Object (DAO)](https://java-design-patterns.com/patterns/data-access-object/): The core pattern managed by DAO Factory, it separates data access logic from business logic. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): DAO Factory is often implemented as a Singleton to ensure only one instance manages DAO creation. +* [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Can be used alongside DAO Factory to retrieve DAO services efficiently. +* [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): In frameworks like Spring, DAOs are typically injected into the service layer instead of being retrieved from a factory. + + +## References and Credits + +* [DAO Factory - J2EE Design Patterns Book](https://www.oreilly.com/library/view/j2ee-design-patterns/0596004273/re15.html) +* [DAO Factory patterns with Hibernate](http://www.giuseppeurso.eu/en/dao-factory-patterns-with-hibernate/) +* [Design Patterns - Java Means DURGA SOFT](https://www.scribd.com/document/407219980/2-DAO-Factory-Design-Pattern) +* [Generic DAO pattern - Hibernate](https://in.relation.to/2005/09/09/generic-dao-pattern-with-jdk-50/) + \ No newline at end of file diff --git a/dao-factory/etc/dao-factory.png b/dao-factory/etc/dao-factory.png new file mode 100644 index 000000000000..d93547d79957 Binary files /dev/null and b/dao-factory/etc/dao-factory.png differ diff --git a/dao-factory/etc/dao-factory.puml b/dao-factory/etc/dao-factory.puml new file mode 100644 index 000000000000..5196c5a1ebd9 --- /dev/null +++ b/dao-factory/etc/dao-factory.puml @@ -0,0 +1,74 @@ +@startuml +package com.iluwatar.daofactory { + class App { + {static} void main(String[] args) + } + + class Customer { + T id + String name + } + + interface CustomerDAO { + void save(Customer customer) + void update(Customer customer) + void delete(ID id) + List> findAll() + Optional> findById(ID id) + void deleteSchema() + } + + abstract class DAOFactory { + {static} DAOFactory getDataSource(DataSourceType dataType) + {abstract} CustomerDAO createCustomerDAO() + } + + enum DataSourceType { + H2 + Mongo + FlatFile + } + + class FlatFileCustomerDAO implements CustomerDAO { + void save(Customer customer) + void update(Customer customer) + void delete(Long id) + List> findAll() + Optional> findById(Long id) + void deleteSchema() + } + + class H2CustomerDAO implements CustomerDAO { + void save(Customer customer) + void update(Customer customer) + void delete(Long id) + List> findAll() + Optional> findById(Long id) + void deleteSchema() + } + + class FlatFileDataSourceFactory extends DAOFactory { + CustomerDAO createCustomerDAO() + } + + class H2DataSourceFactory extends DAOFactory { + CustomerDAO createCustomerDAO() + } + + class MongoCustomerDAO implements CustomerDAO { + void save(Customer customer) + void update(Customer customer) + void delete(ObjectId id) + List> findAll() + Optional> findById(ObjectId id) + void deleteSchema() + } + class MongoDataSourceFactory extends DAOFactory { + CustomerDAO createCustomerDAO() + } + + DataSourceType ..+ DAOFactory + DAOFactory ..+ App + App --> Customer + } +@enduml \ No newline at end of file diff --git a/dao-factory/pom.xml b/dao-factory/pom.xml new file mode 100644 index 000000000000..719ceb9507d5 --- /dev/null +++ b/dao-factory/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + dao-factory + + + + com.h2database + h2 + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.mongodb + mongodb-driver-legacy + + + com.google.code.gson + gson + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + org.mockito + mockito-core + test + + + + \ No newline at end of file diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/App.java b/dao-factory/src/main/java/com/iluwatar/daofactory/App.java new file mode 100644 index 000000000000..b80d3c5ac56a --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/App.java @@ -0,0 +1,124 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import java.io.Serializable; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.bson.types.ObjectId; + +@Slf4j +public class App { + + public static void main(String[] args) { + var daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.H2); + CustomerDAO customerDAO = daoFactory.createCustomerDAO(); + + // Perform CRUD H2 Database + if (customerDAO instanceof H2CustomerDAO h2CustomerDAO) { + h2CustomerDAO.deleteSchema(); + h2CustomerDAO.createSchema(); + } + Customer customerInmemory1 = new Customer<>(1L, "Green"); + Customer customerInmemory2 = new Customer<>(2L, "Red"); + Customer customerInmemory3 = new Customer<>(3L, "Blue"); + Customer customerUpdateInmemory = new Customer<>(1L, "Yellow"); + + LOGGER.debug("H2 - Create customer"); + performCreateCustomer( + customerDAO, List.of(customerInmemory1, customerInmemory2, customerInmemory3)); + LOGGER.debug("H2 - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateInmemory); + LOGGER.debug("H2 - Delete customer"); + performDeleteCustomer(customerDAO, 3L); + deleteSchema(customerDAO); + + // Perform CRUD MongoDb + daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.MONGO); + customerDAO = daoFactory.createCustomerDAO(); + ObjectId idCustomerMongo1 = new ObjectId(); + ObjectId idCustomerMongo2 = new ObjectId(); + Customer customer4 = new Customer<>(idCustomerMongo1, "Masca"); + Customer customer5 = new Customer<>(idCustomerMongo2, "Elliot"); + Customer customerUpdateMongo = new Customer<>(idCustomerMongo2, "Henry"); + + LOGGER.debug("Mongo - Create customer"); + performCreateCustomer(customerDAO, List.of(customer4, customer5)); + LOGGER.debug("Mongo - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateMongo); + LOGGER.debug("Mongo - Delete customer"); + performDeleteCustomer(customerDAO, idCustomerMongo2); + deleteSchema(customerDAO); + + // Perform CRUD Flat file + daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.FLAT_FILE); + customerDAO = daoFactory.createCustomerDAO(); + Customer customerFlatFile1 = new Customer<>(1L, "Duc"); + Customer customerFlatFile2 = new Customer<>(2L, "Quang"); + Customer customerFlatFile3 = new Customer<>(3L, "Nhat"); + Customer customerUpdateFlatFile = new Customer<>(1L, "Thanh"); + LOGGER.debug("Flat file - Create customer"); + performCreateCustomer( + customerDAO, List.of(customerFlatFile1, customerFlatFile2, customerFlatFile3)); + LOGGER.debug("Flat file - Update customer"); + performUpdateCustomer(customerDAO, customerUpdateFlatFile); + LOGGER.debug("Flat file - Delete customer"); + performDeleteCustomer(customerDAO, 3L); + deleteSchema(customerDAO); + } + + public static void deleteSchema(CustomerDAO customerDAO) { + customerDAO.deleteSchema(); + } + + public static void performCreateCustomer( + CustomerDAO customerDAO, List> customerList) { + for (Customer customer : customerList) { + customerDAO.save(customer); + } + List> customers = customerDAO.findAll(); + for (Customer customer : customers) { + LOGGER.debug(customer.toString()); + } + } + + public static void performUpdateCustomer( + CustomerDAO customerDAO, Customer customerUpdate) { + customerDAO.update(customerUpdate); + List> customers = customerDAO.findAll(); + for (Customer customer : customers) { + LOGGER.debug(customer.toString()); + } + } + + public static void performDeleteCustomer( + CustomerDAO customerDAO, T customerId) { + customerDAO.delete(customerId); + List> customers = customerDAO.findAll(); + for (Customer customer : customers) { + LOGGER.debug(customer.toString()); + } + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/CustomException.java b/dao-factory/src/main/java/com/iluwatar/daofactory/CustomException.java new file mode 100644 index 000000000000..9559e765c7d4 --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/CustomException.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +/** Customer exception */ +public class CustomException extends RuntimeException { + public CustomException(String message) { + super(message); + } + + public CustomException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/Customer.java b/dao-factory/src/main/java/com/iluwatar/daofactory/Customer.java new file mode 100644 index 000000000000..95b675487d27 --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/Customer.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * A customer generic POJO that represents the data that can be stored in any supported data source. + * This class is designed t work with various ID types (e.g., Long, String, or ObjectId) through + * generic, making it adaptable to different persistence system. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class Customer implements Serializable { + private T id; + private String name; +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/CustomerDAO.java b/dao-factory/src/main/java/com/iluwatar/daofactory/CustomerDAO.java new file mode 100644 index 000000000000..34316b4c49af --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/CustomerDAO.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import java.io.Serializable; +import java.util.List; +import java.util.Optional; + +/** + * The Data Access Object (DAO) pattern provides an abstraction layer between the application and + * the database. It encapsulates data access logic, allowing the application to work with domain + * objects instead of direct database operations. + * + *

Implementations handle specific storage mechanisms (e.g., in-memory, databases) while keeping + * client code unchanged. + * + * @see H2CustomerDAO + * @see MongoCustomerDAO + * @see FlatFileCustomerDAO + */ +public interface CustomerDAO { + /** + * Persist the given customer + * + * @param customer the customer to persist + */ + void save(Customer customer); + + /** + * Update the given customer + * + * @param customer the customer to update + */ + void update(Customer customer); + + /** + * Delete the customer with the given id + * + * @param id the id of the customer to delete + */ + void delete(T id); + + /** + * Find all customers + * + * @return a list of customers + */ + List> findAll(); + + /** + * Find the customer with the given id + * + * @param id the id of the customer to find + * @return the customer with the given id + */ + Optional> findById(T id); + + /** + * Delete the customer schema. After executing the statements, this function will be called to + * clean up the data and delete the records. + */ + void deleteSchema(); +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactory.java b/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactory.java new file mode 100644 index 000000000000..e7d33186bec5 --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactory.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +/** + * An abstract factory class that provides a way to create concrete DAO (Data Access Object) + * factories for different data sources types (e.g., H2, Mongo, FlatFile). + * + *

This class follows the Abstract Factory design pattern, allowing applications to retrieve the + * approriate DAO implementation without being tightly coupled to a specific data source. + * + * @see H2DataSourceFactory + * @see MongoDataSourceFactory + * @see FlatFileDataSourceFactory + */ +public abstract class DAOFactory { + /** + * Retrieves a {@link CustomerDAO} implementation specific to the underlying data source.. + * + * @return A data source-specific implementation of {@link CustomerDAO} + */ + public abstract CustomerDAO createCustomerDAO(); +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactoryProvider.java b/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactoryProvider.java new file mode 100644 index 000000000000..08585622d00d --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactoryProvider.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +/** + * {@code DAOFactoryProvider} is a utility class responsible for providing concrete implementations + * of the {@link DAOFactory} interface based on the specified data source type. + * + *

This class acts as an entry point to obtain DAO factories for different storage mechanisms + * such as relational databases (e.g., H2), document stores (e.g., MongoDB), or file-based systems. + * It uses the {@link DataSourceType} enumeration to determine which concrete factory to + * instantiate. + * + *

Example usage: + * + *

{@code
+ * DAOFactory factory = DAOFactoryProvider.getDataSource(DataSourceType.H2);
+ * }
+ */ +public class DAOFactoryProvider { + + private DAOFactoryProvider() {} + + /** + * Returns a concrete {@link DAOFactory} intance based on the specified data source type. + * + * @param dataSourceType The type of data source for which a factory is needed. Supported values: + * {@code H2}, {@code Mongo}, {@code FlatFile} + * @return A {@link DAOFactory} implementation corresponding to the given data source type. + * @throws IllegalArgumentException if the given data source type is not supported. + */ + public static DAOFactory getDataSource(DataSourceType dataSourceType) { + return switch (dataSourceType) { + case H2 -> new H2DataSourceFactory(); + case MONGO -> new MongoDataSourceFactory(); + case FLAT_FILE -> new FlatFileDataSourceFactory(); + default -> throw new IllegalArgumentException("Unsupported data source type"); + }; + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/DataSourceType.java b/dao-factory/src/main/java/com/iluwatar/daofactory/DataSourceType.java new file mode 100644 index 000000000000..da01d451f09e --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/DataSourceType.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +/** Enumerates the types of data sources supported by the application. */ +public enum DataSourceType { + H2, + MONGO, + FLAT_FILE +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileCustomerDAO.java b/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileCustomerDAO.java new file mode 100644 index 000000000000..8f1f1f144f77 --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileCustomerDAO.java @@ -0,0 +1,175 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * A Flat File implementation of {@link CustomerDAO}, which store the customer data in a JSON file + * at path {@code ~/Desktop/customer.json}. + */ +@Slf4j +@RequiredArgsConstructor +public class FlatFileCustomerDAO implements CustomerDAO { + private final Path filePath; + private final Gson gson; + Type customerListType = new TypeToken>>() {}.getType(); + + protected Reader createReader(Path filePath) throws IOException { + return new FileReader(filePath.toFile()); + } + + protected Writer createWriter(Path filePath) throws IOException { + return new FileWriter(filePath.toFile()); + } + + /** {@inheritDoc} */ + @Override + public void save(Customer customer) { + List> customers = new LinkedList<>(); + if (filePath.toFile().exists()) { + try (Reader reader = createReader(filePath)) { + customers = gson.fromJson(reader, customerListType); + } catch (IOException ex) { + throw new CustomException("Failed to read customer data", ex); + } + } + customers.add(customer); + try (Writer writer = createWriter(filePath)) { + gson.toJson(customers, writer); + } catch (IOException ex) { + throw new CustomException("Failed to write customer data", ex); + } + } + + /** {@inheritDoc} */ + @Override + public void update(Customer customer) { + if (!filePath.toFile().exists()) { + throw new CustomException("File not found"); + } + List> customers; + try (Reader reader = createReader(filePath)) { + customers = gson.fromJson(reader, customerListType); + } catch (IOException ex) { + throw new CustomException("Failed to read customer data", ex); + } + customers.stream() + .filter(c -> c.getId().equals(customer.getId())) + .findFirst() + .ifPresentOrElse( + c -> c.setName(customer.getName()), + () -> { + throw new CustomException("Customer not found with id: " + customer.getId()); + }); + try (Writer writer = createWriter(filePath)) { + gson.toJson(customers, writer); + } catch (IOException ex) { + throw new CustomException("Failed to write customer data", ex); + } + } + + /** {@inheritDoc} */ + @Override + public void delete(Long id) { + if (!filePath.toFile().exists()) { + throw new CustomException("File not found"); + } + List> customers; + try (Reader reader = createReader(filePath)) { + customers = gson.fromJson(reader, customerListType); + } catch (IOException ex) { + throw new CustomException("Failed to read customer data", ex); + } + Customer customerToRemove = + customers.stream() + .filter(c -> c.getId().equals(id)) + .findFirst() + .orElseThrow(() -> new CustomException("Customer not found with id: " + id)); + customers.remove(customerToRemove); + try (Writer writer = createWriter(filePath)) { + gson.toJson(customers, writer); + } catch (IOException ex) { + throw new CustomException("Failed to write customer data", ex); + } + } + + /** {@inheritDoc} */ + @Override + public List> findAll() { + if (!filePath.toFile().exists()) { + throw new CustomException("File not found"); + } + List> customers; + try (Reader reader = createReader(filePath)) { + customers = gson.fromJson(reader, customerListType); + } catch (IOException ex) { + throw new CustomException("Failed to read customer data", ex); + } + return customers; + } + + /** {@inheritDoc} */ + @Override + public Optional> findById(Long id) { + if (!filePath.toFile().exists()) { + throw new CustomException("File not found"); + } + List> customers = null; + try (Reader reader = createReader(filePath)) { + customers = gson.fromJson(reader, customerListType); + } catch (IOException ex) { + throw new CustomException("Failed to read customer data", ex); + } + return customers.stream().filter(c -> c.getId().equals(id)).findFirst(); + } + + /** {@inheritDoc} */ + @Override + public void deleteSchema() { + if (!filePath.toFile().exists()) { + throw new CustomException("File not found"); + } + try { + Files.delete(filePath); + } catch (IOException ex) { + throw new CustomException("Failed to delete customer data"); + } + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileDataSourceFactory.java b/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileDataSourceFactory.java new file mode 100644 index 000000000000..f423376703b5 --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileDataSourceFactory.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** FlatFileDataSourceFactory concrete factory. */ +public class FlatFileDataSourceFactory extends DAOFactory { + private static final String FILE_PATH = + System.getProperty("user.home") + "/Desktop/customer.json"; + + @Override + public CustomerDAO createCustomerDAO() { + Path filePath = Paths.get(FILE_PATH); + Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); + return new FlatFileCustomerDAO(filePath, gson); + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/H2CustomerDAO.java b/dao-factory/src/main/java/com/iluwatar/daofactory/H2CustomerDAO.java new file mode 100644 index 000000000000..fe027426391c --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/H2CustomerDAO.java @@ -0,0 +1,179 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import javax.sql.DataSource; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * An implementation of {@link CustomerDAO} that uses H2 database (http://www.h2database.com/) which + * is an in-memory database and data will lost after application exits. + */ +@Slf4j +@RequiredArgsConstructor +public class H2CustomerDAO implements CustomerDAO { + private final DataSource dataSource; + private static final String INSERT_CUSTOMER = "INSERT INTO customer(id, name) VALUES (?, ?)"; + private static final String UPDATE_CUSTOMER = "UPDATE customer SET name = ? WHERE id = ?"; + private static final String DELETE_CUSTOMER = "DELETE FROM customer WHERE id = ?"; + private static final String SELECT_CUSTOMER_BY_ID = + "SELECT customer.id, customer.name FROM customer WHERE id= ?"; + private static final String SELECT_ALL_CUSTOMERS = "SELECT customer.* FROM customer"; + private static final String CREATE_SCHEMA = + "CREATE TABLE IF NOT EXISTS customer (id BIGINT PRIMARY KEY, name VARCHAR(255))"; + private static final String DROP_SCHEMA = "DROP TABLE IF EXISTS customer"; + + /** {@inheritDoc} */ + @Override + public void save(Customer customer) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement saveStatement = connection.prepareStatement(INSERT_CUSTOMER)) { + saveStatement.setLong(1, customer.getId()); + saveStatement.setString(2, customer.getName()); + saveStatement.execute(); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } + + /** {@inheritDoc} */ + @Override + public void update(Customer customer) { + if (Objects.isNull(customer) || Objects.isNull(customer.getId())) { + throw new CustomException("Custome null or customer id null"); + } + try (Connection connection = dataSource.getConnection(); + PreparedStatement selectStatement = connection.prepareStatement(SELECT_CUSTOMER_BY_ID); + PreparedStatement updateStatement = connection.prepareStatement(UPDATE_CUSTOMER)) { + selectStatement.setLong(1, customer.getId()); + try (ResultSet resultSet = selectStatement.executeQuery()) { + if (!resultSet.next()) { + throw new CustomException("Customer not found with id: " + customer.getId()); + } + } + updateStatement.setString(1, customer.getName()); + updateStatement.setLong(2, customer.getId()); + updateStatement.executeUpdate(); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } + + /** {@inheritDoc} */ + @Override + public void delete(Long id) { + if (Objects.isNull(id)) { + throw new CustomException("Customer id null"); + } + try (Connection connection = dataSource.getConnection(); + PreparedStatement selectStatement = connection.prepareStatement(SELECT_CUSTOMER_BY_ID); + PreparedStatement deleteStatement = connection.prepareStatement(DELETE_CUSTOMER)) { + selectStatement.setLong(1, id); + try (ResultSet resultSet = selectStatement.executeQuery()) { + if (!resultSet.next()) { + throw new CustomException("Customer not found with id: " + id); + } + } + deleteStatement.setLong(1, id); + deleteStatement.execute(); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } + + /** {@inheritDoc} */ + @Override + public List> findAll() { + List> customers = new LinkedList<>(); + try (Connection connection = dataSource.getConnection(); + PreparedStatement selectStatement = connection.prepareStatement(SELECT_ALL_CUSTOMERS)) { + try (ResultSet resultSet = selectStatement.executeQuery()) { + while (resultSet.next()) { + Long idCustomer = resultSet.getLong("id"); + String nameCustomer = resultSet.getString("name"); + customers.add(new Customer<>(idCustomer, nameCustomer)); + } + } + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + return customers; + } + + /** {@inheritDoc} */ + @Override + public Optional> findById(Long id) { + if (Objects.isNull(id)) { + throw new CustomException("Customer id null"); + } + Customer customer = null; + try (Connection connection = dataSource.getConnection(); + PreparedStatement selectByIdStatement = + connection.prepareStatement(SELECT_CUSTOMER_BY_ID)) { + selectByIdStatement.setLong(1, id); + try (ResultSet resultSet = selectByIdStatement.executeQuery()) { + while (resultSet.next()) { + Long idCustomer = resultSet.getLong("id"); + String nameCustomer = resultSet.getString("name"); + customer = new Customer<>(idCustomer, nameCustomer); + } + } + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + return Optional.ofNullable(customer); + } + + /** Create customer schema. */ + public void createSchema() { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute(CREATE_SCHEMA); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } + + /** {@inheritDoc}} */ + @Override + public void deleteSchema() { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); ) { + statement.execute(DROP_SCHEMA); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/H2DataSourceFactory.java b/dao-factory/src/main/java/com/iluwatar/daofactory/H2DataSourceFactory.java new file mode 100644 index 000000000000..dbb39dd98f3b --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/H2DataSourceFactory.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; + +/** H2DataSourceFactory concrete factory. */ +public class H2DataSourceFactory extends DAOFactory { + private static final String DB_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"; + private static final String USER = "sa"; + private static final String PASS = ""; + + @Override + public CustomerDAO createCustomerDAO() { + return new H2CustomerDAO(createDataSource()); + } + + private DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dataSource.setUser(USER); + dataSource.setPassword(PASS); + return dataSource; + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/MongoCustomerDAO.java b/dao-factory/src/main/java/com/iluwatar/daofactory/MongoCustomerDAO.java new file mode 100644 index 000000000000..1870f61e85fd --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/MongoCustomerDAO.java @@ -0,0 +1,106 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import com.mongodb.client.result.DeleteResult; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; + +/** An implementation of {@link CustomerDAO} that uses MongoDB (https://www.mongodb.com/) */ +@Slf4j +@RequiredArgsConstructor +public class MongoCustomerDAO implements CustomerDAO { + private final MongoCollection customerCollection; + + /** {@inheritDoc} */ + @Override + public void save(Customer customer) { + Document customerDocument = new Document("_id", customer.getId()); + customerDocument.append("name", customer.getName()); + customerCollection.insertOne(customerDocument); + } + + /** {@inheritDoc} */ + @Override + public void update(Customer customer) { + Document updateQuery = new Document("_id", customer.getId()); + Bson update = Updates.set("name", customer.getName()); + customerCollection.updateOne(updateQuery, update); + } + + /** {@inheritDoc} */ + @Override + public void delete(ObjectId objectId) { + Bson deleteQuery = Filters.eq("_id", objectId); + DeleteResult deleteResult = customerCollection.deleteOne(deleteQuery); + if (deleteResult.getDeletedCount() == 0) { + throw new CustomException("Delete failed: No document found with id: " + objectId); + } + } + + /** {@inheritDoc} */ + @Override + public List> findAll() { + List> customers = new LinkedList<>(); + FindIterable customerDocuments = customerCollection.find(); + for (Document customerDocument : customerDocuments) { + Customer customer = + new Customer<>( + (ObjectId) customerDocument.get("_id"), customerDocument.getString("name")); + customers.add(customer); + } + return customers; + } + + /** {@inheritDoc} */ + @Override + public Optional> findById(ObjectId objectId) { + Bson filter = Filters.eq("_id", objectId); + Document customerDocument = customerCollection.find(filter).first(); + Customer customerResult = null; + if (customerDocument != null) { + customerResult = + new Customer<>( + (ObjectId) customerDocument.get("_id"), customerDocument.getString("name")); + } + return Optional.ofNullable(customerResult); + } + + /** {@inheritDoc} */ + @Override + public void deleteSchema() { + customerCollection.drop(); + } +} diff --git a/dao-factory/src/main/java/com/iluwatar/daofactory/MongoDataSourceFactory.java b/dao-factory/src/main/java/com/iluwatar/daofactory/MongoDataSourceFactory.java new file mode 100644 index 000000000000..5a7b1f1b1ece --- /dev/null +++ b/dao-factory/src/main/java/com/iluwatar/daofactory/MongoDataSourceFactory.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import org.bson.types.ObjectId; + +/** MongoDataSourceFactory concrete factory. */ +public class MongoDataSourceFactory extends DAOFactory { + private static final String CONN_STR = "mongodb://localhost:27017/"; + private static final String DB_NAME = "dao_factory"; + private static final String COLLECTION_NAME = "customer"; + + @Override + public CustomerDAO createCustomerDAO() { + try { + MongoClient mongoClient = MongoClients.create(CONN_STR); + MongoDatabase database = mongoClient.getDatabase(DB_NAME); + MongoCollection customerCollection = database.getCollection(COLLECTION_NAME); + return new MongoCustomerDAO(customerCollection); + } catch (CustomException e) { + throw new CustomException("Error: " + e); + } + } +} diff --git a/dao-factory/src/main/resources/logback.xml b/dao-factory/src/main/resources/logback.xml new file mode 100644 index 000000000000..f82341ebb2ab --- /dev/null +++ b/dao-factory/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{15}) %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/dao-factory/src/test/java/com/iluwatar/daofactory/AppTest.java b/dao-factory/src/test/java/com/iluwatar/daofactory/AppTest.java new file mode 100644 index 000000000000..12efea42bdc6 --- /dev/null +++ b/dao-factory/src/test/java/com/iluwatar/daofactory/AppTest.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import org.bson.types.ObjectId; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** {@link App} */ +class AppTest { + /** Test perform CRUD in main class */ + private CustomerDAO mockLongCustomerDAO; + + private CustomerDAO mockObjectIdCustomerDAO; + + @BeforeEach + void setUp() { + mockLongCustomerDAO = mock(CustomerDAO.class); + mockObjectIdCustomerDAO = mock(CustomerDAO.class); + } + + @Test + void testPerformCreateCustomerWithLongId() { + Customer c1 = new Customer<>(1L, "Test1"); + Customer c2 = new Customer<>(2L, "Test2"); + + when(mockLongCustomerDAO.findAll()).thenReturn(List.of(c1, c2)); + + App.performCreateCustomer(mockLongCustomerDAO, List.of(c1, c2)); + + verify(mockLongCustomerDAO).save(c1); + verify(mockLongCustomerDAO).save(c2); + verify(mockLongCustomerDAO).findAll(); + } + + @Test + void testPerformUpdateCustomerWithObjectId() { + ObjectId id = new ObjectId(); + Customer updatedCustomer = new Customer<>(id, "Updated"); + + when(mockObjectIdCustomerDAO.findAll()).thenReturn(List.of(updatedCustomer)); + + App.performUpdateCustomer(mockObjectIdCustomerDAO, updatedCustomer); + + verify(mockObjectIdCustomerDAO).update(updatedCustomer); + verify(mockObjectIdCustomerDAO).findAll(); + } + + @Test + void testPerformDeleteCustomerWithLongId() { + Long id = 100L; + Customer remainingCustomer = new Customer<>(1L, "Remaining"); + + when(mockLongCustomerDAO.findAll()).thenReturn(List.of(remainingCustomer)); + + App.performDeleteCustomer(mockLongCustomerDAO, id); + + verify(mockLongCustomerDAO).delete(id); + verify(mockLongCustomerDAO).findAll(); + } + + @Test + void testDeleteSchema() { + App.deleteSchema(mockLongCustomerDAO); + verify(mockLongCustomerDAO).deleteSchema(); + } +} diff --git a/dao-factory/src/test/java/com/iluwatar/daofactory/DAOFactoryTest.java b/dao-factory/src/test/java/com/iluwatar/daofactory/DAOFactoryTest.java new file mode 100644 index 000000000000..f8aaf199762d --- /dev/null +++ b/dao-factory/src/test/java/com/iluwatar/daofactory/DAOFactoryTest.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import org.junit.jupiter.api.Test; + +/** {@link DAOFactory} */ +class DAOFactoryTest { + + @Test + void verifyH2CustomerDAOCreation() { + var daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.H2); + var customerDAO = daoFactory.createCustomerDAO(); + assertInstanceOf(H2CustomerDAO.class, customerDAO); + } + + @Test + void verifyMongoCustomerDAOCreation() { + var daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.MONGO); + var customerDAO = daoFactory.createCustomerDAO(); + assertInstanceOf(MongoCustomerDAO.class, customerDAO); + } + + @Test + void verifyFlatFileCustomerDAOCreation() { + var daoFactory = DAOFactoryProvider.getDataSource(DataSourceType.FLAT_FILE); + var customerDAO = daoFactory.createCustomerDAO(); + assertInstanceOf(FlatFileCustomerDAO.class, customerDAO); + } +} diff --git a/dao-factory/src/test/java/com/iluwatar/daofactory/FlatFileCustomerDAOTest.java b/dao-factory/src/test/java/com/iluwatar/daofactory/FlatFileCustomerDAOTest.java new file mode 100644 index 000000000000..470964f4217a --- /dev/null +++ b/dao-factory/src/test/java/com/iluwatar/daofactory/FlatFileCustomerDAOTest.java @@ -0,0 +1,500 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +/** {@link FlatFileCustomerDAO} */ +class FlatFileCustomerDAOTest { + private Path filePath; + private File file; + private Gson gson; + + private final Type customerListType = new TypeToken>>() {}.getType(); + private final Customer existingCustomer = new Customer<>(1L, "Thanh"); + private FlatFileCustomerDAO flatFileCustomerDAO; + private FileReader fileReader; + private FileWriter fileWriter; + + @BeforeEach + void setUp() { + filePath = mock(Path.class); + file = mock(File.class); + gson = mock(Gson.class); + fileReader = mock(FileReader.class); + fileWriter = mock(FileWriter.class); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + return fileWriter; + } + }; + when(filePath.toFile()).thenReturn(file); + } + + /** Class test with scenario Save Customer */ + @Nested + class Save { + @Test + void giveFilePathNotExist_whenSaveCustomer_thenCreateNewFileWithCustomer() { + when(file.exists()).thenReturn(false); + flatFileCustomerDAO.save(existingCustomer); + + verify(gson) + .toJson( + argThat( + (List> list) -> + list.size() == 1 && list.getFirst().equals(existingCustomer)), + eq(fileWriter)); + } + + @Test + void givenEmptyFileExist_whenSaveCustomer_thenAddCustomer() { + when(file.exists()).thenReturn(true); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(new LinkedList<>()); + flatFileCustomerDAO.save(existingCustomer); + + verify(gson).fromJson(fileReader, customerListType); + verify(gson) + .toJson( + argThat( + (List> list) -> + list.size() == 1 && list.getFirst().equals(existingCustomer)), + eq(fileWriter)); + } + + @Test + void givenFileWithCustomerExist_whenSaveCustomer_thenShouldAppendCustomer() { + List> customers = new LinkedList<>(); + customers.add(new Customer<>(2L, "Duc")); + customers.add(new Customer<>(3L, "Nguyen")); + when(file.exists()).thenReturn(true); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(customers); + + flatFileCustomerDAO.save(existingCustomer); + + verify(gson).fromJson(fileReader, customerListType); + verify(gson).toJson(argThat((List> list) -> list.size() == 3), eq(fileWriter)); + } + + @Test + void whenReadFails_thenThrowException() { + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + throw new IOException("Failed to read file"); + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + when(file.exists()).thenReturn(true); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.save(existingCustomer)); + } + + @Test + void whenWriteFails_thenThrowException() { + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(new LinkedList<>()); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + throw new IOException("Failed to write file"); + } + }; + when(file.exists()).thenReturn(true); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.save(existingCustomer)); + } + } + + /** Class test with scenario Update Customer */ + @Nested + class Update { + @Test + void givenFilePathNotExist_whenUpdateCustomer_thenThrowException() { + when(file.exists()).thenReturn(false); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.update(existingCustomer)); + } + + @Test + void whenReadFails_thenThrowException() { + when(file.exists()).thenReturn(true); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + throw new IOException("Failed to read file"); + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.update(existingCustomer)); + } + + @Test + void whenWriteFails_thenThrowException() { + when(file.exists()).thenReturn(true); + when(gson.fromJson(any(Reader.class), eq(customerListType))) + .thenReturn( + new LinkedList<>() { + { + add(new Customer<>(1L, "Quang")); + } + }); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + throw new IOException("Failed to write file"); + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.update(existingCustomer)); + } + + @Test + void givenValidCustomer_whenUpdateCustomer_thenUpdateSucceed() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + return fileWriter; + } + }; + flatFileCustomerDAO.update(existingCustomer); + verify(gson) + .toJson( + argThat( + (List> customers) -> + customers.size() == 1 + && customers.stream() + .anyMatch(c -> c.getId().equals(1L) && c.getName().equals("Thanh"))), + eq(fileWriter)); + } + + @Test + void givenIdCustomerNotExist_whenUpdateCustomer_thenThrowException() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(2L, "Quang")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.update(existingCustomer)); + } + } + + /** Class test with scenario Delete Customer */ + @Nested + class Delete { + @Test + void givenFilePathNotExist_whenDeleteCustomer_thenThrowException() { + when(file.exists()).thenReturn(false); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.delete(1L)); + } + + @Test + void whenReadFails_thenThrowException() { + when(file.exists()).thenReturn(true); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + throw new IOException("Failed to read file"); + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.delete(1L)); + } + + @Test + void whenWriteFails_thenThrowException() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) throws IOException { + throw new IOException("Failed to write file"); + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.delete(1L)); + } + + @Test + void givenValidId_whenDeleteCustomer_thenDeleteSucceed() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + existingListCustomer.add(new Customer<>(2L, "Thanh")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + + flatFileCustomerDAO.delete(1L); + assertEquals(1, existingListCustomer.size()); + verify(gson) + .toJson( + argThat( + (List> customers) -> + customers.stream() + .noneMatch(c -> c.getId().equals(1L) && c.getName().equals("Quang"))), + eq(fileWriter)); + } + + @Test + void givenIdNotExist_whenDeleteCustomer_thenThrowException() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + existingListCustomer.add(new Customer<>(2L, "Thanh")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) { + return fileReader; + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.delete(3L)); + } + } + + /** Class test with scenario Find All Customer */ + @Nested + class FindAll { + @Test + void givenFileNotExist_thenThrowException() { + when(file.exists()).thenReturn(false); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.findAll()); + } + + @Test + void whenReadFails_thenThrowException() { + when(file.exists()).thenReturn(true); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + throw new IOException("Failed to read file"); + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.findAll()); + } + + @Test + void givenEmptyCustomer_thenReturnEmptyList() { + when(file.exists()).thenReturn(true); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(new LinkedList<>()); + List> customers = flatFileCustomerDAO.findAll(); + assertEquals(0, customers.size()); + verify(gson).fromJson(fileReader, customerListType); + } + + @Test + void givenCustomerExist_thenReturnCustomerList() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + existingListCustomer.add(new Customer<>(2L, "Thanh")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + List> customers = flatFileCustomerDAO.findAll(); + assertEquals(2, customers.size()); + } + } + + /** Class test with scenario Find By Id Customer */ + @Nested + class FindById { + + @Test + void givenFilePathNotExist_whenFindById_thenThrowException() { + when(file.exists()).thenReturn(false); + assertThrows(CustomException.class, () -> flatFileCustomerDAO.findById(1L)); + } + + @Test + void whenReadFails_thenThrowException() { + when(file.exists()).thenReturn(true); + flatFileCustomerDAO = + new FlatFileCustomerDAO(filePath, gson) { + @Override + protected Reader createReader(Path filePath) throws IOException { + throw new IOException("Failed to read file"); + } + + @Override + protected Writer createWriter(Path filePath) { + return fileWriter; + } + }; + assertThrows(CustomException.class, () -> flatFileCustomerDAO.findById(1L)); + } + + @Test + void givenIdCustomerExist_whenFindById_thenReturnCustomer() { + when(file.exists()).thenReturn(true); + List> existingListCustomer = new LinkedList<>(); + existingListCustomer.add(new Customer<>(1L, "Quang")); + existingListCustomer.add(new Customer<>(2L, "Thanh")); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(existingListCustomer); + Optional> customer = flatFileCustomerDAO.findById(1L); + assertTrue(customer.isPresent()); + assertEquals("Quang", customer.get().getName()); + } + + @Test + void givenIdCustomerNotExist_whenFindById_thenReturnEmpty() { + when(file.exists()).thenReturn(true); + when(gson.fromJson(any(Reader.class), eq(customerListType))).thenReturn(new LinkedList<>()); + Optional> customers = flatFileCustomerDAO.findById(1L); + assertTrue(customers.isEmpty()); + } + } + + /** Clas test with scenario Delete schema */ + @Nested + class DeleteSchema { + @Test + void givenFilePathExist_thenDeleteFile() { + when(file.exists()).thenReturn(true); + + try (MockedStatic mockedFiles = mockStatic(Files.class)) { + flatFileCustomerDAO.deleteSchema(); + mockedFiles.verify(() -> Files.delete(filePath), times(1)); + } + } + + @Test + void givenFilePathNotExist_thenThrowException() { + when(file.exists()).thenReturn(false); + + try (MockedStatic mockedFiles = mockStatic(Files.class)) { + assertThrows(CustomException.class, () -> flatFileCustomerDAO.deleteSchema()); + mockedFiles.verify(() -> Files.delete(filePath), times(0)); + } + } + } +} diff --git a/dao-factory/src/test/java/com/iluwatar/daofactory/H2CustomerDAOTest.java b/dao-factory/src/test/java/com/iluwatar/daofactory/H2CustomerDAOTest.java new file mode 100644 index 000000000000..ce7def36e5bc --- /dev/null +++ b/dao-factory/src/test/java/com/iluwatar/daofactory/H2CustomerDAOTest.java @@ -0,0 +1,300 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.List; +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** Tests {@link H2CustomerDAO} */ +class H2CustomerDAOTest { + private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; + private static final String USER = "sa"; + private static final String PASS = ""; + private static final String CREATE_SCHEMA = + "CREATE TABLE IF NOT EXISTS customer (id BIGINT PRIMARY KEY, name VARCHAR(255))"; + private static final String DROP_SCHEMA = "DROP TABLE IF EXISTS customer"; + private final Customer existingCustomer = new Customer<>(1L, "Nguyen"); + private H2CustomerDAO h2CustomerDAO; + + @BeforeEach + void createSchema() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL, USER, PASS); + var statement = connection.createStatement()) { + statement.execute(CREATE_SCHEMA); + } + } + + @AfterEach + void deleteSchema() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL, USER, PASS); + var statement = connection.createStatement()) { + statement.execute(DROP_SCHEMA); + } + } + + /** Class test for scenario connect with datasource succeed */ + @Nested + class ConnectionSucceed { + + @BeforeEach + void setUp() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dataSource.setUser(USER); + dataSource.setPassword(PASS); + h2CustomerDAO = new H2CustomerDAO(dataSource); + assertDoesNotThrow(() -> h2CustomerDAO.save(existingCustomer)); + var customer = h2CustomerDAO.findById(existingCustomer.getId()); + assertTrue(customer.isPresent()); + assertEquals(customer.get().getName(), existingCustomer.getName()); + assertEquals(customer.get().getId(), existingCustomer.getId()); + } + + @Nested + class SaveCustomer { + @Test + void givenValidCustomer_whenSaveCustomer_thenAddSucceed() { + var customer = new Customer<>(2L, "Duc"); + assertDoesNotThrow(() -> h2CustomerDAO.save(customer)); + var customerInDb = h2CustomerDAO.findById(customer.getId()); + assertTrue(customerInDb.isPresent()); + assertEquals(customerInDb.get().getName(), customer.getName()); + assertEquals(customerInDb.get().getId(), customer.getId()); + List> customers = h2CustomerDAO.findAll(); + assertEquals(2, customers.size()); + } + + @Test + void givenIdCustomerDuplicated_whenSaveCustomer_thenThrowException() { + var customer = new Customer<>(existingCustomer.getId(), "Duc"); + assertThrows(CustomException.class, () -> h2CustomerDAO.save(customer)); + List> customers = h2CustomerDAO.findAll(); + assertEquals(1, customers.size()); + } + } + + @Nested + class UpdateCustomer { + @Test + void givenValidCustomer_whenUpdateCustomer_thenUpdateSucceed() { + var customerUpdate = new Customer<>(existingCustomer.getId(), "Duc"); + assertDoesNotThrow(() -> h2CustomerDAO.update(customerUpdate)); + var customerInDb = h2CustomerDAO.findById(customerUpdate.getId()); + assertTrue(customerInDb.isPresent()); + assertEquals(customerInDb.get().getName(), customerUpdate.getName()); + } + + @Test + void givenIdCustomerNotExist_whenUpdateCustomer_thenThrowException() { + var customerUpdate = new Customer<>(100L, "Duc"); + var customerInDb = h2CustomerDAO.findById(customerUpdate.getId()); + assertTrue(customerInDb.isEmpty()); + assertThrows(CustomException.class, () -> h2CustomerDAO.update(customerUpdate)); + } + + @Test + void givenNull_whenUpdateCustomer_thenThrowException() { + assertThrows(CustomException.class, () -> h2CustomerDAO.update(null)); + List> customers = h2CustomerDAO.findAll(); + assertEquals(1, customers.size()); + } + } + + @Nested + class DeleteCustomer { + @Test + void givenValidId_whenDeleteCustomer_thenDeleteSucceed() { + assertDoesNotThrow(() -> h2CustomerDAO.delete(existingCustomer.getId())); + var customerInDb = h2CustomerDAO.findById(existingCustomer.getId()); + assertTrue(customerInDb.isEmpty()); + List> customers = h2CustomerDAO.findAll(); + assertEquals(0, customers.size()); + } + + @Test + void givenIdCustomerNotExist_whenDeleteCustomer_thenThrowException() { + var customerInDb = h2CustomerDAO.findById(100L); + assertTrue(customerInDb.isEmpty()); + assertThrows(CustomException.class, () -> h2CustomerDAO.delete(100L)); + List> customers = h2CustomerDAO.findAll(); + assertEquals(1, customers.size()); + assertEquals(existingCustomer.getName(), customers.get(0).getName()); + assertEquals(existingCustomer.getId(), customers.get(0).getId()); + } + + @Test + void givenNull_whenDeleteCustomer_thenThrowException() { + assertThrows(CustomException.class, () -> h2CustomerDAO.delete(null)); + List> customers = h2CustomerDAO.findAll(); + assertEquals(1, customers.size()); + assertEquals(existingCustomer.getName(), customers.get(0).getName()); + } + } + + @Nested + class FindAllCustomers { + @Test + void givenNonCustomerInDb_whenFindAllCustomer_thenReturnEmptyList() { + assertDoesNotThrow(() -> h2CustomerDAO.delete(existingCustomer.getId())); + List> customers = h2CustomerDAO.findAll(); + assertEquals(0, customers.size()); + } + + @Test + void givenCustomerExistInDb_whenFindAllCustomer_thenReturnCustomers() { + List> customers = h2CustomerDAO.findAll(); + assertEquals(1, customers.size()); + assertEquals(existingCustomer.getName(), customers.get(0).getName()); + assertEquals(existingCustomer.getId(), customers.get(0).getId()); + } + } + + @Nested + class FindCustomerById { + @Test + void givenValidId_whenFindById_thenReturnCustomer() { + var customerInDb = h2CustomerDAO.findById(existingCustomer.getId()); + assertTrue(customerInDb.isPresent()); + assertEquals(existingCustomer.getName(), customerInDb.get().getName()); + assertEquals(existingCustomer.getId(), customerInDb.get().getId()); + } + + @Test + void givenIdCustomerNotExist_whenFindById_thenReturnEmpty() { + var customerNotExist = h2CustomerDAO.findById(100L); + assertTrue(customerNotExist.isEmpty()); + } + + @Test + void givenNull_whenFindById_thenThrowException() { + assertThrows(CustomException.class, () -> h2CustomerDAO.findById(null)); + } + } + + @Nested + class CreateSchema { + @Test + void whenCreateSchema_thenNotThrowException() { + assertDoesNotThrow(() -> h2CustomerDAO.createSchema()); + } + } + + @Nested + class DeleteSchema { + @Test + void whenDeleteSchema_thenNotThrowException() { + assertDoesNotThrow(() -> h2CustomerDAO.deleteSchema()); + } + } + } + + /** Class test with scenario connect with data source failed */ + @Nested + class ConnectionFailed { + private static final String EXCEPTION_CAUSE = "Connection not available"; + + @BeforeEach + void setUp() throws SQLException { + h2CustomerDAO = new H2CustomerDAO(mockedDataSource()); + } + + private DataSource mockedDataSource() throws SQLException { + var mockedDataSource = mock(DataSource.class); + var mockedConnection = mock(Connection.class); + var exception = new SQLException(EXCEPTION_CAUSE); + doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); + doThrow(exception).when(mockedConnection).createStatement(); + doReturn(mockedConnection).when(mockedDataSource).getConnection(); + return mockedDataSource; + } + + @Test + void givenValidCustomer_whenSaveCustomer_thenThrowException() { + var customer = new Customer<>(2L, "Duc"); + CustomException exception = + assertThrows(CustomException.class, () -> h2CustomerDAO.save(customer)); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void givenValidCustomer_whenUpdateCustomer_thenThrowException() { + var customerUpdate = new Customer<>(existingCustomer.getId(), "Duc"); + CustomException exception = + assertThrows(CustomException.class, () -> h2CustomerDAO.update(customerUpdate)); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void givenValidId_whenDeleteCustomer_thenThrowException() { + Long idCustomer = existingCustomer.getId(); + CustomException exception = + assertThrows(CustomException.class, () -> h2CustomerDAO.delete(idCustomer)); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void whenFindAll_thenThrowException() { + CustomException exception = assertThrows(CustomException.class, h2CustomerDAO::findAll); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void whenFindById_thenThrowException() { + Long idCustomer = existingCustomer.getId(); + CustomException exception = + assertThrows(CustomException.class, () -> h2CustomerDAO.findById(idCustomer)); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void whenCreateSchema_thenThrowException() { + CustomException exception = assertThrows(CustomException.class, h2CustomerDAO::createSchema); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + + @Test + void whenDeleteSchema_thenThrowException() { + CustomException exception = assertThrows(CustomException.class, h2CustomerDAO::deleteSchema); + assertEquals(EXCEPTION_CAUSE, exception.getMessage()); + } + } +} diff --git a/dao-factory/src/test/java/com/iluwatar/daofactory/MongoCustomerDAOTest.java b/dao-factory/src/test/java/com/iluwatar/daofactory/MongoCustomerDAOTest.java new file mode 100644 index 000000000000..c56e72c30389 --- /dev/null +++ b/dao-factory/src/test/java/com/iluwatar/daofactory/MongoCustomerDAOTest.java @@ -0,0 +1,163 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.daofactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.model.Filters; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.util.List; +import java.util.Optional; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; +import org.junit.jupiter.api.Test; + +/** Tests {@link MongoCustomerDAO} */ +class MongoCustomerDAOTest { + MongoCollection customerCollection = mock(MongoCollection.class); + MongoCustomerDAO mongoCustomerDAO = new MongoCustomerDAO(customerCollection); + + @Test + void givenValidCustomer_whenSaveCustomer_thenSaveSucceed() { + Customer customer = new Customer<>(new ObjectId(), "John"); + mongoCustomerDAO.save(customer); + verify(customerCollection) + .insertOne( + argThat( + document -> + document.get("_id").equals(customer.getId()) + && document.get("name").equals(customer.getName()))); + } + + @Test + void givenValidCustomer_whenUpdateCustomer_thenUpdateSucceed() { + ObjectId customerId = new ObjectId(); + Customer customerUpdated = new Customer<>(customerId, "John"); + when(customerCollection.updateOne(any(Bson.class), any(Bson.class))) + .thenReturn(UpdateResult.acknowledged(1L, 1L, null)); + mongoCustomerDAO.update(customerUpdated); + verify(customerCollection) + .updateOne( + argThat( + (Bson filter) -> { + Document filterDoc = (Document) filter; + return filterDoc.getObjectId("_id").equals(customerId); + }), + argThat( + (Bson update) -> { + BsonDocument bsonDoc = update.toBsonDocument(); + BsonDocument setDoc = bsonDoc.getDocument("$set"); + return setDoc.getString("name").getValue().equals(customerUpdated.getName()); + })); + } + + @Test + void givenValidObjectId_whenDeleteCustomer_thenDeleteSucceed() { + ObjectId customerId = new ObjectId(); + when(customerCollection.deleteOne(any(Bson.class))).thenReturn(DeleteResult.acknowledged(1)); + mongoCustomerDAO.delete(customerId); + verify(customerCollection) + .deleteOne( + argThat( + (Bson filter) -> { + BsonDocument filterDoc = filter.toBsonDocument(); + return filterDoc.getObjectId("_id").getValue().equals(customerId); + })); + } + + @Test + void givenIdNotExist_whenDeleteCustomer_thenThrowException() { + ObjectId customerId = new ObjectId(); + when(customerCollection.deleteOne(any(Bson.class))).thenReturn(DeleteResult.acknowledged(0)); + assertThrows(CustomException.class, () -> mongoCustomerDAO.delete(customerId)); + verify(customerCollection) + .deleteOne( + argThat( + (Bson filter) -> { + BsonDocument filterDoc = filter.toBsonDocument(); + return filterDoc.getObjectId("_id").getValue().equals(customerId); + })); + } + + @Test + void findAll_thenReturnAllCustomers() { + FindIterable findIterable = mock(FindIterable.class); + MongoCursor cursor = mock(MongoCursor.class); + Document customerDoc1 = new Document("_id", new ObjectId()).append("name", "Duc"); + Document customerDoc2 = new Document("_id", new ObjectId()).append("name", "Thanh"); + when(customerCollection.find()).thenReturn(findIterable); + when(findIterable.iterator()).thenReturn(cursor); + when(cursor.hasNext()).thenReturn(true, true, false); + when(cursor.next()).thenReturn(customerDoc1, customerDoc2); + List> customerList = mongoCustomerDAO.findAll(); + assertEquals(2, customerList.size()); + verify(customerCollection).find(); + } + + @Test + void givenValidId_whenFindById_thenReturnCustomer() { + FindIterable findIterable = mock(FindIterable.class); + ObjectId customerId = new ObjectId(); + String customerName = "Duc"; + Document customerDoc = new Document("_id", customerId).append("name", customerName); + when(customerCollection.find(Filters.eq("_id", customerId))).thenReturn(findIterable); + when(findIterable.first()).thenReturn(customerDoc); + + Optional> customer = mongoCustomerDAO.findById(customerId); + assertTrue(customer.isPresent()); + assertEquals(customerId, customer.get().getId()); + assertEquals(customerName, customer.get().getName()); + } + + @Test + void givenNotExistingId_whenFindById_thenReturnEmpty() { + FindIterable findIterable = mock(FindIterable.class); + ObjectId customerId = new ObjectId(); + when(customerCollection.find(Filters.eq("_id", customerId))).thenReturn(findIterable); + when(findIterable.first()).thenReturn(null); + Optional> customer = mongoCustomerDAO.findById(customerId); + assertTrue(customer.isEmpty()); + verify(customerCollection).find(Filters.eq("_id", customerId)); + } + + @Test + void whenDeleteSchema_thenDeleteCollection() { + mongoCustomerDAO.deleteSchema(); + verify(customerCollection).drop(); + } +} diff --git a/data-access-object/README.md b/data-access-object/README.md index bd020252d253..7e84299e23e1 100644 --- a/data-access-object/README.md +++ b/data-access-object/README.md @@ -199,10 +199,6 @@ The program output: 10:02:09.898 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@f2f2cc1 ``` -## Detailed Explanation of Data Access Object Pattern with Real-World Examples - -![Data Access Object](./etc/dao.png "Data Access Object") - ## When to Use the Data Access Object Pattern in Java Use the Data Access Object in any of the following situations: diff --git a/data-locality/README.md b/data-locality/README.md index e9f556b8ad5c..a59103b3f89b 100644 --- a/data-locality/README.md +++ b/data-locality/README.md @@ -128,10 +128,6 @@ The console output: In this way, the data-locality module demonstrates the Data Locality pattern. By updating all components of the same type together, it increases the likelihood that the data needed for the update is already in the cache, thereby improving performance. -## Detailed Explanation of Data Locality Pattern with Real-World Examples - -![Data Locality](./etc/data-locality.urm.png "Data Locality pattern class diagram") - ## When to Use the Data Locality Pattern in Java This pattern is applicable in scenarios where large datasets are processed and performance is critical. It's particularly useful in: diff --git a/dependency-injection/README.md b/dependency-injection/README.md index c3fc2c15a977..c9a2848bdfde 100644 --- a/dependency-injection/README.md +++ b/dependency-injection/README.md @@ -118,10 +118,6 @@ The program output: 11:54:05.308 [main] INFO com.iluwatar.dependency.injection.Tobacco -- GuiceWizard smoking RivendellTobacco ``` -## Detailed Explanation of Dependency Injection Pattern with Real-World Examples - -![Dependency Injection](./etc/dependency-injection.png "Dependency Injection") - ## When to Use the Dependency Injection Pattern in Java * When aiming to reduce the coupling between classes and increase the modularity of the application. diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml index ad5bf6c3e314..af19d486f9ee 100644 --- a/double-buffer/pom.xml +++ b/double-buffer/pom.xml @@ -45,7 +45,7 @@ org.apache.commons commons-lang3 - 3.17.0 + 3.18.0 org.junit.jupiter diff --git a/dynamic-proxy/pom.xml b/dynamic-proxy/pom.xml index 236723c52682..bf5250998c53 100644 --- a/dynamic-proxy/pom.xml +++ b/dynamic-proxy/pom.xml @@ -46,17 +46,17 @@ com.fasterxml.jackson.core jackson-core - 2.18.2 + 2.21.4 com.fasterxml.jackson.core jackson-databind - 2.18.3 + 2.22.1 org.springframework spring-web - 7.0.0-M3 + 7.0.0-M4 org.junit.jupiter diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 4cfd05d7adac..eefacf7252d4 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -50,12 +50,12 @@ com.fasterxml.jackson.core jackson-core - 2.18.2 + 2.21.4 com.fasterxml.jackson.core jackson-databind - 2.18.3 + 2.18.9 diff --git a/factory-method/README.md b/factory-method/README.md index 4334b052353d..6a0046956211 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -103,13 +103,12 @@ Use the Factory Method Pattern in Java when: ## Real-World Applications of Factory Method Pattern in Java -* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) -* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) -* [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) -* [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) -* [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) -* [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) -* [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) +* [java.util.Calendar]() +* [java.util.ResourceBundle]() +* [java.text.NumberFormat]() +* [java.nio.charset.Charset]() +* [java.net.URLStreamHandlerFactory]() +* [java.util.EnumSet]() * Frameworks that run application components, configured dynamically at runtime. ## Benefits and Trade-offs of Factory Method Pattern diff --git a/fallback/README.md b/fallback/README.md new file mode 100644 index 000000000000..d6612e756444 --- /dev/null +++ b/fallback/README.md @@ -0,0 +1,114 @@ +--- +title: "Fallback Pattern in Java: Graceful Degradation in Microservices" +shortTitle: Fallback +description: "Learn about the Fallback pattern in Java design, which ensures microservice resilience and graceful system degradation when primary dependencies fail." +category: Resilience +language: en +tag: + - Cloud distributed + - Fault tolerance + - Microservices +--- + +## Intent of Fallback Design Pattern + +The Fallback design pattern is a resiliency pattern used in microservices architecture to handle failures gracefully. It ensures that when a service is unavailable, fails, or times out, the system can continue to operate by providing an alternative response or executing a predefined fallback mechanism. This pattern enhances robustness and reliability by preventing cascading failures and improving the overall user experience. + +## Detailed Explanation of Fallback Pattern with Real-World Examples + +Real-world example + +> Consider a movie streaming application like Netflix. The home page loads personalized recommendations for the logged-in user. If the recommendation microservice goes offline or is too slow, the user shouldn't see a broken page. Instead, the system falls back to a cached list of globally popular movies. While the response is degraded (not personalized), the application remains functional, providing a seamless user experience. + +In plain words + +> Fallback ensures that if a primary service call fails, the application falls back to a backup strategy (e.g. cached response, default value, or simplified service) rather than raising an error and failing completely. + +Wikipedia says + +> A fallback is a contingency option to be taken if the preferred choice is unavailable. In software, fallback mechanisms are crucial for fault tolerance, allowing systems to degrade gracefully rather than crash. + +## Programmatic Example of Fallback Pattern in Java + +This Java example demonstrates how the Fallback pattern can manage service failures, integrate with a Circuit Breaker, and apply timeout limits. + +1. **Defining the Remote Service Interface** + + The `RemoteService` interface represents any external dependency call. + +```java +public interface RemoteService { + String execute() throws Exception; +} +``` + +2. **Defining the Primary Service and Fallback Service** + + The `PrimaryService` simulates our main external dependency which may suffer from errors or latency. The `FallbackService` returns a cached or degraded static response. + +```java +// Primary Service simulating latency and errors +var healthyPrimary = new PrimaryService("Healthy data from primary service", 10, false); +var failingPrimary = new PrimaryService("Failing service", 0, true); +var slowPrimary = new PrimaryService("Slow response from primary service", 500, false); + +// Fallback Service providing degraded response +var fallback = new FallbackService("Fallback degraded/cached response"); +``` + +3. **Monitoring Health with a Circuit Breaker** + + A `SimpleCircuitBreaker` tracks the number of failures to trip the circuit to `OPEN`, bypassing the primary service immediately to avoid waiting for timeouts. + +```java +// Trip after 2 failures; retry after 1 second +var circuitBreaker = new SimpleCircuitBreaker(2, 1000); +``` + +4. **Executing Calls with the FallbackExecutor** + + The `FallbackExecutor` uses virtual threads to execute the primary service call. It applies timeouts, handles exceptions, records failures to the circuit breaker, and falls back to the fallback service as needed. + +```java +try (var executor = new FallbackExecutor()) { + // Scenario 1: Healthy primary service call + String response1 = executor.execute(healthyPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response: {}", response1); // Healthy data from primary service + + // Scenario 2: Failing service call triggers fallback + String response2 = executor.execute(failingPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response: {}", response2); // Fallback degraded/cached response +} +``` + +## When to Use the Fallback Pattern in Java + +The Fallback pattern is applicable: + +* In microservices architectures where dependencies are called over the network and are prone to network partitions, timeouts, and outages. +* When returning a default, empty, or cached value is preferable to failing the entire request. +* In user-facing systems where maintaining a working UI (even with degraded features) is critical for user satisfaction. + +## Real-World Applications of Fallback Pattern in Java + +* [Resilience4j Fallback mechanism](https://resilience4j.readme.io/docs/fallback) +* [Netflix Hystrix Fallback](https://github.com/Netflix/Hystrix/wiki/How-To-Use#Fallback) +* Spring Cloud Circuit Breaker integrations + +## Benefits and Trade-offs of Fallback Pattern + +Benefits: + +* **Graceful Degradation**: Improves user experience by returning partial/cached data instead of errors. +* **Cascading Failure Prevention**: Avoids blocking threads waiting on hung services. +* **Fault Tolerance**: Improves system uptime and reliability. + +Trade-Offs: + +* **Stale Data**: Fallback cached responses may present out-of-date information to the user. +* **Increased Complexity**: Requires writing alternative execution flows and testing fallback scenarios. + +## Related Patterns + +- [Circuit Breaker](https://github.com/iluwatar/java-design-patterns/tree/master/circuit-breaker): Restricts calls to failing services. Often wraps the primary service before fallback is triggered. +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry): Retries failed calls before triggering the fallback. diff --git a/fallback/pom.xml b/fallback/pom.xml new file mode 100644 index 000000000000..361aea79079b --- /dev/null +++ b/fallback/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + fallback + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.fallback.App + + + + + + + + + diff --git a/fallback/src/main/java/com/iluwatar/fallback/App.java b/fallback/src/main/java/com/iluwatar/fallback/App.java new file mode 100644 index 000000000000..6e51acc5e5a0 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/App.java @@ -0,0 +1,99 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Fallback design pattern is a resiliency pattern used in microservices architecture to handle + * failures gracefully. When a service is unavailable, fails, or times out, the system responds with + * a pre-configured fallback mechanism (like cached data or a simplified response). + * + *

This App demonstrates: 1. Healthy calls returning standard responses. 2. Failing calls + * (throwing exception) falling back to a fallback handler. 3. Latent calls (timing out) falling + * back. 4. Circuit Breaker tripping and immediately fast-failing to the fallback handler. 5. + * Recovery after a retry duration, returning the system to a healthy CLOSED state. + */ +public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Main entry point for the application. + * + * @param args Command line arguments (not used) + */ + public static void main(String[] args) { + try (var executor = new FallbackExecutor()) { + var healthyPrimary = new PrimaryService("Healthy data from primary service", 10, false); + var failingPrimary = new PrimaryService("Failing service", 0, true); + var slowPrimary = new PrimaryService("Slow response from primary service", 500, false); + var fallback = new FallbackService("Fallback degraded/cached response"); + + // Failure threshold is 2 failures, retry time period is 1 second (1000ms) + var circuitBreaker = new SimpleCircuitBreaker(2, 1000); + + // Scenario 1: Healthy primary service call + LOGGER.info("Scenario 1: Executing request to healthy primary service..."); + String response1 = executor.execute(healthyPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response received: {}", response1); + LOGGER.info("Circuit Breaker State: {}\n", circuitBreaker.getState()); + + // Scenario 2: Failing primary service call (fails and increments failure count to 1) + LOGGER.info("Scenario 2: Executing request to failing primary service (throws exception)..."); + String response2 = executor.execute(failingPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response received: {}", response2); + LOGGER.info("Circuit Breaker State: {}\n", circuitBreaker.getState()); + + // Scenario 3: Slow primary service call (times out and increments failure count to 2, + // tripping breaker) + LOGGER.info("Scenario 3: Executing request to slow primary service (triggers timeout)..."); + String response3 = executor.execute(slowPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response received: {}", response3); + LOGGER.info("Circuit Breaker State: {}\n", circuitBreaker.getState()); + + // Scenario 4: Fast failing when circuit is OPEN + LOGGER.info("Scenario 4: Executing request while Circuit Breaker is OPEN..."); + String response4 = executor.execute(healthyPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response received: {}", response4); + LOGGER.info("Circuit Breaker State: {}\n", circuitBreaker.getState()); + + // Scenario 5: Recovery from OPEN state + LOGGER.info("Scenario 5: Waiting for retry period to elapse..."); + try { + Thread.sleep(1100); // Wait longer than retryTimePeriodMs (1000ms) + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + LOGGER.info( + "Circuit Breaker State (should be HALF_OPEN on next check): {}", + circuitBreaker.getState()); + LOGGER.info("Executing request to healthy primary service to reset breaker..."); + String response5 = executor.execute(healthyPrimary, fallback, circuitBreaker, 100); + LOGGER.info("Response received: {}", response5); + LOGGER.info("Circuit Breaker State (should be CLOSED): {}\n", circuitBreaker.getState()); + } + } +} diff --git a/fallback/src/main/java/com/iluwatar/fallback/FallbackExecutor.java b/fallback/src/main/java/com/iluwatar/fallback/FallbackExecutor.java new file mode 100644 index 000000000000..01bf3a204d01 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/FallbackExecutor.java @@ -0,0 +1,110 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Orchestrates primary service execution with timeouts, circuit breaker health checks, and fallback + * execution logic. Implements AutoCloseable to ensure thread pools are closed cleanly. + */ +public class FallbackExecutor implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(FallbackExecutor.class); + private final ExecutorService executorService; + + /** Constructor for FallbackExecutor. Initializes a virtual thread per task executor. */ + public FallbackExecutor() { + this.executorService = Executors.newVirtualThreadPerTaskExecutor(); + } + + /** + * Executes the primary service call. If it fails, times out, or the circuit breaker is open, it + * falls back to the fallback service. + * + * @param primary the primary service call to execute + * @param fallback the fallback service to call when primary fails or is bypassed + * @param circuitBreaker the circuit breaker monitoring service health + * @param timeoutMs timeout limit for the primary service in milliseconds + * @return response string + */ + public String execute( + RemoteService primary, + RemoteService fallback, + SimpleCircuitBreaker circuitBreaker, + long timeoutMs) { + + // 1. Check Circuit Breaker + if (circuitBreaker.getState() == SimpleCircuitBreaker.State.OPEN) { + LOGGER.warn("Circuit is OPEN. Fast-failing and calling fallback service."); + try { + return fallback.execute(); + } catch (Exception ex) { + LOGGER.error("Fallback service execution failed: {}", ex.getMessage()); + return "Fallback Error"; + } + } + + // 2. Attempt service call with timeout + Callable task = primary::execute; + Future future = executorService.submit(task); + + try { + String result = future.get(timeoutMs, TimeUnit.MILLISECONDS); + circuitBreaker.recordSuccess(); + return result; + } catch (TimeoutException e) { + LOGGER.error("Service call timed out. Triggering fallback."); + future.cancel(true); // Interrupt / cancel the task + circuitBreaker.recordFailure(); + try { + return fallback.execute(); + } catch (Exception ex) { + LOGGER.error("Fallback service execution failed: {}", ex.getMessage()); + return "Fallback Error"; + } + } catch (Exception e) { + LOGGER.error("Service call failed with exception: {}. Triggering fallback.", e.getMessage()); + circuitBreaker.recordFailure(); + try { + return fallback.execute(); + } catch (Exception ex) { + LOGGER.error("Fallback service execution failed: {}", ex.getMessage()); + return "Fallback Error"; + } + } + } + + @Override + public void close() { + executorService.shutdown(); + } +} diff --git a/fallback/src/main/java/com/iluwatar/fallback/FallbackService.java b/fallback/src/main/java/com/iluwatar/fallback/FallbackService.java new file mode 100644 index 000000000000..c84925f20606 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/FallbackService.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +/** + * A concrete implementation of the remote service representing the fallback handler. It is invoked + * when the primary service fails, returns a cached response or degrades gracefully. + */ +public class FallbackService implements RemoteService { + private final String fallbackResponse; + + /** + * Constructor for FallbackService. + * + * @param fallbackResponse the fallback response to return + */ + public FallbackService(String fallbackResponse) { + this.fallbackResponse = fallbackResponse; + } + + @Override + public String execute() { + return fallbackResponse; + } +} diff --git a/fallback/src/main/java/com/iluwatar/fallback/PrimaryService.java b/fallback/src/main/java/com/iluwatar/fallback/PrimaryService.java new file mode 100644 index 000000000000..55cdb2644e93 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/PrimaryService.java @@ -0,0 +1,59 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +/** + * A concrete implementation of the remote service representing the primary service. It can be + * configured to simulate latency and errors to test resilience features. + */ +public class PrimaryService implements RemoteService { + private final long latencyMs; + private final String response; + private final boolean shouldThrowException; + + /** + * Constructor for PrimaryService. + * + * @param response the successful response to return + * @param latencyMs simulated latency in milliseconds + * @param shouldThrowException if true, the service will throw an exception + */ + public PrimaryService(String response, long latencyMs, boolean shouldThrowException) { + this.latencyMs = latencyMs; + this.response = response; + this.shouldThrowException = shouldThrowException; + } + + @Override + public String execute() throws Exception { + if (shouldThrowException) { + throw new RuntimeException("Primary service failed!"); + } + if (latencyMs > 0) { + Thread.sleep(latencyMs); + } + return response; + } +} diff --git a/fallback/src/main/java/com/iluwatar/fallback/RemoteService.java b/fallback/src/main/java/com/iluwatar/fallback/RemoteService.java new file mode 100644 index 000000000000..7e84a7fdbe21 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/RemoteService.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +/** Representation of a service (e.g. a microservice client) that might fail. */ +public interface RemoteService { + /** + * Executes the service logic. + * + * @return the service response + * @throws Exception if service call fails or is interrupted + */ + String execute() throws Exception; +} diff --git a/fallback/src/main/java/com/iluwatar/fallback/SimpleCircuitBreaker.java b/fallback/src/main/java/com/iluwatar/fallback/SimpleCircuitBreaker.java new file mode 100644 index 000000000000..185167820364 --- /dev/null +++ b/fallback/src/main/java/com/iluwatar/fallback/SimpleCircuitBreaker.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** A simplified circuit breaker implementation for tracking remote service health. */ +public class SimpleCircuitBreaker { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCircuitBreaker.class); + + private final int failureThreshold; + private final long retryTimePeriodMs; + private int failureCount = 0; + private long lastFailureTime = 0; + private State state = State.CLOSED; + + /** The state of the circuit breaker. */ + public enum State { + CLOSED, + OPEN, + HALF_OPEN + } + + /** + * Constructor for SimpleCircuitBreaker. + * + * @param failureThreshold consecutive failure count threshold to trip the breaker + * @param retryTimePeriodMs time duration to wait in OPEN state before trying again (HALF_OPEN) + */ + public SimpleCircuitBreaker(int failureThreshold, long retryTimePeriodMs) { + this.failureThreshold = failureThreshold; + this.retryTimePeriodMs = retryTimePeriodMs; + } + + /** + * Get the current state of the circuit breaker after evaluating transitions. + * + * @return current state + */ + public synchronized State getState() { + evaluateState(); + return state; + } + + private void evaluateState() { + if (state == State.OPEN) { + if (System.currentTimeMillis() - lastFailureTime > retryTimePeriodMs) { + state = State.HALF_OPEN; + LOGGER.info("Circuit Breaker transitioned to HALF_OPEN"); + } + } + } + + /** Records a successful operation, resetting the failure counter and closing the circuit. */ + public synchronized void recordSuccess() { + failureCount = 0; + state = State.CLOSED; + LOGGER.info("Circuit Breaker transitioned to CLOSED (success recorded)"); + } + + /** Records a failure, potentially tripping the circuit to OPEN if threshold is met. */ + public synchronized void recordFailure() { + failureCount++; + lastFailureTime = System.currentTimeMillis(); + if (state == State.CLOSED && failureCount >= failureThreshold) { + state = State.OPEN; + LOGGER.warn("Circuit Breaker transitioned to OPEN (failure threshold reached)"); + } else if (state == State.HALF_OPEN) { + state = State.OPEN; + LOGGER.warn("Circuit Breaker transitioned to OPEN (failed during HALF_OPEN)"); + } + } +} diff --git a/fallback/src/test/java/com/iluwatar/fallback/AppTest.java b/fallback/src/test/java/com/iluwatar/fallback/AppTest.java new file mode 100644 index 000000000000..86ffb6f363be --- /dev/null +++ b/fallback/src/test/java/com/iluwatar/fallback/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Test verifying that App main method runs without throwing exceptions. */ +class AppTest { + @Test + void testMain() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/fallback/src/test/java/com/iluwatar/fallback/FallbackPatternTest.java b/fallback/src/test/java/com/iluwatar/fallback/FallbackPatternTest.java new file mode 100644 index 000000000000..f338c1c8c5c1 --- /dev/null +++ b/fallback/src/test/java/com/iluwatar/fallback/FallbackPatternTest.java @@ -0,0 +1,122 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fallback; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Unit and integration tests for the Fallback design pattern. */ +class FallbackPatternTest { + + @Test + void testHealthyServiceCall() { + try (var executor = new FallbackExecutor()) { + var primary = new PrimaryService("Primary Response", 0, false); + var fallback = new FallbackService("Fallback Response"); + var circuitBreaker = new SimpleCircuitBreaker(2, 1000); + + String response = executor.execute(primary, fallback, circuitBreaker, 100); + assertEquals("Primary Response", response); + assertEquals(SimpleCircuitBreaker.State.CLOSED, circuitBreaker.getState()); + } + } + + @Test + void testFailingServiceCall() { + try (var executor = new FallbackExecutor()) { + var primary = new PrimaryService("Primary Response", 0, true); + var fallback = new FallbackService("Fallback Response"); + var circuitBreaker = new SimpleCircuitBreaker(2, 1000); + + // First failure: should call fallback, state remains CLOSED since threshold is 2 + String response1 = executor.execute(primary, fallback, circuitBreaker, 100); + assertEquals("Fallback Response", response1); + assertEquals(SimpleCircuitBreaker.State.CLOSED, circuitBreaker.getState()); + + // Second failure: should call fallback, state becomes OPEN + String response2 = executor.execute(primary, fallback, circuitBreaker, 100); + assertEquals("Fallback Response", response2); + assertEquals(SimpleCircuitBreaker.State.OPEN, circuitBreaker.getState()); + } + } + + @Test + void testTimeoutServiceCall() { + try (var executor = new FallbackExecutor()) { + // Primary takes 300ms, timeout limit is 50ms + var primary = new PrimaryService("Primary Response", 300, false); + var fallback = new FallbackService("Fallback Response"); + var circuitBreaker = new SimpleCircuitBreaker(1, 1000); + + String response = executor.execute(primary, fallback, circuitBreaker, 50); + assertEquals("Fallback Response", response); + assertEquals(SimpleCircuitBreaker.State.OPEN, circuitBreaker.getState()); + } + } + + @Test + void testCircuitBreakerOpenFastFail() { + try (var executor = new FallbackExecutor()) { + // Configure primary service to throw exception if called + var primary = new PrimaryService("Primary Response", 0, true); + var fallback = new FallbackService("Fallback Response"); + var circuitBreaker = new SimpleCircuitBreaker(1, 1000); + + // Force open by registering a failure + circuitBreaker.recordFailure(); + assertEquals(SimpleCircuitBreaker.State.OPEN, circuitBreaker.getState()); + + // Now call execute. It should short-circuit and not call the failing primary (fast-fail). + String response = executor.execute(primary, fallback, circuitBreaker, 100); + assertEquals("Fallback Response", response); + } + } + + @Test + void testCircuitBreakerRecovery() throws InterruptedException { + try (var executor = new FallbackExecutor()) { + var primary = new PrimaryService("Primary Response", 0, false); + var fallback = new FallbackService("Fallback Response"); + // Failure threshold = 1, retry period = 100ms + var circuitBreaker = new SimpleCircuitBreaker(1, 100); + + // Trip the breaker + circuitBreaker.recordFailure(); + assertEquals(SimpleCircuitBreaker.State.OPEN, circuitBreaker.getState()); + + // Wait 150ms to exceed retry period + Thread.sleep(150); + + // State should evaluate to HALF_OPEN + assertEquals(SimpleCircuitBreaker.State.HALF_OPEN, circuitBreaker.getState()); + + // Execute. Healthy primary service succeeds, state transitions to CLOSED + String response = executor.execute(primary, fallback, circuitBreaker, 100); + assertEquals("Primary Response", response); + assertEquals(SimpleCircuitBreaker.State.CLOSED, circuitBreaker.getState()); + } + } +} diff --git a/fork-join/README.md b/fork-join/README.md new file mode 100644 index 000000000000..b94af1de02ac --- /dev/null +++ b/fork-join/README.md @@ -0,0 +1,161 @@ +--- +title: "Fork/Join Pattern in Java: Parallel Divide-and-Conquer Processing" +shortTitle: Fork/Join +description: "Learn the Fork/Join design pattern in Java with real-world examples, class diagrams, and code samples. Understand how to split large tasks into parallel subtasks for improved performance." +category: Concurrency +language: en +tag: + - Performance + - Scalability + - Concurrency +--- + +## Also known as + +* Divide and Conquer Parallelism +* Work-Stealing Parallelism + +## Intent of Fork/Join Design Pattern + +The Fork/Join pattern recursively splits a large task into independent subtasks (fork), +processes them in parallel across multiple threads, and combines their results (join) to +produce a final outcome. It maximizes CPU utilization for computationally intensive problems. + +## Detailed Explanation of Fork/Join Pattern with Real-World Examples + +Real-world example + +> Imagine a large warehouse that needs to count all its inventory items across 100 aisles. +> Instead of one person counting every aisle sequentially, the manager divides the warehouse +> into sections and assigns a team of workers to count each section simultaneously. Once +> every section is counted, the manager collects all partial counts and sums them into the +> total inventory. This is the Fork/Join pattern: split the work, do it in parallel, merge +> the results. + +In plain words + +> Fork/Join splits a big problem into smaller pieces, solves each piece in parallel on +> separate threads, then combines all results back together. + +## Programmatic Example of Fork/Join Pattern in Java + +We demonstrate the pattern by computing the sum of a large array in parallel using Java's +built-in `ForkJoinPool` and `RecursiveTask`. + +The `SumTask` is a recursive task that splits the array when it's too large: + +```java +public class SumTask extends RecursiveTask { + + private static final int THRESHOLD = 1000; + private final long[] numbers; + private final int start; + private final int end; + + @Override + protected Long compute() { + int length = end - start; + + if (length <= THRESHOLD) { + // Base case: sum directly + long sum = 0; + for (int i = start; i < end; i++) { + sum += numbers[i]; + } + return sum; + } + + // Fork: split into two halves + int mid = start + length / 2; + SumTask leftTask = new SumTask(numbers, start, mid); + SumTask rightTask = new SumTask(numbers, mid, end); + + leftTask.fork(); // run left half asynchronously + long rightResult = rightTask.compute(); // compute right half here + long leftResult = leftTask.join(); // wait for left half + + // Join: combine results + return leftResult + rightResult; + } +} +``` + +The `ForkJoinSumCalculator` provides a clean API: + +```java +public class ForkJoinSumCalculator { + + private final ForkJoinPool pool; + + public ForkJoinSumCalculator() { + this.pool = ForkJoinPool.commonPool(); + } + + public long calculateSum(long[] numbers) { + SumTask task = new SumTask(numbers, 0, numbers.length); + return pool.invoke(task); + } +} +``` + +Running the example in `App`: + +```java +long[] numbers = LongStream.rangeClosed(1, 10_000_000).toArray(); +ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); +long result = calculator.calculateSum(numbers); +System.out.println("Fork/Join sum: " + result); +``` + +Program output: + +``` +Fork/Join sum: 50000005000000 +Expected sum: 50000005000000 +Correct: true +Time taken: 45 ms +Available processors: 8 +``` + +## When to Use the Fork/Join Pattern in Java + +* When you have a large, CPU-intensive task that can be divided into independent subtasks. +* When the subtasks are roughly the same size and don't depend on each other. +* When you want to utilize multiple CPU cores without manually managing threads. +* When the problem naturally fits a divide-and-conquer strategy (e.g., sorting, searching, + numerical computation). + +## When NOT to Use Fork/Join + +* For I/O-bound tasks (network calls, file reads) — use virtual threads or async I/O instead. +* When subtasks are too small — the overhead of forking exceeds the benefit. +* When tasks have dependencies on each other and cannot run independently. + +## Benefits and Trade-offs of Fork/Join Pattern + +Benefits: + +* Maximizes CPU utilization through work-stealing algorithm. +* Scales automatically with the number of available processors. +* Built into Java's standard library (`java.util.concurrent`) — no external dependencies. +* Clean recursive decomposition makes the code readable and maintainable. + +Trade-offs: + +* Overhead from task creation and thread management for very small problems. +* Requires tasks to be independent — shared mutable state introduces bugs. +* Choosing an appropriate threshold requires tuning for optimal performance. +* Debugging parallel code is inherently harder than sequential code. + +## Related Java Design Patterns + +* [Divide and Conquer](https://java-design-patterns.com/patterns/divide-and-conquer/): + Fork/Join is the parallel execution variant of the classic divide-and-conquer strategy. +* [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Fork/Join uses a + specialized pool with work-stealing semantics. + +## References + +* [Java Documentation for ForkJoinPool](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ForkJoinPool.html) +* [Java Concurrency in Practice — Brian Goetz](https://amzn.to/4aRMruW) +* [Java Documentation for RecursiveTask](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/RecursiveTask.html) diff --git a/fork-join/pom.xml b/fork-join/pom.xml new file mode 100644 index 000000000000..23958727728a --- /dev/null +++ b/fork-join/pom.xml @@ -0,0 +1,50 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + fork-join + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.forkjoin.App + + + + + + + + + + diff --git a/fork-join/src/main/java/com/iluwatar/forkjoin/App.java b/fork-join/src/main/java/com/iluwatar/forkjoin/App.java new file mode 100644 index 000000000000..a53bdcec6de7 --- /dev/null +++ b/fork-join/src/main/java/com/iluwatar/forkjoin/App.java @@ -0,0 +1,43 @@ +package com.iluwatar.forkjoin; + +import java.util.stream.LongStream; + +/** + * The Fork/Join pattern is a concurrency design pattern that splits a large task into smaller + * subtasks (fork), processes them in parallel, and then combines the results (join). + * + *

In Java, this pattern is implemented using {@link java.util.concurrent.ForkJoinPool} and + * {@link java.util.concurrent.RecursiveTask}. Worker threads in the pool use a work-stealing + * algorithm — idle threads take tasks from busy threads — maximizing CPU utilization. + * + *

In this example, we demonstrate the pattern by computing the sum of a large array in parallel. + * The array is recursively split in half until each piece is small enough to sum directly, then + * results are combined back up. + */ +public final class App { + + private App() {} + + /** + * @param args command line arguments, not used + */ + public static void main(String[] args) { + // Create an array of 10 million numbers: [1, 2, 3, ..., 10_000_000] + long[] numbers = LongStream.rangeClosed(1, 10_000_000).toArray(); + + // Calculate sum using Fork/Join + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); + long startTime = System.currentTimeMillis(); + long result = calculator.calculateSum(numbers); + long endTime = System.currentTimeMillis(); + + // The expected sum of 1 to N is N*(N+1)/2 + long expected = 10_000_000L * 10_000_001L / 2; + + System.out.println("Fork/Join sum: " + result); + System.out.println("Expected sum: " + expected); + System.out.println("Correct: " + (result == expected)); + System.out.println("Time taken: " + (endTime - startTime) + " ms"); + System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors()); + } +} diff --git a/fork-join/src/main/java/com/iluwatar/forkjoin/ForkJoinSumCalculator.java b/fork-join/src/main/java/com/iluwatar/forkjoin/ForkJoinSumCalculator.java new file mode 100644 index 000000000000..0e9dff32cda8 --- /dev/null +++ b/fork-join/src/main/java/com/iluwatar/forkjoin/ForkJoinSumCalculator.java @@ -0,0 +1,44 @@ +package com.iluwatar.forkjoin; + +import java.util.concurrent.ForkJoinPool; + +/** + * ForkJoinSumCalculator provides a convenient API to sum an array of numbers using the Fork/Join + * framework. It creates a {@link ForkJoinPool}, submits a {@link SumTask}, and returns the computed + * sum. + * + *

The pool manages a set of worker threads that process subtasks in parallel. Idle threads can + * "steal" work from busy threads, maximizing CPU utilization. + */ +public class ForkJoinSumCalculator { + + private final ForkJoinPool pool; + + /** Creates a calculator using the common ForkJoinPool (uses all available CPU cores). */ + public ForkJoinSumCalculator() { + this.pool = ForkJoinPool.commonPool(); + } + + /** + * Creates a calculator with a specific number of threads. + * + * @param parallelism the number of worker threads to use + */ + public ForkJoinSumCalculator(int parallelism) { + this.pool = new ForkJoinPool(parallelism); + } + + /** + * Calculates the sum of all elements in the array using Fork/Join parallelism. + * + * @param numbers the array of numbers to sum + * @return the total sum of all elements + */ + public long calculateSum(long[] numbers) { + if (numbers == null || numbers.length == 0) { + return 0; + } + SumTask task = new SumTask(numbers, 0, numbers.length); + return pool.invoke(task); + } +} diff --git a/fork-join/src/main/java/com/iluwatar/forkjoin/SumTask.java b/fork-join/src/main/java/com/iluwatar/forkjoin/SumTask.java new file mode 100644 index 000000000000..acbd5f0516b7 --- /dev/null +++ b/fork-join/src/main/java/com/iluwatar/forkjoin/SumTask.java @@ -0,0 +1,93 @@ +package com.iluwatar.forkjoin; + +import java.util.concurrent.RecursiveTask; + +/** + * SumTask demonstrates the Fork/Join pattern by recursively splitting an array summation problem + * into smaller subtasks until each subtask is small enough to compute directly. + * + *

How it works: If the portion of the array is smaller than THRESHOLD, sum it in a simple loop. + * Otherwise, split the array in half, fork one half to run in parallel, compute the other half in + * the current thread, and then join the results. This approach utilizes multiple CPU cores to + * perform the summation significantly faster than a single-threaded loop for large arrays. + */ +public class SumTask extends RecursiveTask { + + /** + * If the number of elements to process is at or below this threshold, the task computes the sum + * directly instead of splitting further. + */ + private static final int THRESHOLD = 1000; + + private final long[] numbers; + private final int start; + private final int end; + + /** + * Creates a task to sum elements of the given array from index {@code start} (inclusive) to index + * {@code end} (exclusive). + * + * @param numbers the array of numbers to sum + * @param start the starting index (inclusive) + * @param end the ending index (exclusive) + */ + public SumTask(long[] numbers, int start, int end) { + if (start > end) { + throw new IllegalArgumentException( + "start (" + start + ") must not be greater than end (" + end + ")"); + } + this.numbers = numbers; + this.start = start; + this.end = end; + } + + /** + * The main computation method. This is where the fork/join magic happens. + * + * @return the sum of elements from start to end + */ + @Override + protected Long compute() { + int length = end - start; + + // BASE CASE: if the chunk is small enough, just sum directly + if (length <= THRESHOLD) { + return computeDirectly(); + } + + // FORK: split the task into two halves + int mid = start + length / 2; + + // Create subtask for the left half + SumTask leftTask = new SumTask(numbers, start, mid); + + // Create subtask for the right half + SumTask rightTask = new SumTask(numbers, mid, end); + + // Fork the left task — it will run in a separate thread + leftTask.fork(); + + // Compute the right task in the current thread (no need to fork both) + long rightResult = rightTask.compute(); + + // JOIN: wait for the left task to finish and get its result + long leftResult = leftTask.join(); + + // Combine the results from both halves + return leftResult + rightResult; + } + + /** + * Computes the sum directly using a simple loop. This is used when the chunk size is at or below + * the threshold — no further splitting needed. + * + * @return the sum of elements in the range [start, end) + */ + private long computeDirectly() { + long sum = 0; + for (int i = start; i < end; i++) { + sum += numbers[i]; + } + return sum; + } +} diff --git a/fork-join/src/test/java/com/iluwatar/forkjoin/AppTest.java b/fork-join/src/test/java/com/iluwatar/forkjoin/AppTest.java new file mode 100644 index 000000000000..c66f8610cc55 --- /dev/null +++ b/fork-join/src/test/java/com/iluwatar/forkjoin/AppTest.java @@ -0,0 +1,11 @@ +package com.iluwatar.forkjoin; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldExecuteWithoutException() { + App.main(new String[] {}); + } +} diff --git a/fork-join/src/test/java/com/iluwatar/forkjoin/ForkJoinSumCalculatorTest.java b/fork-join/src/test/java/com/iluwatar/forkjoin/ForkJoinSumCalculatorTest.java new file mode 100644 index 000000000000..6af56dfc38e1 --- /dev/null +++ b/fork-join/src/test/java/com/iluwatar/forkjoin/ForkJoinSumCalculatorTest.java @@ -0,0 +1,56 @@ +package com.iluwatar.forkjoin; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.stream.LongStream; +import org.junit.jupiter.api.Test; + +class ForkJoinSumCalculatorTest { + + @Test + void shouldReturnZeroForNullArray() { + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); + + assertEquals(0L, calculator.calculateSum(null)); + } + + @Test + void shouldReturnZeroForEmptyArray() { + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); + + assertEquals(0L, calculator.calculateSum(new long[0])); + } + + @Test + void shouldCalculateSumOfSmallArray() { + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); + long[] numbers = {10, 20, 30, 40, 50}; + + long result = calculator.calculateSum(numbers); + + assertEquals(150L, result); + } + + @Test + void shouldCalculateSumOfLargeArray() { + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(); + long[] numbers = LongStream.rangeClosed(1, 100_000).toArray(); + + long result = calculator.calculateSum(numbers); + + long expected = 100_000L * 100_001L / 2; + assertEquals(expected, result); + } + + @Test + void shouldWorkWithCustomParallelism() { + // Use only 2 threads + ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(2); + long[] numbers = LongStream.rangeClosed(1, 50_000).toArray(); + + long result = calculator.calculateSum(numbers); + + long expected = 50_000L * 50_001L / 2; + assertEquals(expected, result); + } +} diff --git a/fork-join/src/test/java/com/iluwatar/forkjoin/SumTaskTest.java b/fork-join/src/test/java/com/iluwatar/forkjoin/SumTaskTest.java new file mode 100644 index 000000000000..03df6a6bc268 --- /dev/null +++ b/fork-join/src/test/java/com/iluwatar/forkjoin/SumTaskTest.java @@ -0,0 +1,85 @@ +package com.iluwatar.forkjoin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.concurrent.ForkJoinPool; +import java.util.stream.LongStream; +import org.junit.jupiter.api.Test; + +class SumTaskTest { + + @Test + void shouldSumSmallArrayDirectly() { + // Array smaller than threshold — should compute without forking + long[] numbers = {1, 2, 3, 4, 5}; + SumTask task = new SumTask(numbers, 0, numbers.length); + + long result = ForkJoinPool.commonPool().invoke(task); + + assertEquals(15L, result); + } + + @Test + void shouldSumLargeArrayUsingForkJoin() { + // Array larger than threshold — will fork into subtasks + long[] numbers = LongStream.rangeClosed(1, 10_000).toArray(); + SumTask task = new SumTask(numbers, 0, numbers.length); + + long result = ForkJoinPool.commonPool().invoke(task); + + // Sum of 1 to N = N*(N+1)/2 + long expected = 10_000L * 10_001L / 2; + assertEquals(expected, result); + } + + @Test + void shouldSumPartialRange() { + // Sum only a portion of the array (indices 2 to 5) + long[] numbers = {10, 20, 30, 40, 50, 60}; + SumTask task = new SumTask(numbers, 2, 5); + + long result = ForkJoinPool.commonPool().invoke(task); + + // 30 + 40 + 50 = 120 + assertEquals(120L, result); + } + + @Test + void shouldReturnZeroForEmptyRange() { + long[] numbers = {1, 2, 3}; + SumTask task = new SumTask(numbers, 1, 1); // start == end, empty range + + long result = ForkJoinPool.commonPool().invoke(task); + + assertEquals(0L, result); + } + + @Test + void shouldHandleSingleElement() { + long[] numbers = {42}; + SumTask task = new SumTask(numbers, 0, 1); + + long result = ForkJoinPool.commonPool().invoke(task); + + assertEquals(42L, result); + } + + @Test + void shouldProduceCorrectResultForMillionElements() { + long[] numbers = LongStream.rangeClosed(1, 1_000_000).toArray(); + SumTask task = new SumTask(numbers, 0, numbers.length); + + long result = ForkJoinPool.commonPool().invoke(task); + + long expected = 1_000_000L * 1_000_001L / 2; + assertEquals(expected, result); + } + + @Test + void shouldThrowExceptionWhenStartGreaterThanEnd() { + long[] numbers = {1, 2, 3, 4, 5}; + + assertThrows(IllegalArgumentException.class, () -> new SumTask(numbers, 4, 2)); + } +} diff --git a/health-check/pom.xml b/health-check/pom.xml index 203503ad03b6..8019d9a15f2c 100644 --- a/health-check/pom.xml +++ b/health-check/pom.xml @@ -94,7 +94,7 @@ org.assertj assertj-core - 3.27.3 + 3.27.7 test diff --git a/health-check/src/main/java/com/iluwatar/health/check/App.java b/health-check/src/main/java/com/iluwatar/health/check/App.java index 8f8faed9f821..6c0a446c97ee 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/App.java +++ b/health-check/src/main/java/com/iluwatar/health/check/App.java @@ -43,6 +43,11 @@ public class App { /** Program entry point. */ public static void main(String[] args) { - SpringApplication.run(App.class, args); + var context = SpringApplication.run(App.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } } diff --git a/health-check/src/test/java/AppTest.java b/health-check/src/test/java/AppTest.java index c9cd78366461..0c1be55a16ef 100644 --- a/health-check/src/test/java/AppTest.java +++ b/health-check/src/test/java/AppTest.java @@ -33,6 +33,6 @@ class AppTest { /** Entry point */ @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[] {})); + assertDoesNotThrow(() -> App.main(new String[] {"test"})); } } diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml index 1ac50cecfa04..4d0a9fad318f 100644 --- a/hexagonal-architecture/pom.xml +++ b/hexagonal-architecture/pom.xml @@ -54,7 +54,7 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo - 4.20.0 + 4.33.0 test diff --git a/immutable/README.md b/immutable/README.md new file mode 100644 index 000000000000..07834d2b380d --- /dev/null +++ b/immutable/README.md @@ -0,0 +1,129 @@ +--- +title: "Immutable Pattern in Java: Building Thread-Safe Objects" +shortTitle: Immutable +description: "Learn the Immutable pattern in Java with real-world examples, class diagrams, and tutorials. Understand how to create objects that cannot be modified after construction." +category: Idiom +language: en +tag: + - Immutability + - Thread safety + - Concurrency + - Object composition +--- + +## Also known as + +Value Object (when applied strictly to small domain values) + +## Intent of Immutable Design Pattern + +Ensure that an object's state cannot be changed after it is constructed, making it inherently thread-safe and easier to reason about. + +## Detailed Explanation of Immutable Pattern with Real-World Examples + +Real-world example + +> A birth certificate is a perfect real-world analogy for the Immutable pattern. Once issued, a birth certificate records a person's name, date of birth, and place of birth permanently. You cannot alter the certificate itself; if a legal correction is needed, a new certificate is issued. The original document remains unchanged, guaranteeing that every copy handed to a bank, school, or government office reflects exactly the same facts. + +In plain words + +> An immutable object is one whose state is fixed at construction time and can never change. Instead of modifying an existing object, you create a new one with the desired state. + +Wikipedia says + +> In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created. + +## Programmatic Example of Immutable Pattern in Java + +The core of the pattern is `ImmutableUser`. All fields are `final`, the mutable `roles` list is defensively copied via `List.copyOf`, and "mutation" is expressed by returning a new instance. + +```java +public final class ImmutableUser { + + private final String name; + private final int age; + private final List roles; + + public ImmutableUser(String name, int age, List roles) { + this.name = name; + this.age = age; + this.roles = List.copyOf(roles); + } + + public String getName() { return name; } + public int getAge() { return age; } + public List getRoles() { return roles; } + + public ImmutableUser withAge(int newAge) { + return new ImmutableUser(this.name, newAge, this.roles); + } +} +``` + +`App` demonstrates the pattern in action: + +```java +var alice = new ImmutableUser("Alice", 30, List.of("admin", "user")); +LOGGER.info("Original user: {}", alice); + +var olderAlice = alice.withAge(31); +LOGGER.info("Updated user (new object): {}", olderAlice); +LOGGER.info("Original is unchanged: {}", alice); + +var mutableRoles = new ArrayList<>(List.of("viewer")); +var bob = new ImmutableUser("Bob", 25, mutableRoles); +mutableRoles.add("editor"); +LOGGER.info("Bob's roles (unchanged despite external list mutation): {}", bob.getRoles()); +``` + +Running the example produces output similar to: + +``` +INFO com.iluwatar.immutable.App - Original user: ImmutableUser{name='Alice', age=30, roles=[admin, user]} +INFO com.iluwatar.immutable.App - Updated user (new object): ImmutableUser{name='Alice', age=31, roles=[admin, user]} +INFO com.iluwatar.immutable.App - Original is unchanged: ImmutableUser{name='Alice', age=30, roles=[admin, user]} +INFO com.iluwatar.immutable.App - Bob's roles (unchanged despite external list mutation): [viewer] +``` + +## When to Use the Immutable Pattern in Java + +* When objects are shared across threads and synchronization overhead is undesirable. +* When you need objects to be used safely as map keys or in sets (consistent `hashCode`). +* When you want to model value types such as money, dates, or coordinates. +* When defensive programming is critical and you must prevent accidental state corruption. + +## Real-World Applications of Immutable Pattern in Java + +* `java.lang.String` — the quintessential immutable class in the JDK. +* `java.time.LocalDate`, `LocalDateTime` — immutable date/time representations. +* `java.math.BigDecimal`, `BigInteger` — immutable numeric types. +* Record classes introduced in Java 16 — compiler-generated immutable data carriers. + +## Benefits and Trade-offs of Immutable Pattern + +Benefits: + +* **Thread safety**: No synchronization needed; immutable objects can be shared freely across threads. +* **Simplicity**: Absence of state changes eliminates a whole category of bugs. +* **Safe sharing**: Can be freely passed to untrusted code without defensive copying at call sites. +* **Cache-friendly**: Immutable objects can be cached, interned, or pre-computed without risk. + +Trade-offs: + +* **Object creation overhead**: Every logical "update" allocates a new object, which may pressure the garbage collector in hot paths. +* **Verbose construction**: Complex objects often require a Builder to avoid unwieldy constructors. +* **Not always applicable**: Objects that model inherently stateful entities (e.g., a network connection) cannot reasonably be immutable. + +## Related Java Design Patterns + +* [Value Object](https://java-design-patterns.com/patterns/value-object/): Overlapping concept; value objects are typically immutable and compared by value rather than identity. +* [Builder](https://java-design-patterns.com/patterns/builder/): Commonly paired with Immutable to construct complex objects step-by-step before freezing them. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Cloning a mutable object is an alternative to immutability when shared state must occasionally change. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Leverages immutability to safely share fine-grained objects across many contexts. + +## References and Credits + +* [Effective Java, 3rd Edition — Item 17: Minimize Mutability](https://amzn.to/3JIYJoL) +* [Java Concurrency in Practice](https://amzn.to/3vXyUEh) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3JIYJoL) +* [Wikipedia — Immutable object](https://en.wikipedia.org/wiki/Immutable_object) diff --git a/immutable/pom.xml b/immutable/pom.xml new file mode 100644 index 000000000000..e250a2ed48e3 --- /dev/null +++ b/immutable/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + immutable + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.immutable.App + + + + + + + + + diff --git a/immutable/src/main/java/com/iluwatar/immutable/App.java b/immutable/src/main/java/com/iluwatar/immutable/App.java new file mode 100644 index 000000000000..c49cbe041e2d --- /dev/null +++ b/immutable/src/main/java/com/iluwatar/immutable/App.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.immutable; + +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Immutable pattern ensures that an object's state cannot be changed after construction. + * + *

In this example, {@link ImmutableUser} demonstrates the pattern: all fields are final, the + * mutable {@code roles} list is defensively copied, and any state change produces a brand-new + * instance via {@link ImmutableUser#withAge(int)}. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var alice = new ImmutableUser("Alice", 30, List.of("admin", "user")); + LOGGER.info("Original user: {}", alice); + + var olderAlice = alice.withAge(31); + LOGGER.info("Updated user (new object): {}", olderAlice); + LOGGER.info("Original is unchanged: {}", alice); + + // Demonstrate defensive copy: mutating the source list does not affect alice + var mutableRoles = new java.util.ArrayList<>(List.of("viewer")); + var bob = new ImmutableUser("Bob", 25, mutableRoles); + mutableRoles.add("editor"); + LOGGER.info("Bob's roles (unchanged despite external list mutation): {}", bob.getRoles()); + } +} diff --git a/immutable/src/main/java/com/iluwatar/immutable/ImmutableUser.java b/immutable/src/main/java/com/iluwatar/immutable/ImmutableUser.java new file mode 100644 index 000000000000..4b4f38de4ac2 --- /dev/null +++ b/immutable/src/main/java/com/iluwatar/immutable/ImmutableUser.java @@ -0,0 +1,116 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.immutable; + +import java.util.List; + +/** + * An immutable representation of a user. + * + *

All fields are final and set only at construction time. The {@code roles} list is defensively + * copied to prevent external mutation. Any "modification" produces a new {@link ImmutableUser} + * instance, leaving the original unchanged. + */ +public final class ImmutableUser { + + private final String name; + private final int age; + private final List roles; + + /** + * Constructs an {@link ImmutableUser} with the given attributes. + * + * @param name the user's name + * @param age the user's age + * @param roles the user's roles; copied defensively so external changes have no effect + */ + public ImmutableUser(String name, int age, List roles) { + this.name = name; + this.age = age; + this.roles = List.copyOf(roles); + } + + /** + * Returns the user's name. + * + * @return name + */ + public String getName() { + return name; + } + + /** + * Returns the user's age. + * + * @return age + */ + public int getAge() { + return age; + } + + /** + * Returns an unmodifiable view of the user's roles. + * + * @return roles + */ + public List getRoles() { + return roles; + } + + /** + * Returns a new {@link ImmutableUser} identical to this one but with the given name. + * + * @param newName the new name value + * @return a new instance with the updated name + */ + public ImmutableUser withName(String newName) { + return new ImmutableUser(newName, this.age, this.roles); + } + + /** + * Returns a new {@link ImmutableUser} identical to this one but with the given age. + * + * @param newAge the new age value + * @return a new instance with the updated age + */ + public ImmutableUser withAge(int newAge) { + return new ImmutableUser(this.name, newAge, this.roles); + } + + /** + * Returns a new {@link ImmutableUser} identical to this one but with the given roles. + * + * @param newRoles the new roles; copied defensively + * @return a new instance with the updated roles + */ + public ImmutableUser withRoles(List newRoles) { + return new ImmutableUser(this.name, this.age, newRoles); + } + + @Override + public String toString() { + return "ImmutableUser{name='" + name + "', age=" + age + ", roles=" + roles + '}'; + } +} diff --git a/immutable/src/test/java/com/iluwatar/immutable/ImmutableUserTest.java b/immutable/src/test/java/com/iluwatar/immutable/ImmutableUserTest.java new file mode 100644 index 000000000000..0479aff68d89 --- /dev/null +++ b/immutable/src/test/java/com/iluwatar/immutable/ImmutableUserTest.java @@ -0,0 +1,123 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.immutable; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class ImmutableUserTest { + + @Test + void constructorSetsAllFields() { + var user = new ImmutableUser("Alice", 30, List.of("admin")); + assertEquals("Alice", user.getName()); + assertEquals(30, user.getAge()); + assertEquals(List.of("admin"), user.getRoles()); + } + + @Test + void withAgeReturnsNewObjectWithUpdatedAge() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + var updated = original.withAge(31); + + assertEquals(31, updated.getAge()); + assertEquals("Alice", updated.getName()); + assertEquals(original.getRoles(), updated.getRoles()); + } + + @Test + void withAgeDoesNotMutateOriginal() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + original.withAge(99); + + assertEquals(30, original.getAge()); + } + + @Test + void withAgeReturnsDistinctInstance() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + var updated = original.withAge(31); + + assertNotSame(original, updated); + } + + @Test + void defensiveCopyPreventsExternalListMutation() { + var mutableRoles = new ArrayList<>(List.of("viewer")); + var user = new ImmutableUser("Bob", 25, mutableRoles); + + mutableRoles.add("editor"); + + assertEquals(List.of("viewer"), user.getRoles()); + } + + @Test + void getRolesReturnsUnmodifiableList() { + var user = new ImmutableUser("Bob", 25, List.of("viewer")); + + assertThrows(UnsupportedOperationException.class, () -> user.getRoles().add("editor")); + } + + @Test + void withNameReturnsNewObjectWithUpdatedName() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + var updated = original.withName("Bob"); + + assertEquals("Bob", updated.getName()); + assertEquals(30, updated.getAge()); + assertEquals(original.getRoles(), updated.getRoles()); + } + + @Test + void withNameDoesNotMutateOriginal() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + original.withName("Bob"); + + assertEquals("Alice", original.getName()); + } + + @Test + void withRolesReturnsNewObjectWithUpdatedRoles() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + var updated = original.withRoles(List.of("viewer", "editor")); + + assertEquals(List.of("viewer", "editor"), updated.getRoles()); + assertEquals("Alice", updated.getName()); + assertEquals(30, updated.getAge()); + } + + @Test + void withRolesDoesNotMutateOriginal() { + var original = new ImmutableUser("Alice", 30, List.of("admin")); + original.withRoles(List.of("viewer")); + + assertEquals(List.of("admin"), original.getRoles()); + } +} diff --git a/layered-architecture/src/main/java/view/CakeViewImpl.java b/layered-architecture/src/main/java/view/CakeViewImpl.java index a01d1c1600a0..8c2617b7bba7 100644 --- a/layered-architecture/src/main/java/view/CakeViewImpl.java +++ b/layered-architecture/src/main/java/view/CakeViewImpl.java @@ -40,6 +40,7 @@ public CakeViewImpl(CakeBakingService cakeBakingService) { this.cakeBakingService = cakeBakingService; } + @Override public void render() { cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); } diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java index 28b039cc7738..88ff5c55fa56 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java @@ -1,3 +1,27 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ package com.iluwatar.leaderfollowers; import java.security.SecureRandom; diff --git a/localization/de/README.md b/localization/de/README.md index b727e6ba47e1..4442d9682921 100644 --- a/localization/de/README.md +++ b/localization/de/README.md @@ -1,7 +1,7 @@ -# In Java implementierte Entwurfsmuster +# Design Patterns (Entwurfsmuster) in Java ![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) -[![Lizenz MIT](https://img.shields.io/badge/lizenz-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lizenz MIT](https://img.shields.io/badge/Lizenz-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) [![Codezeilen](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Abdeckung](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Chat beitreten unter https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -11,38 +11,43 @@
-In anderen Sprachen lesen: [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md) - +In anderen Sprachen lesen: [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md), [**da**](localization/da/README.md)
# Einführung -Entwurfsmuster sind bewährte Lösungen, die Entwickler nutzen können, um häufige Probleme beim Entwurf von Anwendungen oder Systemen zu lösen. +Design Patterns (auch Entwurfsmuster genannt) sind allgemein anerkannte Vorgehensweisen für den Entwurf von Anwendungen und Systemen, mit denen sich regelmäßig auftauchende Probleme lösen lassen. -Sie helfen dabei, den Entwicklungsprozess zu beschleunigen, indem sie erprobte und zuverlässige Ansätze bereitstellen. +Mit ihnen lässt sich der Entwicklungsprozess beschleunigen, indem erprobte und bewährte Vorlagen zur Verfügung gestellt werden. -Die Wiederverwendung von Entwurfsmustern verhindert subtile Fehler, die zu größeren Problemen führen können, und verbessert die Lesbarkeit des Codes – besonders für Entwickler und Architekten, die mit diesen Mustern vertraut sind. +Die Nutzung von Entwurfsmustern beugt versteckten Fehlern vor, die zu größeren Problemen führen können. Auch verbessert sich die Lesbarkeit des Codes, besonders für Entwickler und Architekten, die mit diesen Mustern vertraut sind. # Erste Schritte -Diese Seite stellt Java-Entwurfsmuster vor. Die Lösungen wurden von erfahrenen Entwicklern und Architekten aus der Open-Source-Community erstellt. Die Muster können entweder durch ihre Beschreibungen oder durch den Quellcode erkundet werden. Die Codebeispiele sind gut kommentiert und eignen sich als Tutorials, um die Muster zu verstehen und umzusetzen. Wir verwenden dabei bekannte und bewährte Open-Source-Java-Technologien. +Diese Seite präsentiert Entwurfsmuster für Java. Die Lösungen wurden von erfahrenen Programmierern und Architekten aus der Open-Source-Community entwickelt. Die Muster können entweder anhand ihrer Beschreibungen oder durch den Quellcode erkundet werden. Die Codebeispiele sind gut kommentiert und eignen sich als Tutorials, wie das jeweilige Muster zu implementieren ist. Wir verwenden dabei bekannte und bewährte Open-Source-Java-Technologien. -Bevor Sie sich mit den Entwurfsmustern beschäftigen, sollten Sie sich mit den grundlegenden [Software-Entwurfsprinzipien](https://java-design-patterns.com/principles/) vertraut machen. +Ehe Sie tiefer in den Stoff eindringen, sollten Sie sich mit den grundlegenden [Software-Entwurfsprinzipien](https://java-design-patterns.com/principles/) vertraut machen. -Entwürfe sollten immer so einfach wie möglich gehalten werden. Beginnen Sie mit den Prinzipien KISS (Keep It Simple, Stupid), YAGNI (You Aren’t Gonna Need It) und "Do The Simplest Thing That Could Possibly Work". Komplexe Muster sollten nur dann verwendet werden, wenn sie wirklich notwendig sind. +Entwürfe sollten immer so einfach wie möglich gehalten werden. Beginnen Sie mit den Prinzipien KISS (Keep It Simple, Stupid), YAGNI (You Aren’t Gonna Need It) und "Do The Simplest Thing That Could Possibly Work". Komplexere Strukturen und Muster sollten erst dann verwendet werden, wenn sie wirklich notwendig sind. Sobald Sie mit diesen Konzepten vertraut sind, können Sie sich die [verfügbaren Entwurfsmuster](https://java-design-patterns.com/patterns/) ansehen. Dafür gibt es verschiedene Ansätze: - Suchen Sie nach einem bestimmten Muster anhand des Namens. Fehlt ein Muster? Melden Sie es gerne [hier](https://github.com/iluwatar/java-design-patterns/issues). - Nutzen Sie Tags wie `Performance`, `Gang of Four` oder `Data access`. -- Durchsuchen Sie die Muster nach Kategorien wie `Creational`, `Behavioral` und anderen. +- Verwenden Sie Kategorien von Patterns wie `Creational`, `Behavioral` usw. Wir hoffen, dass Sie die hier vorgestellten Lösungen für Ihre Projekte nützlich finden und genauso viel Spaß beim Lernen haben, wie wir bei der Entwicklung hatten. -# Mitwirken +# Mitarbeit + +Wenn Sie zum Projekt beitragen möchten, finden Sie alle notwendigen Informationen in unserem [Entwickler-Wiki](https://github.com/iluwatar/java-design-patterns/wiki). Bei Fragen helfen wir Ihnen gerne im [Gitter-Chat](https://gitter.im/iluwatar/java-design-patterns) weiter. + +# Das Buch + +Die Design Patterns sind jetzt als eBook verfügbar. Hier ist es erhältlich: https://payhip.com/b/bNQFX -Wenn Sie zum Projekt beitragen möchten, finden Sie alle notwendigen Informationen in unserem [Entwickler-Wiki](https://github.com/iluwatar/java-design-patterns/wiki). Bei Fragen helfen wir Ihnen gerne im [Gitter-Chatraum](https://gitter.im/iluwatar/java-design-patterns) weiter. +Mitwirkende am Projekt können das Buch kostenlos erhalten. Kontaktieren Sie mich via [Gitter-Chat](https://gitter.im/iluwatar/java-design-patterns) or E-Mail (iluwatar (at) gmail (dot) com ). Die Nachricht sollte enthalten: Ihre Mailadresse, den Usernamen bei Github, and einen Link zu einem akzeptierten Pull Request. # Lizenz -Dieses Projekt steht unter der MIT-Lizenz. \ No newline at end of file +Dieses Projekt unterliegt den Regelungen der MIT-Lizenz. diff --git a/localization/de/abstract-document/README.md b/localization/de/abstract-document/README.md index 13f8d26fbbbf..ca381a3a8c40 100644 --- a/localization/de/abstract-document/README.md +++ b/localization/de/abstract-document/README.md @@ -1,43 +1,48 @@ --- -title: "Abstract Document Pattern in Java: Vereinfachung der Datenverwaltung mit Flexibilität" shortTitle: Abstract Document -description: "Erkunden Sie das Abstract Document Design Pattern in Java. Lernen Sie seine Absicht, Erklärung, Anwendbarkeit, Vorteile kennen und sehen Sie reale Beispiele zur Implementierung flexibler und dynamischer Datenstrukturen." -category: Strukturell +category: Structural language: de tag: - - Abstraktion - - Entkopplung - - Dynamische Typisierung - - Kapselung - - Erweiterbarkeit - - Polymorphismus + - Abstraction + - Decoupling + - Dynamic typing + - Encapsulation + - Extensibility + - Polymorphism --- -## Absicht des Abstract Document Design Patterns +## Zweck -Das Abstract Document Design Pattern in Java ist ein wichtiges strukturelles Design Pattern, das eine konsistente Möglichkeit bietet, hierarchische und baumartige Datenstrukturen zu handhaben, indem es eine gemeinsame Schnittstelle für verschiedene Dokumenttypen definiert. Es trennt die Kernstruktur des Dokuments von spezifischen Datenformaten und ermöglicht dynamische Aktualisierungen und vereinfachte Wartung. +Abstract Document ist ein wichtiges Struktur-Pattern, das ein einheitliches Handling von hierarchischen baumartige Datenstrukturen ermöglicht, indem es eine gemeinsame Schnittstelle für verschiedene Dokumenttypen definiert. Es trennt die Kernstruktur des Dokuments von spezifischen Datenformaten und ermöglicht so dynamische Aktualisierungen und einfachere Wartung. -## Detaillierte Erklärung des Abstract Document Patterns mit realen Beispielen +## Detaillierte Erklärung -Das Abstract Document Design Pattern in Java ermöglicht die dynamische Handhabung nicht-statischer Eigenschaften. Dieses Pattern verwendet das Konzept der Traits, um Typsicherheit zu gewährleisten und Eigenschaften verschiedener Klassen in eine Menge von Schnittstellen zu trennen. +Abstract Document erlaubt die dynamische Behandlung nicht-statischer Eigenschaften. Dieses Pattern verwendet das Konzept der Traits, um Typsicherheit zu gewährleisten und Eigenschaften verschiedener Klassen in verschiedene Schnittstellen abzuspalten. Reales Beispiel -> Betrachten Sie ein Bibliothekssystem, das das Abstract Document Design Pattern in Java implementiert, wo Bücher verschiedene Formate und Attribute haben können: physische Bücher, eBooks und Hörbücher. Jedes Format hat einzigartige Eigenschaften, wie Seitenzahl für physische Bücher, Dateigröße für eBooks und Dauer für Hörbücher. Das Abstract Document Design Pattern ermöglicht es dem Bibliothekssystem, diese verschiedenen Formate flexibel zu verwalten. Durch die Verwendung dieses Patterns kann das System Eigenschaften dynamisch speichern und abrufen, ohne dass eine starre Struktur für jeden Buchtyp erforderlich ist, was es einfacher macht, neue Formate oder Attribute in der Zukunft hinzuzufügen, ohne dass wesentliche Änderungen am Codebase erforderlich sind. +> Denken Sie an ein Bibliothekssystem, wo Bücher verschiedene Formate und Attribute haben können: physische Bücher, eBooks und Hörbücher. Jedes Format hat spezielle Eigenschaften, wie die Seitenzahl bei physischen Büchern, die Dateigröße bei eBooks oder die Spielzeit bei Hörbüchern. Das Abstract Document Design Pattern ermöglicht es dem Bibliothekssystem, diese verschiedenen Formate flexibel zu verwalten. Durch die Verwendung dieses Patterns kann das System Eigenschaften dynamisch speichern und abrufen, ohne dass eine starre Struktur für jeden Buchtyp erforderlich ist. Damit wird es einfacher, in der Zukunft neue Formate oder Attribute hinzuzufügen, ohne erhebliche Änderungen am Code vornehmen zu müssen. In einfachen Worten -> Das Abstract Document Pattern ermöglicht das Anhängen von Eigenschaften an Objekte, ohne dass diese davon wissen. +> Abstract Document erlaubt das Anhängen von Eigenschaften an Objekte, ohne dass diese davon wissen. Wikipedia sagt -> Ein objektorientiertes strukturelles Design Pattern zur Organisation von Objekten in schwach typisierten Schlüssel-Wert-Speichern und zur Bereitstellung der Daten über typisierte Ansichten. Der Zweck des Patterns besteht darin, einen hohen Grad an Flexibilität zwischen Komponenten in einer stark typisierten Sprache zu erreichen, in der neue Eigenschaften zur Objektstruktur dynamisch hinzugefügt werden können, ohne die Unterstützung der Typsicherheit zu verlieren. Das Pattern verwendet Traits, um verschiedene Eigenschaften einer Klasse in verschiedene Schnittstellen zu trennen. +> Ein objektorientiertes strukturelles Design Pattern zur Organisation von Objekten in schwach typisierten Schlüssel-Wert-Speichern mit Darstellung der Daten über typisierte Ansichten. Der Zweck des Patterns besteht darin, einen hohen Grad an Flexibilität zwischen Komponenten in einer stark typisierten Sprache zu erreichen, in der neue Eigenschaften zur Objektstruktur dynamisch hinzugefügt werden können, ohne die Unterstützung der Typsicherheit zu verlieren. Das Pattern verwendet Traits, um verschiedene Klasseneigenschaften in verschiedene Schnittstellen abzutrennen. -## Programmatisches Beispiel des Abstract Document Patterns in Java +## Klassendiagramm -Betrachten Sie ein Auto, das aus mehreren Teilen besteht. Wir wissen jedoch nicht, ob das spezifische Auto wirklich alle Teile hat oder nur einige davon. Unsere Autos sind dynamisch und extrem flexibel. +![Abstract Document](/abstract-document/etc/abstract-document.png "Abstract Document Traits und Domain") -Lassen Sie uns zunächst die Basisklassen `Document` und `AbstractDocument` definieren. Sie sorgen im Wesentlichen dafür, dass das Objekt eine Eigenschaftsmap und eine beliebige Anzahl von Kindobjekten enthält. +## Beispielprogramm in Java + +Betrachten Sie ein Auto, das aus mehreren Teilen besteht. Wir wissen jedoch nicht, +ob das spezifische Auto wirklich alle Teile hat oder nur einige davon. +Unsere Autos sind dynamisch und extrem flexibel. + +Zunächst definieren wir die Basisklassen `Document` und `AbstractDocument`. +Sie sorgen im Wesentlichen dafür, dass jedes Objekt eine Map von Eigenschaften und eine beliebige Anzahl von Kindobjekten enthält. ```java public interface Document { @@ -80,10 +85,11 @@ public abstract class AbstractDocument implements Document { .map(constructor); } - // Andere Eigenschaften und Methoden... + // Weitere Eigenschaften und Methoden... } ``` -Als nächstes definieren wir ein Enum Property und eine Menge von Schnittstellen für Typ, Preis, Modell und Teile. Dies ermöglicht es uns, eine statisch aussehende Schnittstelle für unsere Car-Klasse zu erstellen. + +Als nächstes definieren wir ein Enum `Property` und je eine Schnittstelle für Typ, Preis, Modell und Teile. So können wir eine statisch aussehende Schnittstelle für unsere Klasse `Car` erstellen. ```java public enum Property { @@ -120,33 +126,43 @@ public interface HasParts extends Document { } ``` -Jetzt sind wir bereit, das `Car` einzuführen. +Nun können wir das `Car` einführen. ```java - public static void main(String[] args) { - LOGGER.info("Konstruktion von Teilen und Auto"); - - var wheelProperties = Map.of( - Property.TYPE.toString(), "wheel", - Property.MODEL.toString(), "15C", - Property.PRICE.toString(), 100L); - - var doorProperties = Map.of( - Property.TYPE.toString(), "door", - Property.MODEL.toString(), "Lambo", - Property.PRICE.toString(), 300L); - - var carProperties = Map.of( - Property.MODEL.toString(), "300SL", - Property.PRICE.toString(), 10000L, - Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); - - var car = new Car(carProperties); - - LOGGER.info("Hier ist unser Auto:"); - LOGGER.info("-> Modell: {}", car.getModel().orElseThrow()); - LOGGER.info("-> Preis: {}", car.getPrice().orElseThrow()); - LOGGER.info("-> Teile: "); +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` +Und schließlich konstruieren und verwenden wir ein solches `Car`. + +```java +public static void main(String[] args) { + LOGGER.info("Constructing parts and car"); + +var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + +var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + +var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + +var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", p.getType().orElse(null), p.getModel().orElse(null), @@ -154,50 +170,67 @@ Jetzt sind wir bereit, das `Car` einzuführen. ); } ``` -Die Programmausgabe: +Programmausgabe: ``` -07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Konstruktion von Teilen und Auto -07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Hier ist unser Auto: -07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> Modell: 300SL -07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> Preis: 10000 -07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> Teile: -07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- Rad/15C/100 -07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- Tür/Lambo/300 +07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Constructing parts and car +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Here is our car: +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> model: 300SL +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> price: 10000 +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> parts: +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- wheel/15C/100 +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- door/Lambo/300 ``` -## Abstract Document Pattern Klassendiagramm - -![Abstract Document](./etc/abstract-document.png "Abstract Document Traits und Domain") -## Wann sollte das Abstract Document Pattern in Java verwendet werden? +## Verwendung -Das Abstract Document Design Pattern ist besonders vorteilhaft in Szenarien, die eine Verwaltung unterschiedlicher Dokumenttypen in Java erfordern, die einige gemeinsame Attribute oder Verhaltensweisen teilen, aber auch einzigartige Attribute oder Verhaltensweisen haben, die spezifisch für ihren Typ sind. Hier sind einige Szenarien, in denen das Abstract Document Design Pattern anwendbar ist: +Abstract Document ist besonders vorteilhaft in Szenarien, die eine Verwaltung unterschiedlicher +Dokumenttypen erfordern, die zwar einige gemeinsame Attribute oder Verhaltensweisen teilen, +aber auch typspezifische Eigenschaften haben. Hier sind einige Beispiele: * **Content-Management-Systeme (CMS)**: In einem CMS könnten verschiedene Arten von Inhalten wie Artikel, Bilder, Videos usw. vorkommen. Jede Inhaltsart könnte gemeinsame Attribute wie Erstellungsdatum, Autor und Tags haben, aber auch spezifische Attribute wie Bildabmessungen für Bilder oder Videodauer für Videos. -* **Dateisysteme**: Wenn Sie ein Dateisystem entwerfen, in dem unterschiedliche Dateitypen verwaltet werden müssen, wie Dokumente, Bilder, Audiodateien und Verzeichnisse, kann das Abstract Document Pattern helfen, eine konsistente Möglichkeit zum Zugriff auf Attribute wie Dateigröße, Erstellungsdatum usw. zu bieten, während spezifische Attribute wie Bildauflösung oder Audiodauer berücksichtigt werden. +* **Dateisysteme**: Wenn Sie ein Dateisystem entwerfen, in dem unterschiedliche Dateitypen verwaltet werden müssen, wie Dokumente, Bilder, Audiodateien und Verzeichnisse, kann das Pattern helfen, einen einheitlichen Zugriff auf Attribute wie Dateigröße, Erstellungsdatum usw. zu bieten, aber zugleich spezifische Attribute wie Bildauflösung oder Audiodauer zu berücksichtigen. -* **E-Commerce-Systeme**: Eine E-Commerce-Plattform könnte verschiedene Produkttypen haben, wie physische Produkte, digitale Downloads und Abonnements. Jeder Typ könnte gemeinsame Attribute wie Name, Preis und Beschreibung haben, aber auch einzigartige Attribute wie Versandgewicht für physische Produkte oder Download-Link für digitale Produkte. +* **E-Commerce-Systeme**: Eine E-Commerce-Plattform kann verschiedene Produkttypen haben, +wie physische Produkte, digitale Downloads und Abonnements. +Alle Typen haben gemeinsame Attribute wie Name, Preis und Beschreibung, +aber auch einzigartige Attribute wie Versandgewicht für physische Produkte +oder Download-Link für digitale Produkte. -* **Medizinische Aufzeichnungssysteme**: Im Gesundheitswesen könnten Patientenakten verschiedene Datentypen enthalten, wie demografische Daten, medizinische Vorgeschichte, Testergebnisse und Rezepte. Das Abstract Document Pattern kann helfen, gemeinsame Attribute wie Patienten-ID und Geburtsdatum zu verwalten, während spezialisierte Attribute wie Testergebnisse oder verschriebene Medikamente berücksichtigt werden. +* **Medizindatensysteme**: Im Gesundheitswesen enthalten Patientenakten verschiedene +Datentypen wie demografische Daten, medizinische Vorgeschichte, Testergebnisse und Rezepte. +Das Abstract Document Pattern kann helfen, gemeinsame Attribute wie Patienten-ID und Geburtsdatum zu +verwalten und zusätzlich spezielle Attribute wie Testergebnisse oder verschriebene Medikamente zu berücksichtigt werden. -* **Konfigurationsmanagement**: Bei der Verwaltung von Konfigurationseinstellungen für Softwareanwendungen gibt es möglicherweise verschiedene Arten von Konfigurationselementen, jedes mit einer eigenen Reihe von Attributen. Das Abstract Document Pattern kann verwendet werden, um diese Konfigurationselemente zu verwalten, während eine konsistente Möglichkeit zum Zugriff auf und Bearbeiten der Attribute sichergestellt wird. +* **Konfigurationsmanagement**: Bei der Verwaltung von Konfigurationseinstellungen für +Software gibt es verschiedene Arten von Konfigurationselementen, jedes mit einer eigenen Reihe +von Attributen. Mit dem Abstract Document Pattern können diese Konfigurationselemente +konsistent verwaltet werden. -* **Bildungsplattformen**: Bildungssysteme könnten verschiedene Arten von Lernmaterialien wie textbasierte Inhalte, Videos, Quizze und Aufgaben haben. Gemeinsame Attribute wie Titel, Autor und Veröffentlichungsdatum können geteilt werden, während spezifische Attribute wie Videodauer oder Aufgabenfälligkeit für jeden Typ einzigartig sind. +* **Bildungsplattformen**: Bildungssysteme nutzen verschiedene Arten von Lernmaterialien wie textbasierte Inhalte, +Videos, Quiz und Übungsaufgaben. Gemeinsame Attribute können Titel, Autor und Veröffentlichungsdatum sein, +während spezifische Attribute wie Videodauer oder Aufgabenfälligkeit typabhängig sind. -* **Projektmanagement-Tools**: In Projektmanagement-Anwendungen könnten unterschiedliche Aufgabenarten wie To-Do-Items, Meilensteine und Probleme vorliegen. Das Abstract Document Pattern könnte verwendet werden, um allgemeine Attribute wie Aufgabenname und Zuweisung zu handhaben, während spezifische Attribute wie Meilensteindaten oder Problemprioritäten zugelassen werden. +* **Projektmanagement-Tools**: In Projektmanagement-Anwendungen können unterschiedliche Aufgabenarten +wie To-Dos, Meilensteine und Probleme vorliegen. Das Abstract Document Pattern kann verwendet werden, um allgemeine +Attribute wie Aufgabenname und Zuständigkeit zu handhaben, während spezifische Attribute wie Meilensteindaten oder +Aufgabenprioritäten zugelassen sind. -* **Dokumente haben vielfältige und sich entwickelnde Attributstrukturen.** +* **Dokumente haben vielfältige und sich verändernde Attributstrukturen.** -* **Dynamisches Hinzufügen neuer Eigenschaften ist eine häufige Anforderung.** +* **Häufig ist es erforderlich, neue Eigenschaften dynamisch hinzuzufügen.** -* **Entkopplung des Datenzugriffs von spezifischen Formaten ist entscheidend.** +* **Entscheidend ist die Entkopplung des Datenzugriffs von spezifischen Formaten.** -* **Wartbarkeit und Flexibilität sind entscheidend für die Codebasis.** +* **Wartbarkeit und Flexibilität sind wesentlich für die Codebasis.** -Die Hauptidee hinter dem Abstract Document Design Pattern ist es, eine flexible und erweiterbare Möglichkeit zur Verwaltung unterschiedlicher Dokumenttypen oder Entitäten mit gemeinsamen und spezifischen Attributen bereitzustellen. Durch die Definition einer gemeinsamen Schnittstelle und deren Implementierung über verschiedene Dokumenttypen hinweg können Sie einen besser organisierten und konsistenteren Ansatz zur Handhabung komplexer Datenstrukturen erreichen. +Die Kernidee des Abstract Document Pattern ist es, eine flexible und erweiterbare Möglichkeit zur Verwaltung +unterschiedlicher Dokumenttypen oder Entitäten mit gemeinsamen und spezifischen Attributen bereitzustellen. +Durch die Definition einer gemeinsamen Schnittstelle und deren Implementierung über verschiedene Dokumenttypen +hinweg können Sie komplexe Datenstrukturen besser organisiert und einheitlich verarbeiten. -## Vorteile und Abwägungen des Abstract Document Patterns +## Vor- und Nachteile **Vorteile:** @@ -206,12 +239,12 @@ Die Hauptidee hinter dem Abstract Document Design Pattern ist es, eine flexible * **Wartbarkeit**: Fördert sauberen und anpassungsfähigen Code durch Trennung der Verantwortlichkeiten. * **Wiederverwendbarkeit**: Typspezifische Ansichten ermöglichen eine Wiederverwendung des Codes zum Zugriff auf bestimmte Attributtypen. -**Abwägungen:** +**Nachteile:** -* **Komplexität**: Erfordert die Definition von Schnittstellen und Ansichten, was zu zusätzlichem Implementierungsaufwand führt. -* **Leistung**: Kann im Vergleich zum direkten Datenzugriff zu leichtem Leistungsaufwand führen. +* **Komplexität**: Die Definition von Schnittstellen und spezifischen Ansichten erfordert zusätzlichen Implementierungsaufwand. +* **Performance**: Leicht verringerte Performance im Vergleich zum direkten Datenzugriff möglich. -## Quellen und Danksagungen +## Quellen * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/localization/de/abstract-factory/README.md b/localization/de/abstract-factory/README.md new file mode 100644 index 000000000000..2e12ab4859f9 --- /dev/null +++ b/localization/de/abstract-factory/README.md @@ -0,0 +1,225 @@ +--- +shortTitle: Abstract Factory +category: Creational +language: de +tag: + - Abstraction + - Decoupling + - Gang of Four + - Instantiation + - Polymorphism +--- + +## Alternativbezeichnung + +* Kit + +## Zweck + +Das Abstract-Factory-Pattern stellt ein Interface zum Erzeugen von Instanzen einer Familie +ähnlicher oder voneinander abhängiger Objekte zur Verfügung, ohne dass dabei deren konkrete Klasse +festgelegt ist. Damit werden Modularität und Flexibilität im Softwaredesign verbessert. + +## Detaillierte Erklärung +Reales Beispiel + +> Stellen Sie sich einen Möbelhersteller vor, der Möbelstücke in verschiedenen Stilen anbietet, z.B. modern, viktorianisch, rustikal. Zu jedem Stil gibt es Produkte wie Stühle, Tische und Sessel. Um Produkte unabhängig vom Stil einheitlich verwalten zu können, wird das Abstract-Factory-Pattern eingesetzt. +> +> Dabei ist die Abstract Factory ein Interface, mit dem mehrere Familien zusammengehöriger Möbelstücke (Stühle, Tische, Sessel) erzeugt werden. Jede einzelne konkrete Factory (ModernFurnitureFactory, VictorianFurnitureFactory, RusticFurnitureFactory) implementiert dieses Interface und erzeugt Möbelstücke des jeweiligen Stils. Auf diese Weise können ganze Einrichtungen in einem bestimmten Stil produziert werden, ohne dass man sich um die Details der Instantiierung kümmern muss. Das erlaubt eine einheitliche Bearbeitung und einen einfachen Wechsel des Einrichtungsstils. + +In einfachen Worten + +> Eine Factory für Factories - eine Factory, die mehrere zusammengehörende Factories vereinigt, ohne die konkrete Klasse der Objekte festzulegen. + +Wikipedia sagt + +> Das Abstract-Factory-Pattern dient zur Kapselung einer Gruppe einzelner Factories mit gemeinsamem Thema, wobei deren konkrete Klasse variabel bleibt. + +Klassendiagramm + +![Abstract Factory class diagram](/abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## Programmbeispiel + +Um ein Königreich mit dem Abstract-Factory-Pattern zu erzeugen, brauchen wir ein gemeinsames Thema. Das Elben-Königreich hat einen Elbenkönig, ein Elbenschlos und eine Elbenarmee, das Ork-Königreich dagegen einen Orkkönig, ein Orkschloss und eine Orkarmee. Die Objekte des jeweiligen Königreichs hängen voneinander ab. + +Zunächst definieren wir die Interfaces und implementieren sie für die einzelnen Königreiche. + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Elben-Implementationen -> +public class ElfCastle implements Castle { + static final String DESCRIPTION = "This is the elven castle!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfKing implements King { + static final String DESCRIPTION = "This is the elven king!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfArmy implements Army { + static final String DESCRIPTION = "This is the elven Army!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Ork-Implementations analog -> ... +``` + +Nun kommt das Interface für die Königreich-Factory und seine Implementationen. + +```java +public interface KingdomFactory { + Castle createCastle(); + + King createKing(); + + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +// Ork-Implementationen analog -> ... +``` + +Jetzt können wir eine Factory bauen, die eine Instanz von entweder `ElfKingdomFactory` oder `OrcKingdomFactory` erstellt. Diese nennen wir `FactoryMaker`. Der Client kann `FactoryMaker` verwenden, um die gewünschte Factory zu erzeugen, mit der dann wiederum konkrete Objekte (abgeleitet von `Army`, `King`, `Castle`) erzeugt werden können. In diesem Beispiel nutzen wir ein Enum als Parameter für die gewünschte Art der Factory. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + }; + } +} +``` + +Hier die main-Methode der Beispielanwendung: + +```java +LOGGER.info("elf kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); + +LOGGER.info("orc kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); +``` + +Ausgabe: + +``` +07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king! +``` + +## Verwendung + +Einsatzkriterien für Abstract Factory: +* Das System sollte nicht davon abhängig sein, wie die Produkte erzeugt, zusammengesetzt und dargestellt werden. +* Nötige Konfiguration für eine oder mehrere Produktfamilien. +* Eine Familie ähnlicher Produkte muss gemeinsam auf gleiche Art genutzt werden. +* Die Klassenbibliothek der Produkte zeigt dem Anwender nur ihre Interfaces, nicht ihre Implementation. +* Abhängigkeiten zwischen den Produkten existieren kürzer als die Verwendung dauert. +* Abhängigkeiten müssen zur Laufzeit durch Parameter konstruiert werden. +* Zur Laufzeit wird ein Produkt aus einer Familie ausgewählt. +* Keine Code-Änderungen bei Hinzufügen weiterer Familien oder Produkte. + +## Tutorials + +* [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java) +* [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory) + +## Vor- und Nachteile + +Vorteile: + +* Flexibilität: Einfacher Wechsel zwischen Produktfamilien ohne Codeänderung. + +* Entkopplung: Der Verwender sieht nur abstrakte Interfaces, wodurch sich Portabilität und Wartbarkeit verbessern. + +* Wiederverwendbarkeit: Objekte aus einer Abstract Factory können projektübergreifend eingesetzt werden. + +* Wartbarkeit: Änderungen an einer einzelnen Produktfamilie sind nur lokal in deren Implementation nötig, was Updates erleichtert. +* +Nachteile: + +* Komplexität: Anfänglicher Zusatzaufwand für die Definition von Interfaces und konkreten Factories. +* +* Intransparenz: Die Transparenz könnte leiden, weil der Client-Code mit den Produkten nur indirekt über den Umweg der Factories interagiert. + +## Reale Anwendungen + +* Die `LookAndFeel` Klassen von Java Swing stellen mittels Abstract Factory verschiedene optische Darstellungen zur Verfügung. +* Verschiedene Implementationen im Java Abstract Window Toolkit (AWT) verwenden das Pattern zur Erzeugung diverser GUI-Komponenten. +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Verwandte Patterns + +* [Factory-Methoden](https://java-design-patterns.com/patterns/factory-method/): Abstract Factory verwendet Factory-Methoden zur Erzeugung von Produkten. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Abstract-Factory-Klassen sind häufig als Singletons implementiert. +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Ähnlich wie Abstract Factory, aber mit Schwerpunkt auf flexibler Konfiguration und Verwaltung verwandter Objekte . + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Design Patterns in Java](https://amzn.to/3Syw0vC) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U) diff --git a/localization/de/active-object/README.md b/localization/de/active-object/README.md new file mode 100644 index 000000000000..d37a52e7a09d --- /dev/null +++ b/localization/de/active-object/README.md @@ -0,0 +1,232 @@ +--- +shortTitle: Active Object +category: Concurrency +language: de +tag: + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management +--- + +## Zweck + +Active Object bietet eine zuverlässige Methode zur Behandlung asynchroner Prozesse, mit der reaktionsfähige Anwendungen +und effizientes Thread-Management gesichert werden. +Dies wird dadurch erreicht, dass die einzelnen Aufgaben in Objekte gekapselt werden, die in eigenen Threads (Steuerungsflüssen) +mit eigener Nachrichtenwarteschlange aktiv sind. Durch diese Trennung bleibt der Hauptthread +reaktionsfähig und Probleme wie direkte Threadmanipulation oder gemeinsamer Zugriff auf Zustände werden vermieden. + +## Detaillierte Erklärung + +Reales Beispiel + +> Stellen Sie sich ein gut besuchtes Restaurant vor, in dem die Gäste Bestellungen bei den +> Kellner aufgeben. Die Kellner gehen nicht selbst in die Küche, um die Essen selbst zuzubereiten, +> sondern sie schreiben die Bestellungen auf Zettel und geben diese dem Küchenmanager. +> Der Manager organisiert eine Gruppe von Köchen, die die verschiedenen Mahlzeiten parallel zubereiten. +> Wenn ein Koch frei ist, nimmt er eine Bestellung aus der Warteschlange, bereitet das Essen zu +> und benachrichtigt den Kellner, sobald es fertig zum Servieren ist. +> +> In dieser Analogie stehen die Kellner für die Client-Threads, +> der Küchenmanager für den Thread-Scheduler, und die Köche für die Methodenausführung +> in verschiedenen Threads. +> Die Organisation ermöglicht es, dass die Kellner immer weiter Bestellungen annehmen können, +> ohne durch die Essenszubereitung aufgehalten zu werden; so wie das Active-Object-Pattern +> den Methodenaufruf von der Ausführung trennt, um die Effizienz zu verbessern. + +In einfachen Worten + +> Das Active-Object-Pattern trennt Methodenausführung und Methodenaufruf, +> um Parallelitätsgrad und Reaktionsfähigkeit in Multithread-Anwendungen zu verbessern. + +Wikipedia sagt + +> Das Design-Pattern Active Object entkoppelt die Methodenausführung vom Methodenaufruf +> für Objekte, die in ihrem jeweils eigenen Thread arbeiten. +> Ziel ist, Parallelität dadurch zu ermöglichen, dass Methoden asynchron aufgerufen werden und ein +> Scheduler die Anfragen organisiert. +> +> Das Pattern besteht aus sechs Elementen. +> +> * Ein Proxy stellt für Clients ein Interface mit öffentlich zugänglichen Methoden zur Verfügung. +> * Ein weiteres Interface definiert die Anfragen an ein aktives Objekt. +> * Eine Liste offener Client-Anfragen. +> * Ein Scheduler entscheidet, welche Anfrage als nächstes ausgeführt wird. +> * Die Implementation der Methoden. +> * Eine Callback-Variable zur Rückmeldung des Ergebnisses. + +Ablaufdiagramm + +![Active Object sequence diagram](/active-object/etc/active-object-sequence-diagram.png) + + +## Programmbeispiel in Java + +Die Orcs sind wilde und nicht zu bändigende Kreaturen. Anscheinend haben sie ihre eigene Steuerung, die nur von ihrem vorherigen Verhalten bestimmt wird. +Um eine derartige Kreatur zu implementieren, können wir das Active-Objekt-Pattern benutzen. + +```java +public abstract class ActiveCreature { + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.", name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Man sieht, dass jede Klasse, die `ActiveCreature` erweitert, ihren eigenen Kontrollfluss für den Aufruf und die Ausführung der Methoden zum Herumstreifen und Essen hat. + +Beispielsweise die Klasse `Orc`: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } +} +``` +Nun können wir etliche Kreaturen dieser Art schaffen, sie zum Essen und Herumstreifen auffordern, aber jede von ihnen wird das in Eigenregie (eigener Thread) ausführen. + +```java +public class App implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); + + private static final int NUM_CREATURES = 3; + + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + List creatures = new ArrayList<>(); + try { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.add(new Orc(Orc.class.getSimpleName() + i)); + creatures.get(i).eat(); + creatures.get(i).roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.get(i).kill(0); + } + } + } +} +``` + +Programmausgabe: + +``` +09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating! +09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating! +09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. +``` + +## Verwendung + +* Wenn asynchrone Aufgaben behandelt werden sollen, ohne dass der Hauptthread blockiert wird, um bessere Performance und Reaktionsfähigkeit zu gewährleisten. +* Bei asynchronen Interaktionen mit externen Ressourcen. +* Zur Verbesserung der Reaktionsfähigkeit. +* Zum Management parallel ablaufender Aufgaben in modularer und wartbarer Art und Weise. +* +## Tutorials + +* [Android and Java Concurrency: The Active Object Pattern(Douglas Schmidt)](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) + +## Reale Anwendungen in Java + +* Echtzeit-Handelssysteme mit asynchroner Verarbeitung von Transaktionen. +* GUIs, bei denen langwierige Arbeiten im Hintergrund ablaufen, ohne dass die Benutzeroberfläche einfriert. +* Spiele, bei denen Aktualisierungen des Spielstatus oder KI-Berechnungen parallel abgearbeitet werden. + +## Vor- und Nachteile + +Vorteile + +* Reaktionsfähigkeit des Hauptthreads wird verbessert +* Parallelitätsprobleme sind in den Objekten gekapselt +* Ermöglicht bessere Codeorganisation und -wartbarkeit. +* Sorgt für Threadsicherheit und vermeidet Probleme beim gemeinsamen Zugriff auf Zustände. + +Nachteile + +* Zusatzaufwand für die Übermittlung von Benachrichtigungen und das Threadmanagement. +* Nicht für alle Arten von Nebenläufigkeitsproblemen geeignet. + +## Verwandte Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): Kapselt Anfragen als Objekte, ähnlich wie Active Object es mit Methodenaufrufen macht. +* [Promise](https://java-design-patterns.com/patterns/promise/): Bietet einen Weg zur Abfrage von Ergebnissen eines asynchronen Methodenaufrufs, oft mit Active Object kombiniert. +* [Proxy](https://java-design-patterns.com/patterns/proxy/): Active Object kann einen Proxy verwenden, um asynchrone Methodenaufrufe zu behandeln. + +## Quellen + +* [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) +* [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV) +* [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/localization/de/actor-model/README.md b/localization/de/actor-model/README.md new file mode 100644 index 000000000000..3c3cb436eb97 --- /dev/null +++ b/localization/de/actor-model/README.md @@ -0,0 +1,203 @@ +--- +shortTitle: Actor Model +category: Concurrency +language: de +tag: + - Concurrency + - Messaging + - Isolation + - Asynchronous + - Distributed Systems + - Actor Model +--- + +## Alternativbezeichnungen + +- Message-passing concurrency +- Actor-based concurrency + +--- + +## Zweck + +Das Actor-Model-Pattern ermöglicht die Konstruktion von hochparallelen fehlertoleranten verteilten Systemen, +indem es isolierte Komponenten (Akteure) verwendet, die ausschließlich über asynchronen Nachrichtenaustausch interagieren. + +## Detaillierte Erklärung + +--- + +### 📦 Reales Beispiel + +Stellen Sie sich ein Kundendienstsystem vor. +- Jeder **Kundendienstmitarbeiter** ist ein **Aktor**. +- Kunden **senden Anfragen (Nachrichten)** an die Mitarbeiter. +- Jeder Mitarbeiter behandelt zu einem bestimmten Zeitpunkt genau eine Anfrage und kann diese **asynchron beantworten**, +ohne dabei anderen Mitarbeitern in die Quere zu kommen. + +--- + +### 🧠 In einfachen Worten + +> "Aktoren sind wie unabhängige Arbeiter, die keine Ressourcen teilen und nur über Nachrichten kommunizieren." + +--- + +### 📖 Wikipedia sagt + +> Das [Actor Model](https://en.wikipedia.org/wiki/Actor_model) ist ein mathematisches Modell +> für parallele Informationsverarbeitung, das "Aktoren" als universelle Ausführer von Aufgaben betrachtet. + +--- + +### 🧹 Klassendiagramm + +![UML Class Diagram](./etc/Actor_Model_UML_Class_Diagram.png) + +--- + +## Programmbeispiel in Java + +### Actor.java + +```java +public abstract class Actor implements Runnable { + + @Setter + @Getter + private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = true; + + + public void send(Message message) { + mailbox.add(message); + } + + public void stop() { + active = false; + } + + @Override + public void run() { + + } + + protected abstract void onReceive(Message message); +} + +``` + +### Message.java + +```java + +@AllArgsConstructor +@Getter +@Setter +public class Message { + private final String content; + private final String senderId; +} +``` + +### ActorSystem.java + +```java +public class ActorSystem { + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} +``` + +### App.java + +```java +public class App { + public static void main(String[] args) { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} +``` + +--- + +## Verwendung + +- Bei der Konstruktion **paralleler oder verteilter Systeme** +- Wenn **keine veränderlichen Zustände geteilt** werden sollen +- Wenn **asynchrone, nachrichtenbasierte Kommunikation** benötigt wird +- Wenn die Komponenten **isoliert und lose gekoppelt** sein sollen. + +--- + +## Tutorials + +- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka) +- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143) + +--- + +## Reale Anwendungen + +- [Akka Framework](https://akka.io/) +- [Concurrency in Erlang und Elixir](https://www.erlang.org/) +- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/) +- JVM-basierte Spiel-Engines und Simulatoren + +--- + +## Vor- und Nachteile + +### ✅ Vorteile +- Unterstützt hohes Maß an Parallelität +- Leichte Skalierbarkeit über Zahl der Threads oder Prozessoren. +- Fehlerisolation und -behebbarkeit. +- Geordnete Nachrichten in den Aktoren + +### ⚠️ Nachteile +- Schwierigeres Debugging wegen asynchronen Verhaltens +- Leichte Performance-Einbußen durch die Nachrichten-Warteschlangen +- Komplexeres Design als bei einfachem Methodenaufruf +--- + +## Verwandte Patterns + +- [Command Pattern](../command) +- [Mediator Pattern](../mediator) +- [Event-Driven Architecture](../event-driven-architecture) +- [Observer Pattern](../observer) + +--- + +## Quellen + +- *Programming Erlang*, Joe Armstrong +- *Reactive Design Patterns*, Roland Kuhn +- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/) +- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html) + diff --git a/localization/de/acyclic-visitor/README.md b/localization/de/acyclic-visitor/README.md new file mode 100644 index 000000000000..d60f456e528a --- /dev/null +++ b/localization/de/acyclic-visitor/README.md @@ -0,0 +1,192 @@ +--- +shortTitle: Acyclic Visitor +category: Behavioral +language: de +tag: + - Decoupling + - Extensibility + - Interface + - Object composition +--- + +## Zweck + +Das Acyclic-Visitor-Pattern entkoppelt Operationen von der Objekthierarchie und erlaubt so ein flexibles Design für verschiedenste Anwendungen. + +## Detailierte Erklärung + +Reales Beispiel + +> Als Vergleich aus der realen analogen Welt soll ein System von Museumsführern dienen. +> Stellen Sie sich ein Museum mit verschiedensten Ausstellungsstücken (Bilder, Skulpturen, historische Artefakte, ...) vor. +> Es gibt dort verschiedene Typen von Führern (Menschen, Audio-Guides, VR-Führer), die zu jedem Objekt Informationen geben. +> Wenn nun eine neue Art der Führung eingeführt wird, muss nicht jedes Ausstellungsstück dafür angepasst werden. +> Stattdessen implementiert jeder Führer eine Schnittstelle zu den jeweiligen Ausstellungstücken. +> Auf diese Weise ist das System leicht erweiterbar. + +In einfachen Worten + +> Acyclic Visitor erlaubt das Hinzufügen von Funktionen, ohne die bestehende Hierarchie anpassen zu müssen. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) sagt: + +> Das Acyclic-Visitor-Pattern erlaubt es, neue Funktionen zu einer bestehenden Klassenhierarchie +> hinzuzufügen, ohne diese Hierarchie zu verändern und ohne Abhängigkeitszyklen (wie beim Visitor Pattern) zu schaffen. + +Ablaufdiagramm + +![Acyclic Visitor sequence diagram](/acyclic-visitor/etc/acyclic-visitor-sequence-diagram.png "Acyclic Visitor sequence diagram") + + +## Programmbeispiel + +Wir betrachten eine Hierarchie von Modem-Klassen. Die Modems werden besucht von einem externen Algorithmus, +der auf Filterkritien (Unix- oder DOS-Kompatibilität) basiert. + +Here die `Modem` Hierarchie. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + + // Weitere Eigenschaften und Methoden ... + + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + + // Weitere Eigenschaften und Methoden... + + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Danach führen wir die `ModemVisitor` Hierarchie ein. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + + // Weitere Eigenschaften und Methoden... + + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + + // Weitere Eigenschaften und Methoden... + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Schließlich die Visitors im Einsatz. + +```java +public static void main(String[] args) { + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + + var zoom = new Zoom(); + var hayes = new Hayes(); + + hayes.accept(conDos); // Hayes modem with Dos configurator + zoom.accept(conDos); // Zoom modem with Dos configurator + hayes.accept(conUnix); // Hayes modem with Unix configurator + zoom.accept(conUnix); // Zoom modem with Unix configurator +} +``` + +Programausgabe: + +``` +09:15:11.125 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Hayes modem used with Dos configurator. +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Zoom modem used with Dos configurator. +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.Hayes -- Only HayesVisitor is allowed to visit Hayes modem +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor -- Zoom modem used with Unix configurator. +``` + +## Verwendung + +* Wenn Sie zu einer bestehenden Hierarchie eine neue Funktion hinzufügen müssen, ohne die Hierarchie zu verändern. +* Wenn es Funktionen gibt, die zwar auf einer Hierarchie arbeiten, aber nicht selbst dazu gehören (Wie die Configure-Funktionen im obigen Beispiel). +* Wenn abhängig vom Objekttyp sehr unterschiedliche Funktionen auszuführen sind. +* Wenn die zu besuchende Klassenhierarchie häufig um neue Kindklassen erweitert wird. +* When the visited class hierarchy will be frequently extended with new derivatives of the Element class. +* Wenn es sehr aufwendig ist, die neuen Kindklassen zu kompilieren, zu verlinken, zu testen oder zu verteilen. + +## Tutorials + +* [The Acyclic Visitor Pattern (Code Crafter)](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Vor- und Nachteile + +Vorteile: + +* Erweiterbarkeit: Neue Funktionen können leicht hinzugefügt werden, ohne die Objektstruktur zu verändern. +* Entkopplung: Kopplung zwischen Objekten und den auf ihnen stattfindenden Operationen wird reduziert. +* Keine Abhängigkeitszyklen: Abhängigkeiten sind azyklisch, Wartbarkeit verbessert sich, Komplexität wird reduziert. + +Nachteile: + +* Komplexität: Viele erforderliche Visitor-Interfaces können die Komplexität erhöhen. +* Wartbarkeit: Änderungen an der Objekthierarchie erfordern Updates aller Visitoren. + +## Verwandte Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): +Wird oft zusammen mit Acyclic Visitor verwendet, um einzelne Objekte und Zusammensetzungen aus ihnen einheitlich zu behandeln. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): +Can als Ergänzung eingesetzt werden, um Objekten Verantwortlichkeiten dynamisch zuzuweisen. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): Acyclic Visitor ist eine Variante des Visitor Patterns, die zyklische Abhängigkeiten vermeidet. + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML](https://amzn.to/4bOtzwF) +* [Acyclic Visitor (Robert C. Martin)](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor (WikiWikiWeb)](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/de/adapter/README.md b/localization/de/adapter/README.md new file mode 100644 index 000000000000..301e7a881508 --- /dev/null +++ b/localization/de/adapter/README.md @@ -0,0 +1,168 @@ +--- +shortTitle: Adapter +category: Structural +language: de +tag: + - Compatibility + - Decoupling + - Gang of Four + - Interface + - Object composition + - Wrapping +--- + +## Alternativbezeichnung + +* Wrapper + +## Zweck + +Das Adapter-Pattern konvertiert die Schnittstelle einer Klasse in eine andere Schnittstelle, die zu den Bedürfnissen der Anwender passt, und sorgt so für Kompatibilität. + +## Detaillierte Erklärung +Vergleich mit der analogen Welt + +> Stellen Sie sich vor, Sie haben einige Bilder auf Ihrer Speicherkarte und wollen diese auf +> Ihren Computer übertragen. Dafür brauchen Sie einen Kartenleser, der mit den Anschlüssen des Rechners +> kompatibel ist, sodass dieser auf die Daten auf der Karten zugreifen kann. Dieser Kartenleser +> ist ein Beispiel für einen Adapter. +> Ein anderes Beispiel sind die Adapter, mit denen man deutsche Netzstecker in ausländischen +> Steckdosen verwenden kann, in die sie sonst nicht passen würden. Auch ein Übersetzer, der die +> Worte eines Sprechers in die Sprache des ausländischen Publikums übersetzt, erfüllt die Funktion eines Adapters. + +In einfachen Worten + +> Das Adapter-Pattern verpackt ein normalerweise inkompatibles Objekt so, dass es mit einer +> anderen Klasse kompatibel wird. + +Wikipedia sagt + +> Das Adapter-Pattern in der Softwareentwicklung ist ein Entwurfsmuster, +> das die Schnittstelle einer bestehenden Klasse im Rahmen einer neuen Schnittstelle nutzbar macht. +> Es wird oft verwendet, damit Klassen zusammenarbeiten können, ohne ihren Quellcode zu verändern. + +Ablaufdiagramm + +![Adapter sequence diagram](/adapter/etc/adapter-sequence-diagram.png "Adapter sequence diagram") + +## Programmbeispiel + +Betrachten wir einen Möchtegern-Kapität, der zwar rudern kann, aber noch nie gesegelt ist. + +Wir beginnen mit dem Interface `RowingBoat` und der Klasse `FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +Der Kapität erwartet, dass sich ein Schiff mit der `row`-Methode von `RowingBoat` steuern lässt. + +```java +public class Captain { + + private final RowingBoat rowingBoat; + + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Nun kommen Piraten und unser Kapitän muss fliehen, hat aber nur ein Fischerboot zur Verfügung. +Wir brauchen einen Adapter, mit dem er auch dieses Boot durch Rudern steuern kann. + +```java +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +Nun segelt das `FishingBoat`, indem der Kapitän rudert, und er kann fliehen. + +```java + public static void main(final String[] args) { + // The captain can only operate rowing boats but with adapter he is able to + // use fishing boats as well + var captain = new Captain(new FishingBoatAdapter()); + captain.row(); +} +``` + +Programmausgabe: + +``` +10:25:08.074 [main] INFO com.iluwatar.adapter.FishingBoat -- The fishing boat is sailing +``` + +## Verwendung +Das Adapter-Pattern ist geeignet für diese Fälle +* Sie wollen eine bestehende Klasse benutzen, deren Schnittstelle anders als benötigt ist. +* Sie wollen eine wiederverwendbare Klasse schreiben, die auch mit fremden Klassen zusammen + arbeiten kann, die nicht unbedingt kompatible Schnittstellen haben. +* Sie müssen verschiedene Tochterklassen verwenden, bei denen es zu aufwendig wäre, zu jeder einzelnen eine Subklasse mit angepasster Schnittstelle zu erstellen. + Ein Adapter kann die Schnittstelle der Elternklasse bedarfsgerecht anpassen. +* Die meisten Anwendungen, die Fremdbibliotheken verwenden, nutzen einen Adapter für die Fremdklassen, + um die eigenen Anwendung vom fremden zu entkoppeln. + +## Tutorials + +* [Using the Adapter Design Pattern in Java (Dzone)](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Adapter in Java (Refactoring Guru)](https://refactoring.guru/design-patterns/adapter/java/example) +* [The Adapter Pattern in Java (Baeldung)](https://www.baeldung.com/java-adapter-pattern) +* [Adapter Design Pattern (GeeksForGeeks)](https://www.geeksforgeeks.org/adapter-pattern/) + +## Vor- und Nachteile + +Die Vor- und Nachteile hängen davon ab, ob ein Klassen- oder ein Objektadapter implementiert wird. + +Ein Klassenadapter adaptiert durch Bindung an eine spezifische zu adaptierende Klasse. +Er kann das Verhalten der zu adaptierenden Klasse überschreiben, weil er +als deren Tochterklasse implementiert wird. +Das hat allerdings zur Folge, dass mit einer Klasse nicht auch all ihre Subklassen adaptiert werden können. +Bei diesem Adaptertyp wird lediglich ein neues Objekt eingeführt, ohne +dass mit einem extra Zeiger der Zugriff darauf ermöglicht werden muss. + +Ein Objektadapter hingegen kann mit verschiedenen zu adaptierenden Klassen arbeiten, auch mit +allen Subklassen. Er kann allen adaptierten Klassen zugleich Funktionalität hinzufügen. +Allerdings wird es damit schwerer, das Verhalten zu überschreiben, weil man dafür eine +Subklasse der adaptierten Klasse benötigt und der Adapter sich auf diese Subklasse statt +auf die ursprünglich adaptierte Klasse beziehen muss. + +## Reale Java-Anwendungen + +* `java.io.InputStreamReader` and `java.io.OutputStreamWriter` in der Java-IO-Bibliothek. +* GUI-Komponentenbibliotheken, die per Plugin oder Adapter zwischen verschiedenen Kompontentenschnittstellen konvertieren können. +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/localization/de/bridge/README.md b/localization/de/bridge/README.md new file mode 100644 index 000000000000..a7cbedf82e41 --- /dev/null +++ b/localization/de/bridge/README.md @@ -0,0 +1,282 @@ +--- +shortTitle: Bridge +category: Structural +language: de +tag: + - Abstraction + - Decoupling + - Extensibility + - Gang of Four + - Object composition +--- + +## Alternativbezeichnung + +* Handle/Body + +## Zweck + +Das Bridge-Pattern ist ein Entwurfsmuster, das eine Abstraktion von ihrer Implementation +entkoppelt, wodurch beide unabhängig voneinander variieren können. +Es ist wesentlich, um flexible und erweiterbare Softwaresysteme zu bauen. + +## Detaillierte Erklärung + +Reales Beispiel + +> In Java wird das Bridge-Pattern oft verwendet für GUI-Frameworks, Datenbanktreiber und Gerätetreiber. +> +> Denken Sie an eine Universalfernbedienung (Abstraktion), die verschiedene Geräte diverser Marken +> (Implementationen) schalten kann. Die Fernbedienung stellt eine einheitliche Schnittstelle bereit für +> Aktionen wie Ein- und Ausschalten, Programmwechsel und Lautstärkeregelung. Diese Aktionen sind +> bei jedem einzelnen Gerät unterschiedlich implementiert. Mit dem Bridge-Pattern werden diese +> spezifischen Implementationen von der Fernbedienungsschnittstelle entkoppelt, sodass alle Geräte bedient +> unabhängig von Marke und interner Funktionsweise bedient werden können. Diese Trennung erlaubt es, +> dass neue Geräte mit der gleichen Fernbedienung ohne Änderung an deren Schnittstelle gesteuert werden können, +> oder dass neue Fernbedienungen für den gleichen Gerätepool entwickelt werden können. + +In einfachen Worten + +> Beim Bridge-Pattern geht es um den Vorrang von Komposition vor Vererbung. +> Details der Implementation werden aus einer Hierarchie in ein anderes Objekt mit separater Hierarchie verschoben. + +Wikipedia sagt + +> Das Bridge-Pattern ist ein Entwurfsmuster der Softwareentwicklung mit dem Zweck, +> eine Abstraktion von ihrer Implementierung zu trennen, so dass beide unabhängig voneinander angepasst werden können. + +Ablaufdiagramm + +![Bridge sequence diagram](/bridge/etc/bridge-sequence-diagram.png) + +## Programmbeispiel + +Stellen Sie sich vor, eine Waffe kann diverse Verzauberungen haben und sie müssen +verschiedene Waffen mit verschiedenen Verzauberungen kombinieren. Wie realisieren Sie das? +Imagine you have a weapon that can have various enchantments, and you need to combine +different weapons with different enchantments. How would you handle this? +Durch viele Versionen einer Waffe mit jeweils einem anderen Zauber, oder würden Sie separate +Verzauberungen definieren und diese nach Bedarf einer Waffe zuordnen? Das Bridge-Pattern macht letzteres möglich. + +Hier ist die `Weapon`-Hierarchie: + +```java +public interface Weapon { + void wield(); + + void swing(); + + void unwield(); + + Enchantment getEnchantment(); +} + +public class Sword implements Weapon { + + private final Enchantment enchantment; + + public Sword(Enchantment enchantment) { + this.enchantment = enchantment; + } + + @Override + public void wield() { + LOGGER.info("The sword is wielded."); + enchantment.onActivate(); + } + + @Override + public void swing() { + LOGGER.info("The sword is swung."); + enchantment.apply(); + } + + @Override + public void unwield() { + LOGGER.info("The sword is unwielded."); + enchantment.onDeactivate(); + } + + @Override + public Enchantment getEnchantment() { + return enchantment; + } +} + +public class Hammer implements Weapon { + + private final Enchantment enchantment; + + public Hammer(Enchantment enchantment) { + this.enchantment = enchantment; + } + + @Override + public void wield() { + LOGGER.info("The hammer is wielded."); + enchantment.onActivate(); + } + + @Override + public void swing() { + LOGGER.info("The hammer is swung."); + enchantment.apply(); + } + + @Override + public void unwield() { + LOGGER.info("The hammer is unwielded."); + enchantment.onDeactivate(); + } + + @Override + public Enchantment getEnchantment() { + return enchantment; + } +} +``` + +Hier die separate `Enchantment`-Hierarchie: + +```java +public interface Enchantment { + void onActivate(); + + void apply(); + + void onDeactivate(); +} + +public class FlyingEnchantment implements Enchantment { + + @Override + public void onActivate() { + LOGGER.info("The item begins to glow faintly."); + } + + @Override + public void apply() { + LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand."); + } + + @Override + public void onDeactivate() { + LOGGER.info("The item's glow fades."); + } +} + +public class SoulEatingEnchantment implements Enchantment { + + @Override + public void onActivate() { + LOGGER.info("The item spreads bloodlust."); + } + + @Override + public void apply() { + LOGGER.info("The item eats the soul of enemies."); + } + + @Override + public void onDeactivate() { + LOGGER.info("Bloodlust slowly disappears."); + } +} +``` + +Hier werden beide Hierarchien aktiv: + +```java +public static void main(String[] args) { + LOGGER.info("The knight receives an enchanted sword."); + var enchantedSword = new Sword(new SoulEatingEnchantment()); + enchantedSword.wield(); + enchantedSword.swing(); + enchantedSword.unwield(); + + LOGGER.info("The valkyrie receives an enchanted hammer."); + var hammer = new Hammer(new FlyingEnchantment()); + hammer.wield(); + hammer.swing(); + hammer.unwield(); +} +``` + +Dies ist die Ausgabe: + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +The item flies and strikes the enemies finally returning to owner's hand. +The hammer is unwielded. +The item's glow fades. +``` + +## Verwendung + +Das Bridge-Pattern kommt in diesen Fällen in Betracht: + +* Eine dauerhafte Bindung zwischen Abstration und Implementierung soll vermieden werden, etwa + wenn die Implementation zur Laufzeit ausgewählt oder ausgewechselt werden muss. +* Sowohl Abstraktion als auch Implementationen sollen durch Vererbung erweitert werden können, + um unabhängige Erweiterungen jeder Komponente zu ermöglichen. +* Änderungen an der Implementation einer Abstraktion sollen die Verwender nicht beeinflussen, d.h. sie sollen nicht neu kompiliert werden müssen. +* Die Hierarchie enthält eine große Anzahl Klassen, was dafür spricht, Objekte in zwei Teile zu spalten. + Dieses Konzept wird von Rumbaugh als "verschachtelte Generalisierungen" bezeichnet. +* Sie wollen eine Implementation mit mehreren Objekten teilen, eventuell unter Verwendung von + Referenzzählern, dabei aber dieses Detail aber vor den Verwendern verstecken. Beispiel dafür + ist die String-Klasse von Coplien, wo mehrere Objekte die gleiche Stringdarstellung haben. + +## Tutorials + +* [Bridge Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/bridge-design-pattern-java) + +## Reale Anwendungen in Java + +* In GUI-Frameworks ist das Fenster die Abstraktion, die Implementation die Fensterkonstruktion des Betriebssystem. +* Bei Datenbanktreibern ist die Abstraktion eine generische Datenbankschnittstelle, die Implementationen sind datenbankspezifische Treiber. +* Bei Gerätetreibern ist der geräteunabhängige Code die Abstraktion, die Implementation betrifft das einzelne Gerät. + +## Vor- und Nachteile + +Vorteile: + +* Entkopplung von Schnittstelle und Implementation: Durch Trennung von Operationen der höheren (Schnittstelle) und der niedrigeren Ebene (Implementation) verbessert sich die Modularität. +* Bessere Erweiterbarkeit: Abstraktions- und Implementationshierarchien können unabhängig voneinander erweitert werden. +* Versteckte Implementationsdetails: Verwender sehen nur die Schnittstelle, nicht ihre Implementation. + +Nachteile: + +* Höhere Komplexität: Systemarchitektur und Code können sich verkomplizieren, vor allem wenn man nicht mit dem Pattern vertraut ist. +* Laufzeitkosten: Die zusätzliche Abstraktionsschicht kann zu Performanceeinbußen führen, auch wenn das in der Praxis oft vernachlässigbar ist. + + +## Verwandte Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): + Das Abstract-Factory-Pattern kann zusammen mit dem Bridge-Pattern verwendet werden, um Plattformen zu schaffen, die unabhängig von den konkreten Klassen zur Objekterzeugung sind. +* [Adapter](https://java-design-patterns.com/patterns/adapter/): + Das Adapter-Pattern stellt eine neue Schnittstelle für ein Objekt zur Verfügung, + das Bridge-Pattern trennt die Schnittstelle des Objekts von der Implementation. +* [Composite](https://java-design-patterns.com/patterns/composite/): + Das Bridge-Pattern wird häufig mit dem Composite-Pattern verwendet, um die Implementationsdetails + einer Komponente zu modellieren. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): + Beide Patterns verwenden Komposition: Strategy für Veränderungen am Verhalten einer Klasse, Bridge für die Trennung von Abstraktion und Implementation. + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3TEnhtl) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/localization/de/builder/README.md b/localization/de/builder/README.md new file mode 100644 index 000000000000..450132d23928 --- /dev/null +++ b/localization/de/builder/README.md @@ -0,0 +1,221 @@ +--- +shortTitle: Builder +language: de +tag: + - Gang of Four + - Instantiation + - Object composition +--- + +## Zweck + +Das Builder-Pattern ist ein fundamentales Erzeugungsmuster, mit dem komplexe Objekte schrittweise konstruiert werden. +Es trennt die Konstruktion eines komplexen Objekts von seiner Darstellung, sodass im gleichen +Konstruktionsprozess verschiedene Ausprägungen erzeugt werden können. + +## Detaillierte Erklärung + +Beispiel aus der realen Welt + +> Das Builder-Pattern ist besonders nützlich, wenn zur Erzeugung eines Objekts viele Parameter benötigt werden. +> +> Stellen Sie sich vor, Sie bestellen ein individuell zusammengestelltes Sandwich. +> Das Builder-Pattern stellt dafür einen SandwichBuilder bereit, mit dem Sie jede einzelne +> Komponente auswählen können (Brotart, Fleisch, Käse, Gemüse, Würzung). Sie müssen nicht +> wissen, wie man so ein Sandwich tatsächlich zusammenbaut. Es genügt, dass Sie Schritt für +> Schritt alle gewünschten Komponenten angeben, um genau das gewünschte Sandwich zu erhalten. +> Diese Trennung der Konstruktion vom fertigen Produkt stellt sicher, dass viele verschiedene +> Sandwichtypen aus den Komponenten konstruiert werden können. + +In einfachen Worten + +> Man kann verschiedene Formen eines Objekts erzeugen, ohne eine Vielzahl von Konstruktoren +> oder einen Konstruktor mit vielen Parametern zu benötigen. Nützlich, wenn ein Objekt in +> mehreren Geschmacksrichtungen auftauchen kann, oder wenn die Erzeugung des Objekts aus +> vielen Schritten besteht. + +Wikipedia sagt + +> Das Builder-Pattern ist ein Entwurfsmuster zur Objekterzeugung, das eine Lösung für +> das Telescoping-Constructor-Antipattern bieten will. + +Was hat es mit diesem Antipattern auf sich? +Irgendwann treffen wir alle auf solche Konstruktoren: + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon){ + // Wertzuweisungen +} +``` +Sie sehen, die Zahl der Parameter im Konstruktor kann schnell unübersichtlich werden, so dass +schwer zu erkennen ist, welche benötigt werden und in welcher Reihenfolge sie stehen müssen. +Dieses Problem verstärkt sich, wenn später noch weitere Optionen hinzugefügt werden. +Dies wird als Telescoping-Constructor-Antipattern bezeichnet. + +Ablaufdiagramm + +![Builder sequence diagram](/builder/etc/builder-sequence-diagram.png) + +## Programmbeispiel + +In diesem Beispiel konstruieren wir verschiedene Typen von `Hero`-Objekten mit wechselnden Attributen. + +Stellen Sie sich einen Charakter-Generator in einem Rollenspiel vor. Die einfachste Option ist es, +den Charakter komplett vom Computer erstellen zu lassen. Manchmal will der Spieler aber selbst bestimmte +Eigenschaften des Charakters auswählen, etwa Beruf, Geschlecht, Haarfarbe etc. Dies ist ein schrittweiser Prozess, der erst abgeschlossen ist, wenn alle gewünschten Eigenschaften +festgelegt wurden. + +Mit dem Builder-Pattern gibt es einen besseren Ansatz dafür. +Betrachten wir zunächst den `Hero`, den wir erzeugen wollen: + +```java +public final class Hero { + private final Profession profession; + private final String name; + private final HairType hairType; + private final HairColor hairColor; + private final Armor armor; + private final Weapon weapon; + + private Hero(Builder builder) { + this.profession = builder.profession; + this.name = builder.name; + this.hairColor = builder.hairColor; + this.hairType = builder.hairType; + this.weapon = builder.weapon; + this.armor = builder.armor; + } +} +``` + +Dazu gibt es den `Builder`: + +```java + public static class Builder { + private final Profession profession; + private final String name; + private HairType hairType; + private HairColor hairColor; + private Armor armor; + private Weapon weapon; + + public Builder(Profession profession, String name) { + if (profession == null || name == null) { + throw new IllegalArgumentException("profession and name can not be null"); + } + this.profession = profession; + this.name = name; + } + + public Builder withHairType(HairType hairType) { + this.hairType = hairType; + return this; + } + + public Builder withHairColor(HairColor hairColor) { + this.hairColor = hairColor; + return this; + } + + public Builder withArmor(Armor armor) { + this.armor = armor; + return this; + } + + public Builder withWeapon(Weapon weapon) { + this.weapon = weapon; + return this; + } + + public Hero build() { + return new Hero(this); + } +} +``` + +Verwendet wird das Ganze dann so: + +```java + public static void main(String[] args) { + + var mage = new Hero.Builder(Profession.MAGE, "Riobard") + .withHairColor(HairColor.BLACK) + .withWeapon(Weapon.DAGGER) + .build(); + LOGGER.info(mage.toString()); + + var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill") + .withHairColor(HairColor.BLOND) + .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) + .build(); + LOGGER.info(warrior.toString()); + + var thief = new Hero.Builder(Profession.THIEF, "Desmond") + .withHairType(HairType.BALD) + .withWeapon(Weapon.BOW) + .build(); + LOGGER.info(thief.toString()); +} +``` + +Programmausgabe: + +``` +16:28:06.058 [main] INFO com.iluwatar.builder.App -- This is a mage named Riobard with black hair and wielding a dagger. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a warrior named Amberjill with blond long curly hair wearing chain mail and wielding a sword. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow. +``` + +## Verwendung + +* Das Builder-Pattern ist ideal für Anwendungen, die komplexe Konstruktoren benötigen. +* Der Algorithmus zur Erzeugung eines komplexen Objekts sollte unabhängig davon sein, aus + welchen Elementen es besteht und wie diese zusammengesetzt werden. +* Der Konstruktionsprozess muss verschiedene Ausprägungen des konstruierten Objekts erlauben. +* Besonders nützlich, wenn viele Schritte zur Erzeugung benötigt werden, die in einer bestimmten + Reihenfolge ausgeführt werden müssen. + +## Tutorials + +* [Builder Design Pattern in Java (DigitalOcean)](https://www.journaldev.com/1425/builder-design-pattern-in-java) +* [Builder (Refactoring Guru)](https://refactoring.guru/design-patterns/builder) +* [Exploring Joshua Bloch’s Builder design pattern in Java (Java Magazine)](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) + +## Reale Anwendungen in Java + +* StringBuilder und StringBuffer konstruieren veränderbare String-Objekte +* Java.nio.ByteBuffer und ähnliche Klassen wie FloatBuffer, IntBuffer usw. +* javax.swing.GroupLayout.Group#addComponent() +* Verschiedene GUI-Builder in IDEs, die GUI-Komponenten bauen. +* Alle Implementationen von [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel Builder](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Vor- und Nachteile + +Vorteile: + +* Bessere Kontrolle des Konstruktionsprozesses als bei anderen Erzeugungsmustern. +* Ermöglicht schrittweise Konstruktion, Verschiebung von Schritten und rekursiven Ablauf der Schritte. +* Kann Objekte konstruieren, die eine komplexe Zusammenstellung von Teilobjekten erfordern. + Dabei wird das Gesamtobjekt von den Teilen und dem Prozess des Zusammenfügens getrennt. +* Prinzip der eindeutigen Verantwortlichkeit: Komplexer Konstruktionscode kann von der Geschäftslogik getrennt werden. + +Nachteile: + +* Der Code kann insgesamt komplexer werden, weil zusätzliche Klassen benötigt werden. +* Durch die Builder-Objekte kann sich der Speicherverbrauch erhöhen. + +## Verwandte Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Kann gemeinsam mit Builder verwendet werden, um Teile eines komplexen Objekts zu generieren. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Builder bauen oft Prototypen nach. +* [Step Builder](https://java-design-patterns.com/patterns/step-builder/): Eine Variante des Builder-Patterns mit Schritt-für-Schritt-Ansatz. + Gute Wahl für Objekte mit einer Vielzahl optionaler Parameter. + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/localization/de/chain-of-responsibility/README.md b/localization/de/chain-of-responsibility/README.md new file mode 100644 index 000000000000..7f4e0f839705 --- /dev/null +++ b/localization/de/chain-of-responsibility/README.md @@ -0,0 +1,221 @@ +--- +shortTitle: Chain of Responsibility +category: Behavioral +language: de +tag: + - Decoupling + - Event-driven + - Gang of Four + - Messaging +--- + +## Alternativbezeichnungen + +* Chain of Command +* Chain of Objects +* Responsibility Chain +* deutsch: Zuständigkeitskette + +## Zweck + +Chain of Responsibility ist ein Verhaltensmuster, +das den Sender einer Anfrage von deren Empfängern entkoppelt, indem mehrere Objekte die +Gelegenheit zum Bearbeiten der Anfrage erhalten. Die empfangenden Objekte sind miteinander +verkettet und die Anfrage wird so lange entlang der Kette weitergereicht, bis ein Objekt +sie bearbeitet. + +## Detaillierte Erklärung + +Vergleichsbeispiel + +> Die Chain of Responsibility gleicht der Arbeit in einem Call-Center für technischen +Kundendienst. Jedes Support-Level entspricht einem Handler in der Kette. +Wenn ein Kunde wegen eines Problems anruft, landet der Anruf bei einem Mitarbeiter des ersten +Levels. Einfache Probleme kann dieser direkt lösen. Wenn der Fall schwieriger ist, leitet +er den Anruf an einen Second-Level-Kollegen weiter. Dieser Prozess läuft über verschiedene +Stufen so lange weiter, bis ein Fachmann gefunden wurde, der das Problem löst. +Indem der Anruf entlang der Kette bis zur passenden Stelle weitergereicht wird, +erreicht man eine Entkopplung zwischen der Anfrage (Anruf) und ihrem Empfänger (jeweiliger +Mitarbeiter). + +In einfachen Worten + +> Das Pattern hilft beim Bau einer Kette von Objekten. Eine Anfrage kommt auf einer Seite herein +und wird von einem Objekt zum nächsten weitergereicht, bis der passende Handler für sie gefunden ist. + +Wikipedia sagt + +> Das Design-Pattern Chain of Responsibility besteht aus einer Quelle für Befehlsobjekt +und einer Reihe von Bearbeiterobjekten. Jedes Bearbeiterobjekt enthält eine Entscheidungslogik, welche +Art von Befehlsobjekten es selbst bearbeiten kann. Die übrigen leitet es an das nächste +Objekt in der Kette weiter. + +Ablaufdiagramm + +![Chain of Responsibility flowchart](/chain-of-responsibility/etc/chain-of-responsibility-flowchart.png) + +## Programmbeispiel + +In diesem Java-Beispiel gibt der König der Orcs lautstarke Befehle an seine Armee, die von +einer Kette Untergebener ausgeführt werden. Am nächsten zum König steht sein General, +dann ein Offizier und schließlich ein einfacher Soldat. + +Zuerst definieren wir für die Befehle die Klasse `Request`. + +```java +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public void markHandled() { + this.handled = true; + } + + @Override + public String toString() { + return getRequestDescription(); + } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +Hier sehen wir die Hierarchie der `RequestHandler`. + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// OrcOfficer und OrcSoldier sind ähnlich definiert + +``` + +Der `OrcKing` gibt den Befehl und baut die Kette (geordnet nach Priorität) auf: + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +Hier erhält die Kette verschiedene Befehle: + +```java + public static void main(String[] args) { + + var king = new OrcKing(); + king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); + king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); + king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); +} +``` + +Ausgabe: + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## Verwendung + +* Wenn mehrere Objekte eine Anfrage bearbeiten können und der zuständige Verarbeiter nicht +vorab bekannt ist. Der Verarbeiter sollte automatisch ermittelt werden. +* Wenn eine Anfrage an eines von mehreren Objekten gesendet wird, ohne den Empfänger explizit festzulegen. +* Bei dynamischer Zusammenstellung der Menge möglicher Bearbeiter. + +## Reale Anwendungen in Java + +* Event-Bubbling in GUI-Frameworks, wo ein Event in verschiedenen Stufen der Komponentenhierachie bearbeitet werden kann. +* Middleware-Frameworks, bei denen Anfragen eine Kette möglicher Verarbeiter durchlaufen. +* Logging-Frameworks, bei denen Nachrichten eine Reihe von Loggern durchlaufen, von denen sie verschieden behandelt werden können. +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## Vor- und Nachteile + +Vorteile: + +* Weniger Kopplung. Der Sender einer Anfrage muss nicht wissen, von wem diese bearbeitet wird. +* Flexibilität bei der Zuweisung von Verantwortlichkeiten durch Umbildung der Kette. +* Für den Fall, dass kein Kettenglied die Anfrage bearbeiten kann, kann ein Default-Verarbeiter festgelegt werden. + +Nachteile: + +* Bei langen und komplexen Ketten kann der Ablauf schwer zu durchschauen und zu debuggen sein. +* Eine Anfrage kann unbearbeitet bleiben, wenn ein passender Bearbeiter fehlt. +* Der (möglicherweise auch vergebliche) Durchlauf durch mehrere Verarbeiter kann die Peformance beeinträchtigen. + +## Verwandte Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): Kann verwendet werden zur Kapselung der Anfrage in ein Objekt, das durch die Kette läuft. +* [Composite](https://java-design-patterns.com/patterns/composite/): Wird oft gemeinsam mit Chain of Responsibility verwendet. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Decorators können ähnlich wie Verantwortlichkeiten verkettet werden. + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PAJUg5) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) +* [Pattern languages of program design 3](https://amzn.to/4a4NxTH) diff --git a/localization/de/dependency-injection/README.md b/localization/de/dependency-injection/README.md new file mode 100644 index 000000000000..3717b59fbbb9 --- /dev/null +++ b/localization/de/dependency-injection/README.md @@ -0,0 +1,169 @@ +--- +shortTitle: Dependency Injection +category: Creational +language: de +tag: + - Decoupling + - Dependency management + - Inversion of control +--- + +## Alternativbezeichnungen + +* Inversion of Control (IoC) +* Dependency Inversion + +## Zweck + +Die Erzeugung der in einem Objekt benötigten Abhängigkeiten soll von der Verwendung entkoppelt werden. So wird der Code flexibler und testbarer. + +## Detaillierte Erklärung + +Beispiel aus dem echten Leben + +> Stellen Sie sich edles Restaurant vor, in dem der Koch diverse Zutaten für das Essen braucht. +> Er geht nicht für jede Zutat einzeln zu deren Hersteller, sondern bedient sich eines zuverlässigen +> Lieferanten, der ihm jeden Tag die Produkte frisch vom jeweiligen Hersteller besorgt. +> So kann er sich aufs Kochen konzentrieren und muss sich nicht mehr um den Einkauf kümmern. +> +> Im Dependency-Injection-Pattern fungiert der Lieferant als "Injektor", der die nötigen +> Abhängigkeiten (Zutaten) dem "Objekt" Koch zur Verfügung stellt. Der Koch kann die Zutaten +> verwenden, ohne deren Ursprung kennen zu müssen. Die Beschaffung und Verwendung der Abhängigkeiten +> sind also klar getrennt. Mit diesem Ansatz werden Effizienz, Flexibilität und Wartungsfreundlichkeit in der Küche verbessert, +> ebenso wie in einem Softwaresystem. + +In einfachen Worten + +> Dependency Injection trennt die Beschaffung der Abhängigkeiten vom eigenen Verhalten des Verwenders. + +Wikipedia sagt + +> In der Softwareentwicklung ist Dependency Injection eine Technik, mit der ein Objekt andere +> Objekte zugewiesen bekommt, die es benötigt. Diese anderen Objekte nennt man Abhängigkeiten (Dependencies). + +Ablaufdiagramm + +![Dependency Injection sequence diagram](/dependency-injection/etc/dependency-injection-sequence-diagram.png) + +## Programmbeispiel + +Der alte Hexenmeister möchte hin und wieder seine Pfeife stopfen und Tabak rauchen. +Dabei will er aber nicht von einer einzigen Tabakmarke abhängig sein, sondern die Marke wechseln können. + +Definieren wir also zunächst die Schnittstelle `Tobacco` und konkrete Klassen für die Marken. + +```java + +public abstract class Tobacco { + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +Als nächstes die `Wizard`-Klassenhierarchie. + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +Schließlich sehen wir, wie leicht es ist, dem Hexenmeister jede beliebige Tabakmarke zu geben. + +```java +public static void main(String[] args) { + var simpleWizard = new SimpleWizard(); + simpleWizard.smoke(); + + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); + + var advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(new SecondBreakfastTobacco()); + advancedSorceress.smoke(); + + var injector = Guice.createInjector(new TobaccoModule()); + var guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); +} +``` + +Prorammausgabe: + +``` +11:54:05.205 [main] INFO com.iluwatar.dependency.injection.Tobacco -- SimpleWizard smoking OldTobyTobacco +11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedWizard smoking SecondBreakfastTobacco +11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedSorceress smoking SecondBreakfastTobacco +11:54:05.308 [main] INFO com.iluwatar.dependency.injection.Tobacco -- GuiceWizard smoking RivendellTobacco +``` + +## Verwendung + +* Wenn die Kopplung zwischen den Klassen reduziert und die Modularität der Anwendung erhöht werden soll +* In Szenarien, wo die Objekterzeugung komplex ist oder sonst von der Verwendung der Klasse getrennt werden soll. +* In Anwendungen, die einfacheres Texten durch Mocks oder Stubs benötigen. +* In Frameworks oder Bibliotheken, die den Lebenszyklus von Objekten managen, wie Spring oder Jakarta EE (früher Java EE). + +## Reale Anwendungen in Java + +* Frameworks wie Spring, Jakarta EE und Google Guice verwenden Dependency Injection (DI) + ausgiebig, um Lebenszyklen und Abhängigkeiten zu verwalten. +* Desktop- und Webanwendungen, die eine flexible Architektur mit leicht austauschbaren Komponenten benötigen. + +## Vor- und Nachteile + +Vorteile: + +* Verbessert die Modularität und Trennung von Zuständigkeiten. +* Vereinfacht Unit-Tests durch leichtes Mocken von Abhängigkeiten. +* Verbessert Flexibilität und Wartbarkeit durch Förderung von loser Kopplung. + +Nachteile: + +* Kann Konfiguration verkomplizieren, vor allem in großen Projekten. +* Entwickler, die mit dem Konzept nicht vertraut sind, müssen es erst erlernen. +* Erfordert sorgfältiges Management von Lebenzyklen und Gültigkeitsbereich der Objekte. + +## Verwandte Patterns + +* [Factory-Methoden](https://java-design-patterns.com/patterns/factory-method/) und [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Werden zur Erzeugung von Instanzen genutzt, die per DI injiziert werden. +* [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Eine Alternative zu DI, um Dienste oder Komponenten zu finden, entkoppelt den Prozess aber nicht so effektiv. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Häufig Ergänzung zu DI, um eine einzige Instanz zu liefern. eines Service für die gesamte Anwendung zu liefern. + +## Quellen + +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) +* [Dependency Injection: Design patterns using Spring and Guice](https://amzn.to/4aMyHkI) +* [Dependency Injection Principles, Practices, and Patterns](https://amzn.to/4aupmxe) +* [Google Guice: Agile Lightweight Dependency Injection Framework](https://amzn.to/4bTDbX0) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://amzn.to/4ayCtxp) +* [Java Design Pattern Essentials](https://amzn.to/3xtPPxa) +* [Pro Java EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework](https://amzn.to/3J6Teoh) +* [Spring in Action](https://amzn.to/4asnpSG) diff --git a/localization/de/fluent-interface/README.md b/localization/de/fluent-interface/README.md new file mode 100644 index 000000000000..0fe0ceda1355 --- /dev/null +++ b/localization/de/fluent-interface/README.md @@ -0,0 +1,216 @@ +--- +shortTitle: Fluent Interface +category: Behavioral +language: de +tag: + - API design + - Code simplification + - Decoupling + - Object composition + - Reactive +--- + +## Alternativbezeichnungen + +* Fluent API +* Method Chaining + +## Zweck + +Primäres Ziel des Fluent-Interface-Pattern ist es, eine gut lesbare sprechende API zur +Verfügung zu stellen, indem Methodenaufrufe einfach verkettet werden können (Method Chaining). +Dieser Ansatz ist ideal, um komplexe Objekte schrittweise zu bauen und generell ein angenehmeres +Programmiererlebnis zu erreichen. + +## Detaillierte Erklärung + +Vergleichsbeispiel + +> Die Bestellung eines frei konfigurierbaren Kaffees in einer Kaffeebar funktioniert ähnlich +> wie das Fluent-Interface-Pattern. +> Dabei teilen Sie dem Barista nicht all ihre Wünsche auf einmal mit, sondern nennen schrittweise +> eine Auswahl nach der anderen, in einem natürlichen Fluss. Sie sagen beispielsweise "Ich möchte +> einen großen großen Kaffee, mit zwei Espresso-Shots, ohne Zucker, plus Mandelmilch". +> Diese Aneinanderhängung von Wünschen entspricht dem Verketten von Methodenaufrufen +> beim Fluent-Interface-Pattern, wodurch der Code zu Objektkonfiguration intuitiv lesbar wird. +> So wie eine Kaffeekomponente nach der anderen ausgewählt wird, wird im Code eine Methode nach der anderen +> ausgeführt. + +In einfachen Worten: + +> Fluent Interface bietet eine sprechende, leicht lesbare Schnittstelle zum Code. + +Wikipedia sagt: + +> In der Softwareentwicklung ist Fluent Interface eine objektorientierte API, deren Design auf +> ausgiebiger Verkettung von Methoden beruht. Ziel ist verbesserte Lesbarkeit des Codes +> durch eine domänenspezifische Sprache (DSL, domain specific language). + +Ablaufdiagramm + +![Fluent Interface sequence diagram](/fluent-interface/etc/fluent-interface-sequence-diagram.png) + +## Programmbeispiel + +Wir wollen Zahlen aus einer Liste nach verschiedenen Kriterien auswählen. Dabei können +wir die Lesbarkeit des Codes gut mit dem Fluent-Interface-Pattern verbessern. + +Der Beispielcode enthält zwei Implementationen eines `FluentIterable`-Interfaces. + +```java +public interface FluentIterable extends Iterable { + + FluentIterable filter(Predicate predicate); + + Optional first(); + + FluentIterable first(int count); + + Optional last(); + + FluentIterable last(int count); + + FluentIterable map(Function function); + + List asList(); + + static List copyToList(Iterable iterable) { + var copy = new ArrayList(); + iterable.forEach(copy::add); + return copy; + } +} +``` + +`SimpleFluentIterable` betreibt eifrige Auswertung und wäre für eine reale Anwendung zu rechenintensiv. + +```java +public class SimpleFluentIterable implements FluentIterable { + // ... +} +``` +`LazyFluentIterable` wertet erst bei Terminierung der Kette aus. + +```java +public class LazyFluentIterable implements FluentIterable { + // ... +} +``` + +Ihre Verwendung zeigen wir mit einer simplen Zahlenliste, die gefiltert, transformiert +und zu einer neuen Liste zusammengestellt wird. Das Ergebnis wird anschließend ausgegeben. + +```java +public static void main(String[] args) { + + var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); + + prettyPrint("The initial list contains: ", integerList); + + var firstThreeNegatives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .first(3) + .asList(); + prettyPrint("The first three negative values are: ", firstThreeNegatives); + + + var lastTwoPositives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(positives()) + .last(2) + .asList(); + prettyPrint("The last two positive values are: ", lastTwoPositives); + + SimpleFluentIterable + .fromCopyOf(integerList) + .filter(number -> number % 2 == 0) + .first() + .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); + + + var transformedList = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .map(transformToString()) + .asList(); + prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); + + + var lastTwoOfFirstFourStringMapped = LazyFluentIterable + .from(integerList) + .filter(positives()) + .first(4) + .last(2) + .map(number -> "String[" + number + "]") + .asList(); + prettyPrint("The lazy list contains the last two of the first four positive numbers " + + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); + + LazyFluentIterable + .from(integerList) + .filter(negatives()) + .first(2) + .last() + .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number)); +} +``` + +Programmausgabe: + +``` +08:50:08.260 [main] INFO com.iluwatar.fluentinterface.app.App -- The initial list contains: 1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68. +08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The first three negative values are: -61, -22, -87. +08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The last two positive values are: 23, 2. +08:50:08.266 [main] INFO com.iluwatar.fluentinterface.app.App -- The first even number is: 14 +08:50:08.267 [main] INFO com.iluwatar.fluentinterface.app.App -- A string-mapped list of negative numbers contains: String[-61], String[-22], String[-87], String[-82], String[-98], String[-68]. +08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- The lazy list contains the last two of the first four positive numbers mapped to Strings: String[18], String[6]. +08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- Last amongst first two negatives: -22 +``` + +## Verwendung + +* Zum Entwurf vielgenutzter APIs, bei denen die Lesbarkeit des sie verwendenden Codes besonders wichtig ist. +* Zur schrittweisen Konstruktion komplexer Objekte mit intuitivem und weniger fehleranfälligem Code. +* Zur Verbesserung der Übersichtlichkeit des Codes und Reduktion von Boilerplate-Code, + speziell bei Konfigurationen und Objektkonstruktion. + +## Tutorials + +* [An Approach to Internal Domain-Specific Languages in Java (InfoQ)](http://www.infoq.com/articles/internal-dsls-java) + +## Reale Anwendungen in Java + +* [Java 8 Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html) +* [Google Guava FluentIterable](https://github.com/google/guava/wiki/FunctionalExplained) +* [JOOQ](http://www.jooq.org/doc/3.0/manual/getting-started/use-cases/jooq-as-a-standalone-sql-builder/) +* [Mockito](http://mockito.org/) +* [Java Hamcrest](http://code.google.com/p/hamcrest/wiki/Tutorial) +* Builder in Bibliotheken wie Apache Camel für den Integrations-Workflow. + +## Vor- und Nachteile + +Vorteile: + +* Signifikant erhöhte Lesbarkeit und Wartbarkeit des Codes +* Unterstützt die Konstruktion unveränderlicher Objekte, weil die Methoden typischerweise neue Instanzen zurückgeben. +* Weniger Variablen nötig, da der Kontext durch die Aufrufkette klar wird. + +Nachteile: + +* Für Neulinge ist der Code weniger intuitiv. +* Verkettung von Methoden erschwert das Debuggen. +* Übermäßige Verwendung kann zu komplexem schwer wartbarem Code führen. + +## Verwandte Patterns + +* [Builder](https://java-design-patterns.com/patterns/builder/): Verwendet oft Fluent Interface zur schrittweisen Konstruktion. Bei Builder geht es um die Konstruktion komplexer Objekte, bei Fluent Interface um die Methodenverkettung. +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Fluent Interfaces können als spezielle Verwendung von Chain of Responsibility betrachtet werden, wo jede Methode in der Kette eine Teilaufgabe behandelt und ihr Ergebnis an die nächste Methode weiterreicht. + +## Quellen + +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3UrXkh2) +* [Domain Specific Languages](https://amzn.to/3R1UYDA) +* [Effective Java](https://amzn.to/4d4azvL) +* [Java Design Pattern Essentials](https://amzn.to/44bs6hG) +* [Fluent Interface (Martin Fowler)](http://www.martinfowler.com/bliki/FluentInterface.html) diff --git a/localization/de/singleton/README.md b/localization/de/singleton/README.md new file mode 100644 index 000000000000..6d27a16ee29d --- /dev/null +++ b/localization/de/singleton/README.md @@ -0,0 +1,114 @@ +--- +shortTitle: Singleton +category: Creational +language: de +tag: + - Gang of Four + - Instantiation + - Lazy initialization + - Resource management +--- + +## Alternativbezeichnung + +* Single Instance + +## Zweck + +Sicherstellen, dass es nur eine Instanz einer Klasse gibt, und einen globalen Zugriffspunkt auf diese Instanz bereitstellen. + +## Detaillierte Erklärung + +Analogie aus der Realität + +> Das Singleton-Pattern entspricht der Ausgabe von Pässen durch die Regierung. +> Jeder Bürger darf zu jeder Zeit nur einen Pass besitzen. Die Meldebehörde stellt sicher, +> dass niemandem ein zweiter Pass ausgestellt wird. +> Wenn ein Bürger ins Ausland reist, benötigt er seinen Pass, der als einzigartiger weltweit anerkannter Nachweis +> seiner Identität dient. + +In einfachen Worten + +> Es darf nur ein einziges Objekt dieser Klasse erzeugt werden. +> +Wikipedia sagt + +> In der Softwareentwicklung ist das Singleton ein Entwurfsmuster, das die Instanziierung einer +> Klasse auf ein einziges Objekt beschränkt. +> Dies ist sinnvoll, wenn genau ein Objekt benötigt wird, das Aktionen über das gesamte System +> hinweg koordiniert. + +Ablaufdiagramm + +![Singleton Pattern sequence diagram](/singleton/etc/singleton-sequence-diagram.png) + +## Programmbeispiel + +vgl. Joshua Bloch, Effective Java 2nd Edition, Seite 18 + +> Die beste Art der Implementation eines Singletons ist ein Enum mit nur einem Element. + +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +So wird es verwendet: + +```java + var enumIvoryTower1 = EnumIvoryTower.INSTANCE; + var enumIvoryTower2 = EnumIvoryTower.INSTANCE; + LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); + LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); +``` + +Ausgabe in der Konsole: + +``` +enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852 +enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852 +``` + +## Verwendung + +Ein Singleton sollte verwendet werden, wenn +* genau eine Instanz der Klasse benötigt wird, die für Nutzer über einen wohldefinierten Zugriffspunkt erreichbar ist. +* es möglich sein soll, diese Klasse durch Vererbung zu erweitern, ohne dass bei Verwendung der erweiterten Instanz Codeänderungen nötig sind. + +## Reale Anwendungen in Java + +* Logging-Klassen +* Konfigurationsklassen in vielen Anwendungen +* Verbindungspools +* Dateimanager +* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + +## Vor- und Nachteile +Vorteile: +* Kontrollierter Zugriff auf die einzige Instanz. +* Namensraum wird nicht unnötig belastet. +* Operationen und Darstellungen können durch Vererbung verfeinert werden. +* Bei Bedarf auch mehrere Instanzen möglich. +* Flexibler als Klassenoperationen + +Nachteile: +* Schwierig zu testen wegen globalem Status. +* Möglicherweise komplexeres Lebenszyklusmanagement. +* Bei Parallelität sind ohne sorgfältige Synchronisierung Engpässe möglich. + +## Verwandte Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Oft verwendet, um sicherzustellen, dass nur eine Instanz existiert. +* [Factory Methoden](https://java-design-patterns.com/patterns/factory-method/): Das Singleton-Pattern kann implementiert werden, indem über eine Factory-Methode die Instanzerzeugung gekapselt wird. +* [Prototyp](https://java-design-patterns.com/patterns/prototype/): Hier müssen keine Instanzen erzeugt werden. Das Pattern kann zusammen mit dem Singleton verwendet werden, um einzige Instanzen zu verwalten. + +## Quellen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/localization/de/step-builder/README.md b/localization/de/step-builder/README.md new file mode 100644 index 000000000000..cdcb0b6ee9ac --- /dev/null +++ b/localization/de/step-builder/README.md @@ -0,0 +1,218 @@ +--- +shortTitle: Step Builder +category: Creational +language: de +tag: + - Code simplification + - Domain + - Encapsulation + - Extensibility + - Instantiation + - Interface +--- + +## Alternativbezeichnung + +* Fluent Builder + +## Zweck + +Das Step-Builder-Pattern ist eine erweiterte Technik, um komplexe Objekte übersichtlich und flexibel +zu erzeugen. Es ist ideal für Szenarien, in denen die Objekterzeugung schrittweise und äußerst genau zu erfolgen hat. + +## Detaillierte Erklärung + +Vergleichsbeispiel: + +> Betrachten wir den Zusammenbau eines individuell konfigurierten Computers. +Dafür sind mehrere Schritte nötig: Die CPU muss ausgewählt werden, ein Motherboard, dazu kommen +Arbeitsspeicher, Grafikkarte und Festplatte, die nach und nach ins Gehäuse eingebaut werden müssen. +Jeder Schritt folgt auf den anderen, bis schließlich ein funktionsfähiger Rechner entsteht. +Dieser schrittweise Konstruktionsprozess entspricht dem Step-Builder-Pattern und sorgt dafür, +dass alle nötigen Komponenten richtig zusammengebaut werden und anforderungsgemäß funktionieren. + +In einfachen Worten + +> Das Step-Builder-Pattern konstruiert komplexe Objekte nach und nach durch eine Reihe +definierter Schritte. Das macht den Vorgang übersichtlich und flexibel. + +Wikipedia sagt + +> Step Builder ist eine Variante des Builder-Patterns mit dem Ziel, eine flexible Lösung +zur schrittweisen Konstruktion komplexer Objekte anzubieten. Sie ist besonders hilfreich, +wenn ein Objekt viele Initialisierungsschritte benötigt, die der Klarheit und Flexibilität wegen +einzeln abgearbeitet werden können. + +Ablaufdiagramm + +![Step Builder Ablaufdiagramm](/step-builder/etc/step-builder-sequence-diagram.png) + +## Programmbeispiel + +Als Erweiterung des Builder-Patterns führt Step Builder den Nutzer Schritt für Schritt durch +den Erzeugungsprozess eines Objekts. Es werden immer nur die nächsten verfügbaren Schritte +angezeigt, und die build-Methode ist erst dann verfügbar, wenn das Objekt tatsächlich bereit +zum Bau ist. + +Betrachten wir eine Klasse `Character` mit vielen Attributen wie `name`, `fighterClass`, +`wizardClass`, `weapon`, `spell`, und `abilities`. + +```java +public class Character { + + private String name; + private String fighterClass; + private String wizardClass; + private String weapon; + private String spell; + private List abilities; + + public Character(String name) { + this.name = name; + } + +} +``` + +Die Konstruktion ist wegen der vielen Attribute komplex. Darum verwenden wir Step Builder. + +Wir schreiben eine Klasse `CharacterStepBuilder`, um den Benutzer durch den Konstruktionsprozess zu führen. + +```java +public class CharacterStepBuilder { + + // neuer Builder startet mit dem Schritt Namensvergabe + public static NameStep newBuilder() { + return new CharacterSteps(); + } + +} +``` + +Die Klasse `CharacterStepBuilder` enthält eine Reihe von Interfaces, +die jeweils einen Schritt des Konstruktionsprozesses repräsentieren. Indem jedes Interface +eine Methode für den folgenden Schritt deklariert, wird der Benutzer durch den Prozess geführt. + +```java +// nach der Namensvergabe kommt die Auswahl der wizardClass oder fighterClass +public interface NameStep { + ClassStep name(String name); +} +``` + +```java +// nach der Klassenwahl wird entweder eine Waffe oder ein Zauberspruch zugewiesen +public interface ClassStep { + WeaponStep fighterClass(String fighterClass); + SpellStep wizardClass(String wizardClass); +} + +// Weitere Schritte weggelassen +``` + +Die Klasse `Steps` implementiert all diese Interfaces und baut schließlich das `Character`-Object. + +```java +private static class Steps implements NameStep, ClassStep, WeaponStep, SpellStep, BuildStep { + + private String name; + private String fighterClass; + private String wizardClass; + private String weapon; + private String spell; + private List abilities; + + // Die Implementationen der Methoden für die einzelnen Schritte sind hier weggelassen + + @Override + public Character build() { + return new Character(name, fighterClass, wizardClass, weapon, spell, abilities); + } +} +``` + +Jetzt ist die Erzeugung eines `Character`-Objekts ein geführter Prozess. + +```java +public static void main(String[] args) { + + var warrior = CharacterStepBuilder + .newBuilder() + .name("Amberjill") + .fighterClass("Paladin") + .withWeapon("Sword") + .noAbilities() + .build(); + + LOGGER.info(warrior.toString()); + + var mage = CharacterStepBuilder + .newBuilder() + .name("Riobard") + .wizardClass("Sorcerer") + .withSpell("Fireball") + .withAbility("Fire Aura") + .withAbility("Teleport") + .noMoreAbilities() + .build(); + + LOGGER.info(mage.toString()); + + var thief = CharacterStepBuilder + .newBuilder() + .name("Desmond") + .fighterClass("Rogue") + .noWeapon() + .build(); + + LOGGER.info(thief.toString()); +} +``` + +Konsolenausgabe: + +``` +12:58:13.887 [main] INFO com.iluwatar.stepbuilder.App -- This is a Paladin named Amberjill armed with a Sword. +12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Sorcerer named Riobard armed with a Fireball and wielding [Fire Aura, Teleport] abilities. +12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Rogue named Desmond armed with a with nothing. +``` + +## Verwendung + +* Wenn die Konstruktion eines Objekts viele Initialisierungsschritte benötigt. +* Wenn die Objektkonstruktion komplex ist und viele Parameter enthält. +* Um einen übersichtlichen, lesbaren und wartbaren Objekterzeugungsprozess bereitzustellen. + +## Tutorials + +* [Step Builder (Marco Castigliego)](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html) + +## Reale Anwendungen in Java +* Komplexe Konfigurationseinstellungen in Java-Anwendungen. +* Konstruktion von Objekten für Datenbankeinträge mit vielen Feldern. +* Konstruktion von GUI-Elementen, wo jeder Schritt einen anderen Teil der Schnittstelle festlegt. + +## Vor- und Nachteile + +Vorteile + +* Code wird lesbarer und wartbarer durch übersichtliche und prägnante Objektkonstruktion. +* Erhöhte Flexibilität bei der Objekterzeugung durch Varianten im Konstruktionsprozess. +* Unterstützt unveränderbare Objekte durch Abtrennung ihrer Erzeugung.ntation. + +Nachteile + +* Code kann durch zusätzliche Klassen und Interfaces komplexer werden. +* Langatmiger Code bei vielen Konstruktionsschritten. + +## Verwandte Patterns + +* [Builder](https://java-design-patterns.com/patterns/builder/): Beide Patterns dienen der Konstruktion komplexer Objekte. Step Builder ist eine Variante mit Betonung auf schrittweisem Vorgehen. +* [Fluent Interface](https://java-design-patterns.com/patterns/fluentinterface/): Wird oft zusammen mit Step Builder verwendet, um eine sprechende API mit Methodenverkettung zur Konstruktion bereitzustellen. +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Wird manchmal im Step-Builder-Pattern genutzt, um die Konstruktion des Builders selbst zu kapseln. + +## Quellen + +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/localization/fa/abstract-document/README.md b/localization/fa/abstract-document/README.md new file mode 100644 index 000000000000..7097ffc8b4ea --- /dev/null +++ b/localization/fa/abstract-document/README.md @@ -0,0 +1,243 @@ +--- +title: "الگوی Abstract Document در جاوا: ساده‌سازی مدیریت داده با انعطاف‌پذیری" +shortTitle: Abstract Document +description: "الگوی طراحی Abstract Document در جاوا را بررسی کنید. با هدف، توضیح، کاربرد، مزایا و نمونه‌های دنیای واقعی برای پیاده‌سازی ساختارهای داده‌ای پویا و انعطاف‌پذیر آشنا شوید." +category: Structural +language: fa +tag: + - Abstraction + - Decoupling + - Dynamic typing + - Encapsulation + - Extensibility + - Polymorphism +--- + +## هدف الگوی طراحی Abstract Document + +الگوی طراحی Abstract Document در جاوا یک الگوی طراحی ساختاری مهم است که راهی یکپارچه برای مدیریت ساختارهای داده‌ای سلسله‌مراتبی و درخت‌ی فراهم می‌کند، با تعریف یک واسط مشترک برای انواع مختلف اسناد. این الگو ساختار اصلی سند را از فرمت‌های خاص داده جدا می‌کند، که باعث به‌روزرسانی پویا و نگهداری ساده‌تر می‌شود. + +## توضیح دقیق الگوی Abstract Document با نمونه‌های دنیای واقعی + +الگوی طراحی Abstract Document در جاوا امکان مدیریت پویا ویژگی‌های پویا(غیر استاتیک) را فراهم می‌کند. این الگو از مفهوم traits استفاده می‌کند تا ایمنی نوع‌داده (type safety) را فراهم کرده و ویژگی‌های کلاس‌های مختلف را به مجموعه‌ای از واسط‌ها تفکیک کند. + +مثال دنیای واقعی + +> فرض کنید یک سیستم کتابخانه از الگوی Abstract Document در جاوا استفاده می‌کند، جایی که کتاب‌ها می‌توانند فرمت‌ها و ویژگی‌های متنوعی داشته باشند: کتاب‌های فیزیکی، کتاب‌های الکترونیکی، و کتاب‌های صوتی. هر فرمت ویژگی‌های خاص خود را دارد، مانند تعداد صفحات برای کتاب‌های فیزیکی، حجم فایل برای کتاب‌های الکترونیکی، و مدت‌زمان برای کتاب‌های صوتی. الگوی Abstract Document به سیستم کتابخانه اجازه می‌دهد تا این فرمت‌های متنوع را به‌صورت انعطاف‌پذیر مدیریت کند. با استفاده از این الگو، سیستم می‌تواند ویژگی‌ها را به‌صورت پویا ذخیره و بازیابی کند، بدون نیاز به ساختار سفت و سخت برای هر نوع کتاب، و این کار افزودن فرمت‌ها یا ویژگی‌های جدید را در آینده بدون تغییرات عمده در کد آسان می‌سازد. + +به زبان ساده + +> الگوی Abstract Document اجازه می‌دهد ویژگی‌هایی به اشیاء متصل شوند بدون اینکه خود آن اشیاء از آن اطلاع داشته باشند. + +ویکی‌پدیا می‌گوید + +> یک الگوی طراحی ساختاری شی‌ء‌گرا برای سازماندهی اشیاء در کلید-مقدارهایی با تایپ آزاد و ارائه داده‌ها از طریق نمای تایپ است. هدف این الگو دستیابی به انعطاف‌پذیری بالا بین اجزا در یک زبان strongly typed است که در آن بتوان ویژگی‌های جدیدی را به‌صورت پویا به ساختار درختی اشیاء اضافه کرد، بدون از دست دادن پشتیبانی از type safety. این الگو از traits برای جداسازی ویژگی‌های مختلف یک کلاس در اینترفیس‌های متفاوت استفاده می‌کند. + +نمودار کلاس + +![Abstract Document class diagram](./etc/abstract-document.png "Abstract Document class diagram") + +## مثال برنامه‌نویسی از الگوی Abstract Document در جاوا + +فرض کنید یک خودرو داریم که از قطعات مختلفی تشکیل شده است. اما نمی‌دانیم آیا این خودرو خاص واقعاً همه قطعات را دارد یا فقط برخی از آن‌ها. خودروهای ما پویا و بسیار انعطاف‌پذیر هستند. + +بیایید ابتدا کلاس‌های پایه `Document` و `AbstractDocument` را تعریف کنیم. این کلاس‌ها اساساً یک شیء را قادر می‌سازند تا یک نقشه از ویژگی‌ها و هر تعداد شیء فرزند را نگه دارد. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + + // Other properties and methods... +} +``` +در ادامه، یک enum به نام Property و مجموعه‌ای از واسط‌ها برای type، price، model و parts تعریف می‌کنیم. این کار به ما اجازه می‌دهد یک واسط با ظاهر استاتیک برای کلاس Car ایجاد کنیم. +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} + +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} + +public class Part extends AbstractDocument implements HasType, HasModel, HasPrice { + + public Part(Map properties) { + super(properties); + } +} +``` +اکنون آماده‌ایم تا کلاس Car را معرفی کنیم. +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` +و در نهایت، نحوه ساخت و استفاده از Car را در یک مثال کامل می‌بینید. +```java + public static void main(String[] args) { + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); +} +``` +خروجی برنامه: +``` +07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Constructing parts and car +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Here is our car: +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> model: 300SL +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> price: 10000 +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> parts: +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- wheel/15C/100 +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- door/Lambo/300 +``` + + ### چه زمانی از الگوی Abstract Document در جاوا استفاده کنیم؟ + +الگوی طراحی Abstract Document به‌ویژه در سناریوهایی مفید است که نیاز به مدیریت انواع مختلفی از اسناد در جاوا وجود دارد که برخی ویژگی‌ها یا رفتارهای مشترک دارند، ولی ویژگی‌ها یا رفتارهای خاص خود را نیز دارند. در ادامه چند سناریوی مناسب برای این الگو آورده شده است: + +* سیستم‌های مدیریت محتوا (CMS): ممکن است انواع مختلفی از محتوا مانند مقاله، تصویر، ویدئو و... وجود داشته باشد. هر نوع محتوا ویژگی‌های مشترکی مثل تاریخ ایجاد، نویسنده و تگ‌ها دارد، ولی همچنین ویژگی‌های خاصی مثل ابعاد تصویر یا مدت‌زمان ویدئو. + +* سیستم‌های فایل: اگر یک سیستم فایل طراحی می‌کنید که باید انواع مختلف فایل مانند اسناد، تصاویر، فایل‌های صوتی و دایرکتوری‌ها را مدیریت کند، این الگو می‌تواند راهی یکپارچه برای دسترسی به ویژگی‌هایی مانند اندازه فایل یا تاریخ ایجاد، فراهم کند و در عین حال ویژگی‌های خاص هر نوع فایل را هم مدیریت کند. + +* سیستم‌های تجارت الکترونیک: یک پلتفرم فروش آنلاین ممکن است محصولات مختلفی داشته باشد مثل محصولات فیزیکی، فایل‌های دیجیتال، و اشتراک‌ها. این محصولات ویژگی‌هایی مثل نام، قیمت و توضیح را به اشتراک می‌گذارند، ولی ویژگی‌های خاصی هم دارند مانند وزن حمل برای محصولات فیزیکی یا لینک دانلود برای دیجیتال‌ها. + +* سیستم‌های سوابق پزشکی: در مراقبت سلامت، پرونده بیماران ممکن است داده‌های مختلفی مثل مشخصات فردی، سوابق پزشکی، نتایج آزمایش‌ها و نسخه‌ها را شامل شود. این الگو می‌تواند ویژگی‌های مشترک مثل شماره بیمار یا تاریخ تولد را مدیریت کند و هم‌زمان ویژگی‌های خاصی مثل نتایج آزمایش یا داروهای تجویزی را هم پوشش دهد. + +* مدیریت پیکربندی: هنگام کار با تنظیمات پیکربندی نرم‌افزار، ممکن است انواع مختلفی از عناصر پیکربندی وجود داشته باشد، هر یک با ویژگی‌های خاص خود. این الگو می‌تواند برای مدیریت این عناصر مفید باشد. + +* پلتفرم‌های آموزشی: سیستم‌های آموزشی ممکن است انواع مختلفی از منابع یادگیری داشته باشند مثل محتوای متنی، ویدیوها، آزمون‌ها و تمرین‌ها. ویژگی‌های مشترکی مثل عنوان، نویسنده و تاریخ انتشار وجود دارد، ولی ویژگی‌های خاصی مانند مدت ویدیو یا مهلت تحویل تمرین نیز ممکن است وجود داشته باشد. + +* ابزارهای مدیریت پروژه: در برنامه‌های مدیریت پروژه، ممکن است انواع مختلفی از وظایف مانند آیتم‌های to-do، milestoneها و issueها داشته باشید. این الگو می‌تواند برای مدیریت ویژگی‌های عمومی مانند نام وظیفه و مسئول آن استفاده شود و در عین حال ویژگی‌های خاص مانند تاریخ milestone یا اولویت issue را نیز پوشش دهد. + +* اسناد ساختار ویژگی‌های متنوع و در حال تحول دارند. + +* افزودن ویژگی‌های جدید به‌صورت پویا یک نیاز رایج است. + +* جداسازی دسترسی به داده از فرمت‌های خاص حیاتی است. + +* نگهداری‌پذیری و انعطاف‌پذیری برای کد اهمیت دارد. + +ایده اصلی پشت الگوی Abstract Document فراهم کردن روشی انعطاف‌پذیر و قابل توسعه برای مدیریت انواع مختلف اسناد یا موجودیت‌ها با ویژگی‌های مشترک و خاص است. با تعریف یک واسط مشترک و پیاده‌سازی آن در انواع مختلف اسناد، می‌توان به شیوه‌ای منظم و یکپارچه برای مدیریت ساختارهای پیچیده داده دست یافت. +### مزایا و معایب الگوی Abstract Document +

+مزایا: + +* انعطاف‌پذیری: پشتیبانی از ساختارهای متنوع اسناد و ویژگی‌ها. + +* قابلیت توسعه: افزودن ویژگی‌های جدید بدون شکستن کد موجود. + +* نگهداری‌پذیری: ارتقاء کد تمیز و قابل تطبیق به‌واسطه جداسازی وظایف. + +* قابلیت استفاده مجدد: نمای دید تایپ‌شده باعث استفاده مجدد از کد برای دسترسی به نوع خاصی از ویژگی می‌شود. + +معایب: + +* پیچیدگی: نیاز به تعریف واسط‌ها و نماها، که باعث اضافه شدن سربار پیاده‌سازی می‌شود. + +* کارایی: ممکن است سربار کمی نسبت به دسترسی مستقیم به داده داشته باشد. +
+ +منابع و اعتبارها + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) + +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) + +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)] (https://amzn.to/49zRP4R) + +* [Patterns of Enterprise Application Architecture] (https://amzn.to/3WfKBPR) + +* [Abstract Document Pattern (Wikipedia)] (https://en.wikipedia.org/wiki/Abstract_Document_Pattern) + +* [Dealing with Properties (Martin Fowler)] (http://martinfowler.com/apsupp/properties.pdf) diff --git a/localization/de/abstract-document/etc/abstract-document.png b/localization/fa/abstract-document/etc/abstract-document.png similarity index 100% rename from localization/de/abstract-document/etc/abstract-document.png rename to localization/fa/abstract-document/etc/abstract-document.png diff --git a/localization/fa/abstract-factory/README.md b/localization/fa/abstract-factory/README.md new file mode 100644 index 000000000000..85dce3437ba4 --- /dev/null +++ b/localization/fa/abstract-factory/README.md @@ -0,0 +1,223 @@ +--- +title: "الگوی طراحی Abstract Factory در جاوا: مهارت در ایجاد شیء با ظرافت" +shortTitle: Abstract Factory +description: "با مثال‌های دنیای واقعی، دیاگرام‌های کلاس و آموزش‌ها، الگوی Abstract Factory را در جاوا بیاموزید. منظور، کاربرد، مزایا و نمونه‌های واقعی آن را درک کنید و دانش طراحی الگوهایتان را افزایش دهید." +category: Creational +language: fa +tag: + - Abstraction + - Decoupling + - Gang of Four + - Instantiation + - Polymorphism +--- + +## همچنین به این عنوان شناخته می‌شود + +* کیت + +## هدف از الگوی طراحی Abstract Factory + +الگوی Abstract Factory در جاوا یک واسط برای ایجاد خانواده‌هایی از اشیای مرتبط یا وابسته فراهم می‌کند بدون آنکه کلاس‌های مشخص آن‌ها را تعیین کند، و این کار موجب افزایش مدولاریتی و انعطاف‌پذیری در طراحی نرم‌افزار می‌شود. + +## توضیح دقیق الگوی Abstract Factory با مثال‌های دنیای واقعی + +مثال دنیای واقعی + +> تصور کنید یک شرکت مبلمان وجود دارد که از الگوی Abstract Factory در جاوا برای تولید سبک‌های مختلف مبلمان استفاده می‌کند: مدرن، ویکتوریایی و روستایی. هر سبک شامل محصولاتی مانند صندلی‌ها، میزها و کاناپه‌ها است. برای اطمینان از یکنواختی در هر سبک، شرکت از یک الگوی Abstract Factory استفاده می‌کند. +> +> در این سناریو، Abstract Factory یک واسط برای ایجاد خانواده‌هایی از اشیای مبلمان مرتبط (صندلی‌ها، میزها، کاناپه‌ها) است. هر Factory مشخص (کارخانه‌ی مبلمان مدرن، کارخانه‌ی مبلمان ویکتوریایی، کارخانه‌ی مبلمان روستایی) این واسط را پیاده‌سازی می‌کند و مجموعه‌ای از محصولات مطابق با سبک خاص ایجاد می‌کند. به این ترتیب، مشتریان می‌توانند یک مجموعه کامل از مبلمان مدرن یا ویکتوریایی ایجاد کنند بدون اینکه نگران جزئیات ساخت آن‌ها باشند. این باعث حفظ یکنواختی سبک می‌شود و امکان تغییر آسان سبک مبلمان را فراهم می‌کند. + +به زبان ساده + +> کارخانه‌ای از کارخانه‌ها؛ یک Factory یا کارخانه که مجموعه‌ای از کارخانه‌های مرتبط یا وابسته را بدون مشخص کردن کلاس‌های concrete آن‌ها گروه‌بندی می‌کند. + +ویکی‌پدیا می‌گوید + +> الگوی Abstract Factory راهی برای کپسوله کردن مجموعه‌ای از کارخانه‌های منحصر به فرد با یک تم مشترک بدون تعیین کلاس‌های concrete آن‌ها فراهم می‌کند. + +دیاگرام کلاس + +![Abstract Factory class diagram](./etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## مثال برنامه‌نویسی از Abstract Factory در جاوا + +برای ایجاد یک پادشاهی با استفاده از الگوی Abstract Factory در جاوا، ما به اشیایی با یک تم مشترک نیاز داریم. یک پادشاهی اِلف (Elf) به یک پادشاه اِلف، یک قلعه‌ی اِلف، و یک ارتش اِلف نیاز دارد، در حالی که یک پادشاهی اورک (Orc) به یک پادشاه اورک، یک قلعه‌ی اورک، و یک ارتش اورک نیاز دارد. بین اشیای موجود در پادشاهی وابستگی وجود دارد. + +ترجمه‌ی مثال پادشاهی بالا. ابتدا ما برخی واسط‌ها و پیاده‌سازی‌هایی برای اشیای موجود در پادشاهی داریم: + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Elven implementations -> +public class ElfCastle implements Castle { + static final String DESCRIPTION = "This is the elven castle!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfKing implements King { + static final String DESCRIPTION = "This is the elven king!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfArmy implements Army { + static final String DESCRIPTION = "This is the elven Army!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Orcish implementations similarly -> ... +``` + +سپس واسط و پیاده‌سازی‌های کارخانه‌ی پادشاهی را داریم: + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +// Orcish implementations similarly -> ... +``` + +اکنون می‌توانیم یک کارخانه برای کارخانه‌های مختلف پادشاهی طراحی کنیم. در این مثال، ما `FactoryMaker` را ایجاد کردیم که مسئول برگرداندن یک نمونه از `ElfKingdomFactory` یا `OrcKingdomFactory` است. مشتری می تواند از `FactoryMaker` برای ایجاد کارخانه concrete مورد نظر استفاده کند که به نوبه خود اشیاء concrete مختلف (مشتق شده از ارتش، پادشاه، قلعه) را تولید می‌کند. در این مثال، ما همچنین از یک enum برای پارامتری کردن نوع کارخانه پادشاهی که مشتری درخواست خواهد کرد استفاده کردیم. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + }; + } +} +``` + +نمونه‌ای از تابع اصلی برنامه: + +```java +LOGGER.info("elf kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); + +LOGGER.info("orc kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); +``` + +خروجی برنامه: + +``` +07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king! +``` + +## چه زمانی باید از الگوی Abstract Factory در جاوا استفاده کرد؟ + +* زمانی که سیستم باید مستقل از نحوه‌ی ایجاد، ترکیب و نمایش محصولاتش باشد. +* زمانی که نیاز به پیکربندی سیستم با یکی از چند خانواده محصول دارید. +* زمانی که باید خانواده‌ای از اشیای مرتبط با هم استفاده شوند، برای اطمینان از یکنواختی. +* زمانی که می‌خواهید کتابخانه‌ای از محصولات را فراهم کنید و فقط واسط‌های آن‌ها را نمایان کنید، نه پیاده‌سازی‌ها را. +* زمانی که طول عمر وابستگی‌ها کوتاه‌تر از مصرف‌کننده باشد. +* زمانی که نیاز به ساخت وابستگی‌ها با مقادیر یا پارامترهای زمان اجرا باشد. +* زمانی که باید در زمان اجرا انتخاب کنید که کدام خانواده از محصول را استفاده کنید. +* زمانی که افزودن محصولات یا خانواده های جدید نباید نیاز به تغییر در کد موجود داشته باشد. + +## آموزش‌های الگوی Abstract Factory در جاوا + +* [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java) +* [Abstract Factory (Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory) + +## مزایا و معایب الگوی Abstract Factory + +مزایا: + +> * انعطاف‌پذیری: به راحتی می‌توان خانواده‌های محصول را تعویض کرد بدون تغییر کد. + +> * جداسازی (Decoupling): کد مشتری فقط با واسط‌های انتزاعی کار می‌کند که باعث قابلیت حمل و نگهداری می‌شود. + +> * قابلیت استفاده مجدد: کارخانه‌های انتزاعی و محصولات امکان استفاده مجدد از مؤلفه‌ها را فراهم می‌کنند. + +> * قابلیت نگهداری: تغییرات در خانواده‌های محصول محلی شده و به‌روزرسانی را ساده‌تر می‌کند. + +معایب: + +> * پیچیدگی: تعریف واسط‌های انتزاعی و کارخانه‌های مشخص سربار اولیه ایجاد می‌کند. + +> * غیرمستقیم بودن: کد مشتری از طریق کارخانه‌ها با محصولات کار می‌کند که ممکن است شفافیت را کاهش دهد. + +## نمونه‌های واقعی استفاده از الگوی Abstract Factory در جاوا + +* کلاس‌های `LookAndFeel` در Java Swing برای ارائه گزینه های مختلف look-and-feel +* پیاده‌سازی‌های مختلف در Java AWT برای ایجاد اجزای مختلف GUI +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## الگوهای طراحی مرتبط با جاوا + +* الگوی [Factory Method](https://java-design-patterns.com/patterns/factory-method/): الگوی کارخانه‌ی انتزاعی از روش‌های کارخانه‌ای برای ایجاد محصولات استفاده می‌کند. +* الگوی [Singleton](https://java-design-patterns.com/patterns/singleton/): کلاس‌های کارخانه‌ی انتزاعی اغلب به صورت Singleton پیاده‌سازی می‌شوند. +* الگوی [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): مشابه کارخانه‌ی انتزاعی اما بر پیکربندی و مدیریت مجموعه‌ای از اشیای مرتبط تمرکز دارد. + +## منابع و ارجاعات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Design Patterns in Java](https://amzn.to/3Syw0vC) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U) diff --git a/localization/fa/abstract-factory/etc/abstract-factory.urm.png b/localization/fa/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/localization/fa/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/localization/fa/active-object/README.md b/localization/fa/active-object/README.md new file mode 100644 index 000000000000..7c105b072aaa --- /dev/null +++ b/localization/fa/active-object/README.md @@ -0,0 +1,220 @@ +--- +title: "الگوی Active Object در جاوا: دستیابی به پردازش ناهمگام کارآمد" +shortTitle: Active Object +description: "با الگوی طراحی Active Object در جاوا آشنا شوید. این راهنما رفتار ناهمگام، هم‌زمانی (concurrency) و مثال‌های کاربردی برای بهبود عملکرد برنامه‌های جاوای شما را پوشش می‌دهد." +category: Concurrency +language: fa +tag: + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management +--- + +## هدف الگوی طراحی Active Object + +الگوی Active Object روشی مطمئن برای پردازش ناهمگام در جاوا فراهم می‌کند که به پاسخ‌گو بودن برنامه‌ها و مدیریت مؤثر threadها کمک می‌کند. این الگو با محصور کردن وظایف در شیءهایی که هر کدام thread و صف پیام مخصوص خود را دارند، به این هدف می‌رسد. این جداسازی باعث می‌شود thread اصلی پاسخ‌گو باقی بماند و مشکلاتی مانند دست‌کاری مستقیم threadها یا دسترسی به وضعیت مشترک (shared state) به وجود نیاید. + +## توضیح کامل الگوی Active Object با مثال‌های دنیای واقعی + +مثال دنیای واقعی + +> تصور کنید در یک رستوران شلوغ، مشتریان سفارش خود را به گارسون‌ها می‌سپارند. به‌جای آنکه گارسون‌ها خودشان به آشپزخانه بروند و غذا را آماده کنند، سفارش‌ها را روی کاغذهایی می‌نویسند و به یک هماهنگ‌کننده می‌دهند. این هماهنگ‌کننده گروهی از سرآشپزها را مدیریت می‌کند که غذاها را به صورت ناهمگام آماده می‌کنند. هرگاه آشپزی آزاد شود، سفارش بعدی را از صف برمی‌دارد، غذا را آماده می‌کند و پس از آن گارسون را برای سرو غذا مطلع می‌سازد. +> +> در این قیاس، گارسون‌ها نماینده threadهای کلاینت هستند، هماهنگ‌کننده نقش زمان‌بند (scheduler) را ایفا می‌کند، و آشپزها نمایان‌گر اجرای متدها در threadهای جداگانه هستند. این ساختار باعث می‌شود گارسون‌ها بتوانند بدون مسدود شدن توسط فرایند آماده‌سازی غذا، سفارش‌های بیشتری دریافت کنند—درست مانند اینکه الگوی Active Object، فراخوانی متد را از اجرای آن جدا می‌کند تا هم‌زمانی (concurrency) را افزایش دهد. + +به زبان ساده + +> الگوی Active Object، اجرای متد را از فراخوانی آن جدا می‌کند تا در برنامه‌های چندریسمانی (multithreaded)، هم‌زمانی و پاسخ‌گویی بهتری فراهم شود. + +طبق تعریف ویکی‌پدیا + +> الگوی طراحی Active Object اجرای متد را از فراخوانی آن جدا می‌کند، برای شیءهایی که هرکدام thread کنترل مخصوص به خود را دارند. هدف، معرفی هم‌زمانی با استفاده از فراخوانی متد به‌صورت ناهمگام و یک زمان‌بند برای مدیریت درخواست‌ها است. +> +> این الگو شامل شش جزء کلیدی است: +> +> * یک proxy، که رابطی برای کلاینت‌ها با متدهای عمومی فراهم می‌کند. +> * یک interface که درخواست متد برای شیء فعال (active object) را تعریف می‌کند. +> * فهرستی از درخواست‌های معلق از سوی کلاینت‌ها. +> * یک زمان‌بند (scheduler) که تصمیم می‌گیرد کدام درخواست بعدی اجرا شود. +> * پیاده‌سازی متد شیء فعال. +> * یک callback یا متغیر برای اینکه کلاینت نتیجه را دریافت کند. + +نمودار توالی + +![Active Object sequence diagram](./etc/active-object-sequence-diagram.png) + +## مثال برنامه‌نویسی از Active Object در جاوا + +این بخش نحوه عملکرد الگوی Active Object در جاوا را توضیح می‌دهد و کاربرد آن در مدیریت وظایف ناهمگام و کنترل هم‌زمانی را نشان می‌دهد. + +اورک‌ها به دلیل ذات وحشی و غیرقابل مهارشان شناخته می‌شوند. به‌نظر می‌رسد هرکدام thread کنترل مخصوص خود را دارند. برای پیاده‌سازی یک موجود که دارای سازوکار thread مستقل خود باشد و فقط API را در اختیار قرار دهد نه اجرای داخلی را، می‌توان از الگوی Active Object استفاده کرد. + +```java +public abstract class ActiveCreature { + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.", name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +می‌توان دید هر کلاسی که از ActiveCreature ارث‌بری کند، دارای thread کنترل مختص به خود برای فراخوانی و اجرای متدها خواهد بود. + +برای مثال، کلاس Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } +} +``` +اکنون می‌توان چند موجود مانند orc ایجاد کرد، به آن‌ها دستور داد که بخورند و پرسه بزنند، و آن‌ها این دستورات را در thread مختص به خود اجرا می‌کنند: + +```java +public class App implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); + + private static final int NUM_CREATURES = 3; + + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + List creatures = new ArrayList<>(); + try { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.add(new Orc(Orc.class.getSimpleName() + i)); + creatures.get(i).eat(); + creatures.get(i).roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.get(i).kill(0); + } + } + } +} +``` + +خروجی برنامه: + +``` +09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating! +09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating! +09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. +``` + +چه زمانی از الگوی Active Object در جاوا استفاده کنیم؟ + +از الگوی Active Object در جاوا استفاده کنید زمانی که: +> * نیاز دارید وظایف ناهمگام را بدون مسدود کردن thread اصلی مدیریت کنید تا عملکرد و پاسخ‌گویی بهتری داشته باشید. +> * نیاز به تعامل ناهمگام با منابع خارجی دارید. +> * می‌خواهید پاسخ‌گویی برنامه را افزایش دهید. +> * نیاز به مدیریت وظایف هم‌زمان به‌صورت ماژولار و قابل نگهداری دارید. + +آموزش‌های Java برای الگوی Active Object +> [Android and Java Concurrency: The Active Object Pattern (Douglas Schmidt)]((https://www.youtube.com/watch?v=Cd8t2u5Qmvc)) + +کاربردهای دنیای واقعی الگوی Active Object در جاوا + +> سیستم‌های معاملات بلادرنگ که درخواست‌ها به‌صورت ناهمگام پردازش می‌شوند. +> که در آن وظایف طولانی در پس‌زمینه اجرا می‌شوند بدون آنکه رابط کاربری را متوقف کنند. +> رابط‌های کاربری گرافیکی (GUI) +> برنامه‌نویسی بازی‌ها برای مدیریت به‌روزرسانی‌های هم‌زمان وضعیت بازی یا محاسبات هوش مصنوعی. + +مزایا و ملاحظات الگوی Active Object + +با مزایا و معایب استفاده از الگوی Active Object در جاوا آشنا شوید؛ از جمله بهبود ایمنی threadها و ملاحظات سربار احتمالی (overhead). + +> مزایا: +> +> * پاسخ‌گویی بهتر thread اصلی. +> * محصورسازی مسائل مربوط به هم‌زمانی درون شیءها. +> * بهبود سازمان‌دهی کد و قابلیت نگهداری. +> * فراهم‌سازی ایمنی در برابر شرایط بحرانی (thread safety) و جلوگیری از مشکلات وضعیت مشترک. + +> معایب: +> +> * سربار اضافی به دلیل ارسال پیام و مدیریت threadها. +> * برای تمام سناریوهای هم‌زمانی مناسب نیست. + +الگوهای طراحی مرتبط در جاوا + +> * [Command](https://java-design-patterns.com/patterns/command/): درخواست را به‌عنوان یک شیء کپسوله می‌کند، مشابه روشی که Active Object فراخوانی متد را کپسوله می‌کند. +> * [Promise](https://java-design-patterns.com/patterns/promise/): راهی برای دریافت نتیجه یک فراخوانی متد ناهمگام فراهم می‌کند؛ اغلب همراه با Active Object استفاده می‌شود. +> * [Proxy](https://java-design-patterns.com/patterns/proxy/): الگوی Active Object می‌تواند از proxy برای مدیریت فراخوانی‌های متد به‌صورت ناهمگام استفاده کند. + +منابع و مراجع + +> * [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) +> * [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) +> * [Java Concurrency in Practice](https://amzn.to/4aRMruW) +> * [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV) +> * [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61) +> * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) + diff --git a/localization/fa/active-object/etc/active-object-sequence-diagram.png b/localization/fa/active-object/etc/active-object-sequence-diagram.png new file mode 100644 index 000000000000..b725d9b07b6d Binary files /dev/null and b/localization/fa/active-object/etc/active-object-sequence-diagram.png differ diff --git a/localization/fa/active-object/etc/active-object.urm.png b/localization/fa/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/fa/active-object/etc/active-object.urm.png differ diff --git a/localization/fa/active-object/etc/active-object.urm.puml b/localization/fa/active-object/etc/active-object.urm.puml new file mode 100644 index 000000000000..3fc3c8e1e921 --- /dev/null +++ b/localization/fa/active-object/etc/active-object.urm.puml @@ -0,0 +1,25 @@ +@startuml +package com.iluwatar.activeobject { + abstract class ActiveCreature { + - logger : Logger + - name : String + - requests : BlockingQueue + - thread : Thread + + ActiveCreature(name : String) + + eat() + + name() : String + + roam() + } + class App { + - creatures : Integer + - logger : Logger + + App() + + main(args : String[]) {static} + + run() + } + class Orc { + + Orc(name : String) + } +} +Orc --|> ActiveCreature +@enduml \ No newline at end of file diff --git a/localization/fa/factory/README.md b/localization/fa/factory/README.md new file mode 100644 index 000000000000..db41813464e3 --- /dev/null +++ b/localization/fa/factory/README.md @@ -0,0 +1,155 @@ +--- +title: "الگوی factory در جاوا: ساده‌سازی ایجاد اشیاء" +shortTitle: factory +description: "الگوی طراحی factory در جاوا را با مثال‌ها و توضیحات دقیق بیاموزید. یاد بگیرید چگونه با استفاده از الگوی factory کدی انعطاف‌پذیر و مقیاس‌پذیر ایجاد کنید. مناسب برای توسعه‌دهندگانی که به دنبال بهبود مهارت‌های طراحی شیءگرا هستند." +category: structural +language: fa +tag: + - Abstraction + - Encapsulation + - Gang of Four + - Instantiation + - Polymorphism +--- + +## هدف از الگوی طراحی factory + +الگوی طراحی factory در جاوا یک الگوی ساختاری است که یک رابط برای ایجاد یک شیء تعریف می‌کند اما به زیرکلاس‌ها اجازه می‌دهد نوع اشیائی را که ایجاد خواهند شد تغییر دهند. این الگو انعطاف‌پذیری و مقیاس‌پذیری را در کد شما ترویج می‌دهد. + +## توضیح دقیق الگوی factory با مثال‌های دنیای واقعی + +### مثال دنیای واقعی + +> تصور کنید در یک نانوایی انواع مختلف کیک‌ها با استفاده از الگوی طراحی factory ساخته می‌شوند. `CakeFactory` فرآیند ایجاد را مدیریت می‌کند و امکان افزودن آسان انواع جدید کیک‌ها را بدون تغییر در فرآیند اصلی فراهم می‌کند. `CakeFactory` می‌تواند انواع مختلفی از کیک‌ها مانند کیک شکلاتی، کیک وانیلی و کیک توت‌فرنگی تولید کند. به جای اینکه کارکنان نانوایی به صورت دستی مواد اولیه را انتخاب کنند و دستورالعمل‌های خاصی را برای هر نوع کیک دنبال کنند، از `CakeFactory` برای مدیریت فرآیند استفاده می‌کنند. مشتری فقط نوع کیک را درخواست می‌کند و `CakeFactory` مواد اولیه و دستورالعمل مناسب را تعیین کرده و نوع خاصی از کیک را ایجاد می‌کند. این تنظیم به نانوایی اجازه می‌دهد تا انواع جدید کیک‌ها را به راحتی اضافه کند بدون اینکه فرآیند اصلی تغییر کند، که این امر انعطاف‌پذیری و مقیاس‌پذیری را ترویج می‌دهد. + +### تعریف ویکی‌پدیا + +> الگوی factory یک شیء برای ایجاد اشیاء دیگر است – به طور رسمی، factory یک تابع یا متدی است که اشیاء با نمونه‌ها یا کلاس‌های مختلف را بازمی‌گرداند. + +### نمودار توالی + +![نمودار توالی factory](./etc/factory-sequence-diagram.png) + +## مثال برنامه‌نویسی از الگوی factory در جاوا + +تصور کنید یک کیمیاگر قصد دارد سکه‌هایی تولید کند. کیمیاگر باید بتواند هم سکه‌های طلا و هم سکه‌های مسی ایجاد کند و تغییر بین آن‌ها باید بدون تغییر در کد موجود امکان‌پذیر باشد. الگوی factory این امکان را فراهم می‌کند با ارائه یک متد ایجاد استاتیک که می‌توان آن را با پارامترهای مرتبط فراخوانی کرد. + +در جاوا، می‌توانید الگوی factory را با تعریف یک رابط `Coin` و پیاده‌سازی‌های آن `GoldCoin` و `CopperCoin` پیاده‌سازی کنید. کلاس `CoinFactory` یک متد استاتیک `getCoin` ارائه می‌دهد تا اشیاء سکه را بر اساس نوع ایجاد کند. + +```java +public interface Coin { + String getDescription(); +} +``` + +```java +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +```java +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +کد زیر انواع سکه‌هایی که پشتیبانی می‌شوند (`GoldCoin` و `CopperCoin`) را نشان می‌دهد. + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +سپس متد استاتیک `getCoin` برای ایجاد اشیاء سکه در کلاس factory `CoinFactory` کپسوله شده است. + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +اکنون، در کد کلاینت، می‌توانیم انواع مختلفی از سکه‌ها را با استفاده از کلاس factory تولید کنیم. + +```java +public static void main(String[] args) { + LOGGER.info("The alchemist begins his work."); + var coin1 = CoinFactory.getCoin(CoinType.COPPER); + var coin2 = CoinFactory.getCoin(CoinType.GOLD); + LOGGER.info(coin1.getDescription()); + LOGGER.info(coin2.getDescription()); +} +``` + +خروجی برنامه: + +``` +06:19:53.530 [main] INFO com.iluwatar.factory.App -- The alchemist begins his work. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a copper coin. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a gold coin. +``` + +## زمان استفاده از الگوی factory در جاوا + +* از الگوی طراحی factory در جاوا زمانی استفاده کنید که کلاس از قبل نوع دقیق و وابستگی‌های اشیائی که نیاز به ایجاد آن دارد را نمی‌داند. +* زمانی که یک متد یکی از چندین کلاس ممکن که یک کلاس والد مشترک دارند را بازمی‌گرداند و می‌خواهد منطق انتخاب شیء را کپسوله کند. +* این الگو معمولاً هنگام طراحی فریم‌ورک‌ها یا کتابخانه‌ها برای ارائه بهترین انعطاف‌پذیری و جداسازی از انواع کلاس‌های خاص استفاده می‌شود. + +## کاربردهای دنیای واقعی الگوی factory در جاوا + +> * [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +> * [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +> * [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +> * [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +> * این مورد [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) اشیاء singleton مختلف را بر اساس یک پروتکل بازمی‌گرداند +> * [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +> * [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) و متدهای مشابه دیگر. +> +> * کتابخانه‌ی JavaFX از الگوهای factory برای ایجاد کنترل‌های مختلف رابط کاربری متناسب با نیازهای محیط کاربر استفاده می‌کند. + +## مزایا و معایب الگوی factory + +### مزایا: + +> * پیاده‌سازی الگوی factory در برنامه جاوای شما، وابستگی بین پیاده‌سازی و کلاس‌هایی که استفاده می‌کند را کاهش می‌دهد. +> * از [اصل Open/Closed](https://java-design-patterns.com/principles/#open-closed-principle) پشتیبانی می‌کند، زیرا سیستم می‌تواند انواع جدیدی را بدون تغییر کد موجود معرفی کند. + +### معایب: + +> * کد می‌تواند به دلیل معرفی چندین کلاس اضافی پیچیده‌تر شود. +> * استفاده بیش از حد می‌تواند کد را کمتر خوانا کند اگر پیچیدگی ایجاد اشیاء کم یا غیرضروری باشد. + +## الگوهای طراحی مرتبط با جاوا + +> * الگوی [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): می‌توان آن را نوعی factory در نظر گرفت که با گروهی از محصولات کار می‌کند. +> * الگوی [Singleton](https://java-design-patterns.com/patterns/singleton/): اغلب همراه با factory استفاده می‌شود تا اطمینان حاصل شود که یک کلاس تنها یک نمونه دارد. +> * الگوی [Builder](https://java-design-patterns.com/patterns/builder/): ساخت یک شیء پیچیده را از نمایش آن جدا می‌کند، مشابه نحوه‌ای که factoryها مدیریت نمونه‌سازی را انجام می‌دهند. +> * الگوی [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): یک factory از محتوای غیرقابل تغییر با رابط‌های builder و factory جداگانه است. + +## منابع و اعتبارات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) diff --git a/localization/fa/factory/etc/factory-sequence-diagram.png b/localization/fa/factory/etc/factory-sequence-diagram.png new file mode 100644 index 000000000000..260bea92f247 Binary files /dev/null and b/localization/fa/factory/etc/factory-sequence-diagram.png differ diff --git a/localization/pt/active-object/README.md b/localization/pt/active-object/README.md new file mode 100644 index 000000000000..07828f6fc28a --- /dev/null +++ b/localization/pt/active-object/README.md @@ -0,0 +1,127 @@ +--- +title: Active Object +category: Concurrency +language: pt +tag: + - Performance +--- + + +## Intenção +O padrão de design de objeto ativo separa a execução do método da invocação do método para objetos que residem em seu encadeamento de controle. O objetivo é introduzir simultaneidade, usando invocação de método assíncrono e um agendador para lidar com solicitações. + +## Explicação + +A classe que implementa o padrão de objeto ativo conterá um mecanismo de auto-sincronização sem usar métodos 'sincronizados'. + +Exemplo do mundo real + + +>Os Orcs são conhecidos por sua selvageria e alma indomável. Parece que eles têm seu próprio fio de controle com base no comportamento anterior. + +Para implementar uma criatura que possui seu próprio mecanismo de thread de controle e expor apenas sua API e não a execução em si, podemos usar o padrão Active Object. + + +**Exemplo programático** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Podemos ver que qualquer classe que estenderá a classe ActiveCreature terá seu próprio thread de controle para invocar e executar métodos. + +Por exemplo, a classe Orc: +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Agora, podemos criar várias criaturas, como Orcs, dizer-lhes para comer e vagar, e eles o executarão em seu próprio fio de controle: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Diagrama de classes + +![alt text](./etc/active-object.urm.png "Active Object class diagram") + +## Tutoriais + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/pt/delegation/README.md b/localization/pt/delegation/README.md new file mode 100644 index 000000000000..9f424895891d --- /dev/null +++ b/localization/pt/delegation/README.md @@ -0,0 +1,157 @@ +--- +title: "Delegation Pattern in Java: Mastering Efficient Task Assignment" +shortTitle: Delegation +description: "Explore the Delegation Design Pattern in Java with real-world examples, class diagrams, and its benefits. Learn how to enhance your code flexibility and reuse." +category: Behavioral +language: pt +tag: + - Decoupling + - Delegation + - Object composition +--- + +## Também conhecido como + +* Helper +* Surrogate + +## Propósito + +Permitir que um objeto delegue a responsabilidade por uma tarefa a outro objeto auxiliar. + +## Explicação + +Exemplo do mundo real + +> Em um restaurante, o chef principal delega tarefas aos sous-chefs: um cuida das grelhas, outro das saladas e um terceiro é responsável pelas sobremesas. Cada sous-chef é especializado em sua área, permitindo que o chef principal se concentre na gestão geral da cozinha. Isso reflete o padrão Delegation, no qual um objeto principal delega tarefas específicas a objetos auxiliares, cada um especialista em seu domínio. + +Em outras palavras + +> Delegation é um padrão de design em que um objeto repassa uma tarefa a um objeto auxiliar. + +De acordo com a Wikipédia + +> Em programação orientada a objetos, delegação se refere a avaliar um membro (propriedade ou método) de um objeto (o receptor) no contexto de outro objeto original (o remetente). A delegação pode ser feita explicitamente, passando o objeto remetente para o objeto receptor, o que pode ser feito em qualquer linguagem orientada a objetos; ou implicitamente, pelas regras de busca de membros da linguagem, o que exige suporte da linguagem para esse recurso. + +Diagrama de sequência + +![Delegation sequence diagram](../../../delegation/etc/delegation-sequence-diagram.png) + +## Exemplo Programático + +Vamos considerar um exemplo de impressão. + +Temos uma interface `Printer` e três implementações: `CanonPrinter`, `EpsonPrinter` e `HpPrinter`. + +```java +public interface Printer { + void print(final String message); +} + +@Slf4j +public class CanonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Canon Printer : {}", message); + } +} + +@Slf4j +public class EpsonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Epson Printer : {}", message); + } +} + +@Slf4j +public class HpPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("HP Printer : {}", message); + } +} +``` + +O `PrinterController` pode ser usado como um `Printer`, delegando qualquer trabalho tratado por essa interface a um objeto que a implemente. + +```java +public class PrinterController implements Printer { + + private final Printer printer; + + public PrinterController(Printer printer) { + this.printer = printer; + } + + @Override + public void print(String message) { + printer.print(message); + } +} +``` + +No código cliente, os controladores de impressora podem imprimir mensagens de formas diferentes, dependendo do objeto para o qual delegam esse trabalho. + +```java +public class App { + + private static final String MESSAGE_TO_PRINT = "hello world"; + + public static void main(String[] args) { + var hpPrinterController = new PrinterController(new HpPrinter()); + var canonPrinterController = new PrinterController(new CanonPrinter()); + var epsonPrinterController = new PrinterController(new EpsonPrinter()); + + hpPrinterController.print(MESSAGE_TO_PRINT); + canonPrinterController.print(MESSAGE_TO_PRINT); + epsonPrinterController.print(MESSAGE_TO_PRINT); + } +} +``` + +Saída do programa: + +``` +HP Printer:hello world +Canon Printer:hello world +Epson Printer:hello world +``` + +## Quando usar o padrão Delegation + +* Quando você deseja passar a responsabilidade de uma classe para outra sem usar herança. +* Para obter reutilização baseada em composição em vez de herança. +* Quando você precisa usar diversas classes auxiliares intercambiáveis em tempo de execução. + +## Aplicações do mundo real do padrão Delegation + +* O pacote java.awt.event do Java, no qual listeners são frequentemente usados para tratar eventos. +* Classes wrapper do Java Collections Framework (java.util.Collections), que delegam a outros objetos de coleção. +* No Spring Framework, a delegação é usada extensivamente no container IoC, no qual beans delegam tarefas a outros beans. + +## Benefícios e desafios do padrão Delegation + +Benefícios: + +* Reduz a criação de subclasses: os objetos podem delegar operações a objetos diferentes e alterá-los em tempo de execução, reduzindo a necessidade de criar subclasses. +* Incentiva a reutilização: a delegação promove a reutilização do código do objeto auxiliar. +* Aumenta a flexibilidade: ao delegar tarefas a objetos auxiliares, é possível alterar o comportamento das suas classes em tempo de execução. + +Desafios: + +* Sobrecarga em tempo de execução: a delegação pode introduzir camadas adicionais de indireção, o que pode resultar em pequenos custos de desempenho. +* Complexidade: o design pode se tornar mais complicado, pois envolve classes e interfaces adicionais para gerenciar a delegação. + +## Padrões relacionados + +* [Composite](https://java-design-patterns.com/patterns/composite/): a delegação pode ser usada dentro de um padrão composite para delegar comportamentos específicos de componentes a componentes filhos. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): a delegação é frequentemente usada no padrão strategy, no qual um objeto de contexto delega tarefas a um objeto de estratégia. +* https://java-design-patterns.com/patterns/proxy/: o padrão proxy é uma forma de delegação em que um objeto proxy controla o acesso a outro objeto, ao qual delega o trabalho. + +## Referências e Créditos + +* [Effective Java](https://amzn.to/4aGE7gX) +* [Head First Design Patterns](https://amzn.to/3J9tuaB) +* [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VOcRsw) +* [Delegate Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Delegation_pattern) diff --git a/localization/pt/money/README.md b/localization/pt/money/README.md new file mode 100644 index 000000000000..278924fb1315 --- /dev/null +++ b/localization/pt/money/README.md @@ -0,0 +1,131 @@ +--- +title: "Money Pattern in Java: Encapsulating Monetary Values with Currency Consistency" +shortTitle: Money +description: "Learn how the Money design pattern in Java ensures currency safety, precision handling, and maintainable financial operations. Explore examples, applicability, and benefits of the pattern." +category: Structural +language: pt +tag: + - Business + - Domain + - Encapsulation + - Immutable +--- + +## Também conhecido como + +* Monetary Value Object + +## Propósito + +Encapsular valores monetários e sua moeda associada em um objeto específico do domínio. + +## Explicação + +Exemplo do mundo real + +> Imagine um sistema de vale-presente on-line, no qual cada vale-presente mantém um saldo específico em uma determinada moeda. Em vez de usar apenas um valor de ponto flutuante para o saldo, o sistema usa um objeto Money para rastrear o valor e a moeda com precisão. Sempre que alguém usa o vale-presente, o saldo é atualizado com cálculos precisos que evitam erros de arredondamento de ponto flutuante, garantindo que a lógica de domínio permaneça consistente e correta. + +Em outras palavras + +> O padrão Money encapsula tanto um valor quanto sua moeda, garantindo que as operações financeiras sejam precisas, consistentes e fáceis de manter. + +De acordo com a Wikipédia + +> O padrão de design Money encapsula um valor monetário e sua moeda, permitindo operações aritméticas e conversões seguras, ao mesmo tempo em que preserva a precisão e a consistência nos cálculos financeiros. + +Mapa mental + +![Money Pattern Mind Map](../../../money/etc/money-mind-map.png) + +Fluxograma + +![Money Pattern Flowchart](../../../money/etc/money-flowchart.png) + +## Exemplo Programático + +Neste exemplo, criamos uma classe `Money` para demonstrar como valores monetários podem ser encapsulados junto com sua moeda. Essa abordagem ajuda a evitar imprecisões de ponto flutuante, garante que as operações aritméticas sejam tratadas de forma consistente e fornece uma maneira clara e centrada no domínio de trabalhar com dinheiro. + +```java +@AllArgsConstructor +@Getter +public class Money { + private double amount; + private String currency; + + public Money(double amnt, String curr) { + this.amount = amnt; + this.currency = curr; + } + + private double roundToTwoDecimals(double value) { + return Math.round(value * 100.0) / 100.0; + } + + public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException { + if (!moneyToBeAdded.getCurrency().equals(this.currency)) { + throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies"); + } + this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount()); + } + + public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException { + if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) { + throw new CannotSubtractException("You are trying to subtract two different currencies"); + } else if (moneyToBeSubtracted.getAmount() > this.amount) { + throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have"); + } + this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount()); + } + + public void multiply(int factor) { + if (factor < 0) { + throw new IllegalArgumentException("Factor must be non-negative"); + } + this.amount = roundToTwoDecimals(this.amount * factor); + } + + public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) { + if (exchangeRate < 0) { + throw new IllegalArgumentException("Exchange rate must be non-negative"); + } + this.amount = roundToTwoDecimals(this.amount * exchangeRate); + this.currency = currencyToChangeTo; + } +} +``` + +Ao encapsular toda a lógica relacionada a dinheiro em uma única classe, reduzimos o risco de misturar moedas diferentes, melhoramos a clareza do código-base e facilitamos futuras modificações, como adicionar novas moedas ou refinar as regras de arredondamento. Esse padrão fortalece o modelo de domínio ao tratar o dinheiro como um conceito distinto, e não apenas como mais um valor numérico. + +## Quando usar o padrão Money + +* Quando cálculos financeiros ou manipulações de dinheiro fazem parte da lógica de negócio +* Quando é necessário um tratamento preciso de valores monetários para evitar imprecisões de ponto flutuante +* Quando princípios de domain-driven design e tipagem forte são desejados + +## Aplicações do mundo real do padrão Money + +* A biblioteca JSR 354 (Java Money and Currency) em Java +* Modelos de domínio personalizados em sistemas de e-commerce e contabilidade + +## Benefícios e desafios do padrão Money + +Benefícios + +* Fornece uma representação única e type-safe para valores monetários e moeda +* Incentiva o encapsulamento de operações relacionadas, como adição, subtração e formatação +* Evita erros de ponto flutuante ao usar inteiros ou bibliotecas decimais especializadas + +Desafios + +* Requer classes e infraestrutura adicionais para lidar com conversões e formatação de moeda +* Pode introduzir sobrecarga de desempenho ao realizar um grande número de operações monetárias + +## Padrões relacionados + +* [Value Object](https://java-design-patterns.com/patterns/value-object/): Money é tipicamente um exemplo clássico de value object em domain-driven design. + +## Referências e Créditos + +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) +* [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/localization/pt/polling-publisher/README.md b/localization/pt/polling-publisher/README.md new file mode 100644 index 000000000000..d9cf98a550b3 --- /dev/null +++ b/localization/pt/polling-publisher/README.md @@ -0,0 +1,119 @@ +--- +title: "Polling Publisher-Subscriber Pattern in Java: Mastering Asynchronous Messaging Elegantly" +shortTitle: Polling Pub/Sub +description: "Learn how to implement a Polling Publisher-Subscriber system in Java using Spring Boot and Kafka. Explore the architecture, real-world analogies, and benefits of asynchronous communication with clean code examples." +category: Architectural +language: pt +tag: + - Spring Boot + - Kafka + - Microservices + - Asynchronous Messaging + - Decoupling +--- + +## Também conhecido como + +* Event-Driven Architecture +* Asynchronous Pub/Sub Pattern +* Message Queue-Based Polling System + +## Propósito + +O padrão Polling Publisher-Subscriber desacopla os produtores de dados dos consumidores ao permitir uma comunicação assíncrona e orientada a mensagens. Um serviço consulta periodicamente (poll) uma fonte de dados e publica mensagens em um message broker (por exemplo, Kafka), que são então consumidas por um ou mais serviços assinantes. + +## Explicação + +### Exemplo do mundo real + +> Uma agência de notícias consulta constantemente as últimas atualizações. Assim que recebe novas informações, ela as publica em diferentes veículos (TV, jornais, aplicativos). Cada veículo consome e exibe as atualizações de forma independente. + +### Em outras palavras + +> Um serviço verifica regularmente se há atualizações (polling) e envia mensagens para o Kafka. Outro serviço escuta o Kafka e processa as mensagens de forma assíncrona. + +### De acordo com a Wikipédia + +> Este padrão se assemelha muito ao [modelo Publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern), no qual as mensagens são enviadas pelos publicadores e recebidas pelos assinantes sem que eles se conheçam. + +### Fluxo da arquitetura + +``` ++------------+ +--------+ +-------------+ +| Publisher | ---> | Kafka | ---> | Subscriber | ++------------+ +--------+ +-------------+ +``` + +## Exemplo Programático (Spring Boot + Kafka) + +### Serviço Publisher + +- Usa o `@Scheduled` do Spring para consultar dados periodicamente. +- Publica dados em um tópico do Kafka. +- Opcionalmente expõe uma API REST para publicação manual de dados. + +```java +@Scheduled(fixedRate = 5000) +public void pollAndPublish() { + String data = pollingService.getLatestData(); + kafkaTemplate.send("updates-topic", data); +} +``` + +### Serviço Subscriber + +- Escuta um tópico do Kafka usando `@KafkaListener`. +- Processa as mensagens de forma assíncrona. + +```java +@KafkaListener(topics = "updates-topic") +public void processUpdate(String message) { + log.info("Received update: {}", message); + updateProcessor.handle(message); +} +``` + +## Quando usar o padrão Polling Publisher-Subscriber + +Use esse padrão quando: + +* Não é possível o produtor enviar dados em tempo real (push). +* Deseja-se um baixo acoplamento entre produtores e consumidores. +* É necessário processamento de eventos assíncrono e escalável. +* Você está construindo uma arquitetura de microsserviços orientada a eventos. + +## Aplicações do mundo real + +* Painéis de relatórios em tempo real +* Agregadores de health check para sistemas distribuídos +* Processamento de telemetria de IoT +* Sistemas de notificação e alerta + +## Benefícios e desafios do padrão Polling Pub/Sub + +### Benefícios + +* Baixo acoplamento entre serviços +* Arquitetura assíncrona e escalável +* Tolerante a falhas, com persistência de mensagens no Kafka +* Fácil de estender com novos consumidores ou publicadores + +### Desafios + +* O polling introduz latência entre a geração e o consumo dos dados +* Requer o gerenciamento e a configuração do Kafka (ou de outro broker) +* Implantação e infraestrutura ligeiramente mais complexas + +## Padrões relacionados + +* [Observer Pattern](https://java-design-patterns.com/patterns/observer/) +* [Mediator Pattern](https://java-design-patterns.com/patterns/mediator/) +* [Message Queue Pattern](https://java-design-patterns.com/patterns/event-queue/) + +## Referências e Créditos + +* [Apache Kafka Documentation](https://kafka.apache.org/documentation/) +* [Spring Kafka Documentation](https://docs.spring.io/spring-kafka) +* [Spring Scheduled Tasks](https://www.baeldung.com/spring-scheduled-tasks) +* [Spring Kafka Tutorial – Baeldung](https://www.baeldung.com/spring-kafka) +* Inspired by: [iluwatar/java-design-patterns](https://github.com/iluwatar/java-design-patterns) diff --git a/localization/zh-TW/README.md b/localization/zh-TW/README.md new file mode 100644 index 000000000000..f7748a7c6208 --- /dev/null +++ b/localization/zh-TW/README.md @@ -0,0 +1,42 @@ + + +# 設計模式Java版 + +![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) [](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)![License MIT](https://img.shields.io/badge/license-MIT-blue.svg) [](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg) [](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status) + +# 介紹 + +設計模式是程式設計師在設計應用程式或系統時,可以用來解決常見問題的最佳且具形式化的實踐方法。 + +設計模式能透過提供經過測試與驗證的開發範式,加快開發流程。 + +重複使用設計模式有助於避免那些可能導致重大問題的細微錯誤,同時也能提升程式碼的可讀性,讓熟悉這些模式的開發人員與架構師更容易理解。 + +# 入門 + +這個網站展示了 Java 設計模式。這些解決方案由開放原始碼社群中有經驗的程式設計師與架構師所開發。使用者可以透過高層次的描述來瀏覽這些模式,或是直接查看其原始碼。程式碼範例都有詳細的註解,可以視為實作特定設計模式的教學範本。我們使用的是最受歡迎且經過實戰驗證的開放原始碼 Java 技術。 + +在深入學習這些內容之前,你應該先熟悉各種[軟體設計原則](https://java-design-patterns.com/principles/). + +所有設計都應盡可能簡單。建議先從 KISS(Keep It Simple, Stupid)、YAGNI(You Aren’t Gonna Need It)以及 Do The Simplest Thing That Could Possibly Work 這些原則開始。只有在實際需要擴充性時,才應該引入複雜性與設計模式。 + +熟悉了這些概念,就可以透過以下任一種方式深入研究可用的設計模式: + +- 依名稱搜尋特定模式。找不到的話?請[在這裡](https://github.com/iluwatar/java-design-patterns/issues)回報新模式。 +- 使用難度標籤: `Performance(效能)` , `Gang of Four(四人幫)`和`Data access(資料存取)` 。 +- 使用模式分類`Creational(建立型)` ,`Behavioral(行為型)`和其他类别。 + + +希望你能在這個網站上找到對你的架構有幫助的物件導向解決方案,並且在學習的過程中和我們開發這些方案時一樣感到愉快。 + +# 如何做出貢獻 + +如果你願意為這個專案做出貢獻,你可以在我們的[開發者 Wiki](https://github.com/iluwatar/java-design-patterns/wiki)找到相關資訊。我們也會在[Gitter聊天室](https://gitter.im/iluwatar/java-design-patterns)中協助你並回答你的問題。 + +# 許可證 + +該項目使用麻省理工學院許可證。 + + diff --git a/localization/zh/abstract-document/README.md b/localization/zh-TW/abstract-document/README.md similarity index 68% rename from localization/zh/abstract-document/README.md rename to localization/zh-TW/abstract-document/README.md index cf19dfcf84cb..f71ff845a97f 100644 --- a/localization/zh/abstract-document/README.md +++ b/localization/zh-TW/abstract-document/README.md @@ -2,34 +2,34 @@ title: Abstract Document shortTitle: Abstract Document category: Structural -language: zh +language: zh-TW tag: - Extensibility --- ## 目的 -使用动态属性,并在保持类型安全的同时实现非类型化语言的灵活性。 +使用動態屬性,並在保持型別安全的同時實現非型別化語言的靈活性。 -## 解释 +## 解釋 -抽象文档模式使您能够处理其他非静态属性。 此模式使用特征的概念来实现类型安全,并将不同类的属性分离为一组接口。 +抽象文件模式 (Abstract Document Pattern) 使您能夠處理其他非靜態屬性。此模式使用特性 (trait) 的概念來實現型別安全,並將不同類別的屬性分離為一組介面。 -真实世界例子 +真實世界範例 -> 考虑由多个部分组成的汽车。 但是,我们不知道特定汽车是否真的拥有所有零件,或者仅仅是零件中的一部分。 我们的汽车是动态而且非常灵活的。 +> 考慮由多個部分組成的汽車。但是,我們不知道特定汽車是否真的擁有所有零件,或者僅僅是零件中的一部分。我們的汽車是動態而且非常靈活的。 -通俗的说 +簡單的說 -> 抽象文档模式允许在对象不知道的情况下将属性附加到对象。 +> 抽象文件模式允許在物件不知道的情況下將屬性附加到物件上。 -维基百科说 +維基百科說 -> 面向对象的结构设计模式,用于组织松散类型的键值存储中的对象并使用类型化的视图公开数据。 该模式的目的是在强类型语言中实现组件之间的高度灵活性,在这种语言中,可以在不丢失类型安全支持的情况下,将新属性动态地添加到对象树中。 该模式利用特征将类的不同属性分成不同的接口。 +> 物件導向的結構設計模式,用於組織鬆散型別的鍵值儲存中的物件,並使用型別化的視圖公開資料。該模式的目的是在強型別語言中實現元件之間的高度靈活性,在這種語言中,可以在不遺失型別安全支援的情況下,將新屬性動態地新增到物件樹中。該模式利用特性 (trait) 將類別的不同屬性分成不同的介面。 -**程序示例** +**程式碼範例** -让我们首先定义基类`Document`和`AbstractDocument`。 它们基本上使对象拥有属性映射和任意数量的子对象。 +讓我們先定義基礎類別`Document`和`AbstractDocument`。 它們基本上使物件擁有屬性對映 (map) 和任意數量的子物件。 ```java public interface Document { @@ -74,7 +74,7 @@ public abstract class AbstractDocument implements Document { ... } ``` -接下来,我们定义一个枚举“属性”和一组类型,价格,模型和零件的接口。 这使我们能够为Car类创建静态外观的界面。 +接下來,我們定義一個列舉 `Property` 和一組關於型別、價格、模型和零件的介面。這使我們能夠為 `Car` 類別創建靜態外觀的介面。 ```java public enum Property { @@ -110,7 +110,7 @@ public interface HasParts extends Document { } ``` -现在我们准备介绍`Car`。 +現在我們準備介紹`Car`。 ```java public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { @@ -121,7 +121,7 @@ public class Car extends AbstractDocument implements HasModel, HasPrice, HasPart } ``` -最后是完整示例中的`Car`构造和使用方式。 +最後是完整範例中 `Car`的建構和使用方式。。 ```java LOGGER.info("Constructing parts and car"); @@ -162,19 +162,21 @@ public class Car extends AbstractDocument implements HasModel, HasPrice, HasPart // door/Lambo/300 ``` -## 类图 +## 類別圖 ![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") -## 适用性 +## 適用性 -使用抽象文档模式当 +在以下情況使用抽象文件模式: -* 需要即时添加新属性 -* 你想要一种灵活的方式来以树状结构组织域 -* 你想要更宽松的耦合系统 +* 需要即時新增新屬性時 -## 鸣谢 +* 想要一種靈活的方式以樹狀結構組織領域 (domain) 時 + +* 想要一個更鬆散耦合的系統時 + +## 參考資料和來源 * [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) * [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) diff --git a/localization/zh/abstract-document/etc/abstract-document.png b/localization/zh-TW/abstract-document/etc/abstract-document.png similarity index 100% rename from localization/zh/abstract-document/etc/abstract-document.png rename to localization/zh-TW/abstract-document/etc/abstract-document.png diff --git a/localization/zh-TW/abstract-factory/README.md b/localization/zh-TW/abstract-factory/README.md new file mode 100644 index 000000000000..414c1a8f0100 --- /dev/null +++ b/localization/zh-TW/abstract-factory/README.md @@ -0,0 +1,229 @@ +--- +title: Abstract Factory +shortTitle: Abstract Factory +category: Structural +language: zh-TW +tag: + - Extensibility +--- + +## 別稱 + +* Kit (套件) + +## 抽象工廠設計模式的意圖 + +Java 中的抽象工廠模式 (Abstract Factory pattern) 提供一個介面,用於創建一系列相關或相依的物件家族,而無需指定其具體類別,從而增強了軟體設計的模組化與靈活性。 + +## 抽象工廠模式的詳細解釋與真實世界範例 + +真實世界範例 + +> 想像一家傢俱公司,它使用 Java 中的抽象工廠模式來生產多種風格的傢俱:現代風、維多利亞風和鄉村風。每種風格都包含椅子、桌子和沙發等產品。為了確保每種風格內部的一致性,該公司使用了抽象工廠模式。 +> +> 在這個情境中,抽象工廠是一個用於創建相關傢俱物件家族(椅子、桌子、沙發)的介面。每個具體工廠(ModernFurnitureFactory、VictorianFurnitureFactory、RusticFurnitureFactory)都實作了這個抽象工廠介面,並創建一組符合特定風格的產品。如此一來,客戶端就可以創建一整套現代或維多利亞風格的傢俱,而無需擔心其實例化的細節。這不僅保持了風格的一致性,也讓更換不同風格的傢俱變得輕而易舉。 + +簡單來說 + +> 工廠中的工廠;一個將個別但相關/相依的工廠群組在一起,而無需指定其具體類別的工廠。 + +維基百科說 + +> 抽象工廠模式提供了一種方法,可以封裝一組具有共通主題的獨立工廠,而無需指定它們的具體類別。 + +類別圖 + +![Abstract Factory class diagram](./etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## Java 中的抽象工廠程式碼範例 + +為了使用抽象工廠模式來創建一個王國,我們需要具有共通主題的物件。精靈王國需要精靈國王、精靈城堡和精靈軍隊;而獸人王國則需要獸人國王、獸人城堡和獸人軍隊。王國中的這些物件之間存在著相依性。 + +將上述的王國範例轉換為程式碼。首先,我們為王國中的物件定義一些介面和實作。 + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Elven implementations -> +public class ElfCastle implements Castle { + static final String DESCRIPTION = "This is the elven castle!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfKing implements King { + static final String DESCRIPTION = "This is the elven king!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class ElfArmy implements Army { + static final String DESCRIPTION = "This is the elven Army!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Orcish implementations similarly -> ... +``` + +接著,我們為王國工廠定義抽象和實作。 + +```java +public interface KingdomFactory { + Castle createCastle(); + + King createKing(); + + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +// 獸人 (Orcish) 的實作也類似 -> ... +``` +現在,我們可以為我們不同的王國工廠設計一個工廠。在這個範例中,我們創建了 `FactoryMaker`,它負責返回 `ElfKingdomFactory` 或 O`OrcKingdomFactory` 的實例。客戶端可以使用 `FactoryMaker` 來創建所需的具體工廠,而該工廠又會生產出不同的具體物件(繼承自 `Army`, `King`, `Castle`)。在這個範例中,我們還使用了一個 enum 來參數化客戶端將請求哪種類型的王國工廠。 + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + }; + } +} +``` + +這是我們範例應用程式的主函式: + +```java +LOGGER.info("elf kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); + +LOGGER.info("orc kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); +``` + +程式輸出: + +``` +07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king! +``` + +## 在 Java 中何時使用抽象工廠模式 +在 Java 中,當您遇到以下情況時,請使用抽象工廠模式:: + +* 系統應與其產品的創建、組合和表示方式無關。 + +* 您需要用多個產品家族中的其中一個來配置系統。 + +* 必須同時使用一系列相關的產品物件,以強制保持一致性。 + +* 您希望提供一個產品的類別庫,只暴露它們的介面,而不是它們的實作。 + +* 相依物件的生命週期比消費者的生命週期短。 + +* 相依物件需要使用執行時期的值或參數來建構。 + +* 您需要在執行時期從一個家族中選擇要使用的產品。 + +* 新增新產品或家族時,不應要求修改現有程式碼。 + +## Java 抽象工廠模式教學 + +* [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java) +* [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory) + +## 抽象工廠模式的優點與權衡 + +優點: + +* 靈活性:無需修改程式碼即可輕鬆切換產品家族。 + +* 解耦:客戶端程式碼只與抽象介面互動,提升了可移植性和可維護性。 + +* 可重用性:抽象工廠和產品有助於跨專案的元件重用。 + +* 可維護性:對個別產品家族的變更是局部的,簡化了更新過程。 + +權衡: + +* 複雜性:定義抽象介面和具體工廠會增加初期的開發開銷。 + +* 間接性:客戶端程式碼透過工廠間接與產品互動,可能會降低透明度。 + +## Java 中抽象工廠模式的實際應用 + +* Java Swing 的 `LookAndFeel` 類別,用於提供不同的外觀與感覺選項。 + +* Java Abstract Window Toolkit (AWT) 中的各種實作,用於創建不同的 GUI 元件。 + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## 相關的 Java 設計模式 + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): 抽象工廠使用工廠方法來創建產品。 +* [Singleton](https://java-design-patterns.com/patterns/singleton/): 抽象工廠類別通常被實作為單例 +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): 與抽象工廠類似,但更專注於以靈活的方式配置和管理一組相關物件。 + +## 參考資料與致謝 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Design Patterns in Java](https://amzn.to/3Syw0vC) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U) diff --git a/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.png b/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.puml b/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.puml new file mode 100644 index 000000000000..999091ef54f6 --- /dev/null +++ b/localization/zh-TW/abstract-factory/etc/abstract-factory.urm.puml @@ -0,0 +1,101 @@ +@startuml +package com.iluwatar.abstractfactory { + class App { + - LOGGER : Logger {static} + - army : Army + - castle : Castle + - king : King + + App() + + createKingdom(factory : KingdomFactory) + + getArmy() : Army + ~ getArmy(factory : KingdomFactory) : Army + + getCastle() : Castle + ~ getCastle(factory : KingdomFactory) : Castle + + getKing() : King + ~ getKing(factory : KingdomFactory) : King + + main(args : String[]) {static} + - setArmy(army : Army) + - setCastle(castle : Castle) + - setKing(king : King) + } + class FactoryMaker { + + FactoryMaker() + + makeFactory(type : KingdomType) : KingdomFactory {static} + } + enum KingdomType { + + ELF {static} + + ORC {static} + + valueOf(name : String) : KingdomType {static} + + values() : KingdomType[] {static} + } + interface Army { + + getDescription() : String {abstract} + } + interface Castle { + + getDescription() : String {abstract} + } + class ElfArmy { + ~ DESCRIPTION : String {static} + + ElfArmy() + + getDescription() : String + } + class ElfCastle { + ~ DESCRIPTION : String {static} + + ElfCastle() + + getDescription() : String + } + class ElfKing { + ~ DESCRIPTION : String {static} + + ElfKing() + + getDescription() : String + } + class ElfKingdomFactory { + + ElfKingdomFactory() + + createArmy() : Army + + createCastle() : Castle + + createKing() : King + } + interface King { + + getDescription() : String {abstract} + } + interface KingdomFactory { + + createArmy() : Army {abstract} + + createCastle() : Castle {abstract} + + createKing() : King {abstract} + } + class OrcArmy { + ~ DESCRIPTION : String {static} + + OrcArmy() + + getDescription() : String + } + class OrcCastle { + ~ DESCRIPTION : String {static} + + OrcCastle() + + getDescription() : String + } + class OrcKing { + ~ DESCRIPTION : String {static} + + OrcKing() + + getDescription() : String + } + class OrcKingdomFactory { + + OrcKingdomFactory() + + createArmy() : Army + + createCastle() : Castle + + createKing() : King + } +} +KingdomType ..+ FactoryMaker +App --> "-castle" Castle +FactoryMaker ..+ App +App --> "-king" King +App --> "-army" Army +ElfArmy ..|> Army +ElfCastle ..|> Castle +ElfKing ..|> King +ElfKingdomFactory ..|> KingdomFactory +OrcArmy ..|> Army +OrcCastle ..|> Castle +OrcKing ..|> King +OrcKingdomFactory ..|> KingdomFactory +@enduml \ No newline at end of file diff --git a/localization/zh-TW/active-object/README.md b/localization/zh-TW/active-object/README.md new file mode 100644 index 000000000000..7ed92bef3244 --- /dev/null +++ b/localization/zh-TW/active-object/README.md @@ -0,0 +1,123 @@ +--- +title: Active Object +shortTitle: Active Object +category: Concurrency +language: zh-TW +tag: + - Performance +--- + + +## 目的 +主動式物件設計模式 (Active Object Design Pattern) 將物件的方法執行與方法呼叫脫鉤,每個物件都駐留在其自身的控制執行緒中。其目的是透過使用非同步方法呼叫和用於處理請求的排程器來引入並行性 (concurrency)。 + +## 解釋 + +實作主動式物件模式的類別將包含自我同步機制,而無需使用 synchronized 方法。 + +真實世界範例 + +>獸人以其野性和頑強的靈魂而著稱。牠們的行為似乎由一個獨立的控制執行緒所驅動,該執行緒基於先前的動作做出反應。 + +為了實作出一個擁有自身控制執行緒、僅公開其 API 而不暴露其執行細節的物件,我們可以使用主動式物件模式。 + +**程序示例** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam and the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +我們可以看到,任何繼承 ActiveCreature 的類別都將擁有自己的控制執行緒來執行和呼叫方法。 + +如,Orc (獸人) 類別: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +現在,我們可以建立多個生物 (例如獸人),命令牠們進食和漫遊,然後牠們將在各自的控制執行緒上執行這些動作: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## 類別圖 + +![alt text](./etc/active-object.urm.png "Active Object class diagram") diff --git a/localization/zh-TW/active-object/etc/active-object.urm.png b/localization/zh-TW/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/zh-TW/active-object/etc/active-object.urm.png differ diff --git a/localization/zh-TW/actor-model/README.md b/localization/zh-TW/actor-model/README.md new file mode 100644 index 000000000000..652696ce8931 --- /dev/null +++ b/localization/zh-TW/actor-model/README.md @@ -0,0 +1,193 @@ +--- +title: Actor Model +shortTitle: Actor Model +category: Concurrency +language: zh-TW +tag: + - Performance +--- + +## 亦稱為 + +- 訊息傳遞並行 (Message-passing concurrency) + +- 基於 Actor 的並行 (Actor-based concurrency) + +--- + +## Actor Model 模式的意圖 +Actor Model 模式利用隔離的元件 (actor),透過非同步訊息傳遞進行互動,來建構高並行、分散式和容錯的系統。 + +--- + +## Actor Model 模式的詳細解釋與真實世界範例 + +### 📦 現實世界範例 + +想像一個客戶服務系統: +- 每一位 **客戶支援專員** 都是一個**actor**. +- 客戶 **傳送問題 (訊息) ** 給專員。 +- 每位專員一次處理一個請求,並且能夠 **非同步地回覆** 而不會干擾到其他專員。 + +--- + +### 🧠 白話解釋 + +> 「Actors 就像是獨立的工人,從不共享記憶體,只透過訊息來溝通。」 + +--- + +### 📖 維基百科說 + +> [Actor model](https://en.wikipedia.org/wiki/Actor_model) 是一種並行運算的數學模型,將「actor」視為並行運算的普世基本元素。 + +--- + +### 🧹 架構圖 + +![UML Class Diagram](./etc/Actor_Model_UML_Class_Diagram.png) + +--- + +## Java 的 Actor Model 模式程式範例 + +### Actor.java + +```java +public abstract class Actor implements Runnable { + + @Setter @Getter private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = true; + + + public void send(Message message) { + mailbox.add(message); + } + + public void stop() { + active = false; + } + + @Override + public void run() { + + } + + protected abstract void onReceive(Message message); +} + +``` + +### Message.java + +```java + +@AllArgsConstructor +@Getter +@Setter +public class Message { + private final String content; + private final String senderId; +} +``` + +### ActorSystem.java + +```java +public class ActorSystem { + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} +``` + +### App.java + +```java +public class App { + public static void main(String[] args) { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} +``` + +--- + +## 何時在 Java 中使用 Actor Model 模式 +- 建立 **並行或分散式系統**時 +- 您希望 **沒有共享的可變狀態**時 +- 你需要 **非同步、訊息驅動的通訊**時 +- 元件應 **隔離且鬆散耦合** + +--- + +## Actor Model 模式的 Java 教學 + +- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka) +- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143) + +--- + +## Actor Model 模式的真實世界應用 + +- [Akka 框架](https://akka.io/) +- [Erlang and Elixir concurrency](https://www.erlang.org/) +- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/) +- J基於 JVM 的遊戲引擎和模擬器。 + +--- + +## Actor Model 模式的優點與權衡 + +### ✅ 優點 +- 支援高並行性。 +- 易於跨執行緒或機器進行擴展。 +- 容錯隔離與恢復。 +- 保證 Actor 內部的訊息順序。 + +### ⚠️ 權衡 +- 由於非同步行為,偵錯更困難。 +- 由於訊息佇列,會有輕微的效能開銷。 +- 設計上比簡單的方法呼叫更複雜。 +--- + +## 相關的 Java 設計模式 + +- [Command Pattern](../command) +- [Mediator Pattern](../mediator) +- [Event-Driven Architecture](../event-driven-architecture) +- [Observer Pattern](../observer) + +--- + +## 參考資料與致謝 + +- *Programming Erlang*, Joe Armstrong +- *Reactive Design Patterns*, Roland Kuhn +- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/) +- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html) + diff --git a/localization/zh-TW/actor-model/etc/Actor_Model_UML_Class_Diagram.png b/localization/zh-TW/actor-model/etc/Actor_Model_UML_Class_Diagram.png new file mode 100644 index 000000000000..a4c34d7a75fd Binary files /dev/null and b/localization/zh-TW/actor-model/etc/Actor_Model_UML_Class_Diagram.png differ diff --git a/localization/zh-TW/actor-model/etc/actor-model.urm.puml b/localization/zh-TW/actor-model/etc/actor-model.urm.puml new file mode 100644 index 000000000000..020c1fc735a4 --- /dev/null +++ b/localization/zh-TW/actor-model/etc/actor-model.urm.puml @@ -0,0 +1,35 @@ +@startuml actor-model + +title Actor Model - UML Class Diagram + +class ActorSystem { + +actorOf(actor: Actor): Actor + +shutdown(): void +} + +class Actor { + -mailbox: BlockingQueue + -active: boolean + +send(message: Message): void + +stop(): void + +run(): void + #onReceive(message: Message): void +} + +class ExampleActor { + +onReceive(message: Message): void +} + +class Message { + -content: String + -sender: Actor + +getContent(): String + +getSender(): Actor +} + +ActorSystem --> Actor : creates +Actor <|-- ExampleActor : extends +Actor --> Message : processes +ExampleActor --> Message : uses + +@enduml diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java index b6b6da79faae..2e822606ec3b 100644 --- a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java @@ -73,6 +73,11 @@ public class Main { * @param args command line args */ public static void main(String[] args) { - SpringApplication.run(Main.class, args); + var context = SpringApplication.run(Main.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } } diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java index 97f9295ff0c1..70e1e3809181 100644 --- a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java @@ -32,6 +32,6 @@ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[] {})); + assertDoesNotThrow(() -> Main.main(new String[] {"test"})); } } diff --git a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java index 506096f4e909..b3be47acc2cd 100644 --- a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java +++ b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java @@ -72,6 +72,11 @@ public class Main { * @param args command line args */ public static void main(String[] args) { - SpringApplication.run(Main.class, args); + var context = SpringApplication.run(Main.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } } diff --git a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java index 2b500440ebc0..87d019da4c3a 100644 --- a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java +++ b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java @@ -32,6 +32,6 @@ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[] {})); + assertDoesNotThrow(() -> Main.main(new String[] {"test"})); } } diff --git a/microservices-distributed-tracing/pom.xml b/microservices-distributed-tracing/pom.xml index c7dddf0fa0b6..fa9e288879f1 100644 --- a/microservices-distributed-tracing/pom.xml +++ b/microservices-distributed-tracing/pom.xml @@ -52,7 +52,7 @@ io.zipkin.reporter2 zipkin-reporter-brave - 3.5.0 + 3.5.3 org.junit.jupiter diff --git a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java index 91e41631c190..60ef23d6def2 100644 --- a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java +++ b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java @@ -72,6 +72,11 @@ public class Main { * @param args command line args */ public static void main(String[] args) { - SpringApplication.run(Main.class, args); + var context = SpringApplication.run(Main.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } } diff --git a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java index 1534943abd02..8dee84dcbdf1 100644 --- a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java +++ b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java @@ -33,6 +33,6 @@ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[] {})); + assertDoesNotThrow(() -> Main.main(new String[] {"test"})); } } diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java index fe099eab415f..414e7166c11f 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java @@ -45,7 +45,12 @@ @Slf4j public class App { public static void main(String[] args) { - SpringApplication.run(App.class, args); + var context = SpringApplication.run(App.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } /** diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java index f6cd88e0f505..e00b1aad7ade 100644 --- a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java @@ -40,7 +40,7 @@ class AppTest { @Test void testMain() { - assertDoesNotThrow(() -> App.main(new String[] {})); + assertDoesNotThrow(() -> App.main(new String[] {"test"})); } @Test diff --git a/microservices-messaging/README.md b/microservices-messaging/README.md new file mode 100644 index 000000000000..3ca95350e2a8 --- /dev/null +++ b/microservices-messaging/README.md @@ -0,0 +1,247 @@ +--- +title: "Microservices Messaging Pattern in Java: Enabling Asynchronous Communication Between Services" +shortTitle: Microservices Messaging +description: "Learn about the Microservices Messaging pattern, a method for enabling asynchronous communication between services through message brokers to enhance decoupling, scalability, and fault tolerance in distributed systems." +category: Integration +language: en +tag: + - API design + - Asynchronous + - Cloud distributed + - Decoupling + - Enterprise patterns + - Event-driven + - Messaging + - Microservices + - Scalability +--- +## Also known as + +* Asynchronous Messaging +* Event-Driven Communication +* Message-Oriented Middleware (MOM) + +## Intent of Microservices Messaging Design Pattern + +The Microservices Messaging pattern enables asynchronous communication between microservices through message passing, allowing for better decoupling, scalability, and fault tolerance. Services communicate by exchanging messages over messaging channels managed by a message broker. + +## Detailed Explanation of Microservices Messaging Pattern with Real-World Examples + +Real-world example + +> Imagine an e-commerce platform where a customer places an order. The Order Service publishes an "Order Created" message to a message broker. Multiple services listen to this message: the Inventory Service updates stock levels, the Payment Service processes payment, and the Notification Service sends confirmation emails. Each service operates independently, processing messages at its own pace without blocking others. If the Payment Service is temporarily down, the message broker holds the message until it recovers, ensuring no data is lost. + +In plain words + +> The Microservices Messaging pattern allows services to communicate asynchronously through a message broker, enabling them to work independently without waiting for each other. + +Wikipedia says + +> Message-oriented middleware is software or hardware infrastructure supporting sending and receiving messages between distributed systems. MOM allows application modules to be distributed over heterogeneous platforms and reduces the complexity of developing applications that span multiple operating systems and network protocols. + +Flowchart + +![Microservices Messaging flowchart](./etc/microservices-messaging-flowchart.png) + + + +## Programmatic Example of Microservices Messaging Pattern in Java + + +The Microservices Messaging pattern demonstrates how services communicate through a message broker without direct coupling. In this example, we show an order processing system where services exchange messages asynchronously. + +The `Message` class represents the data exchanged between services. + +```java +public class Message { + private final String id; + private final String content; + private final LocalDateTime timestamp; + + public Message(String content) { + this.id = UUID.randomUUID().toString(); + this.content = content; + this.timestamp = LocalDateTime.now(); + } + + // Getters +} +``` + +The `MessageBroker` acts as the intermediary that routes messages between producers and consumers. + +```java +public class MessageBroker { + private final Map subscribers = new ConcurrentHashMap<>(); + + public void subscribe(String topic, Consumer handler) { + subscribers.computeIfAbsent(topic, k -> new ArrayList<>()).add(handler); + } + + public void publish(String topic, Message message) { + List handlers = subscribers.get(topic); + if (handlers != null) { + handlers.forEach(handler -> handler.accept(message)); + } + } +} +``` + +The `OrderService` is a message producer that publishes order messages. + +```java +public class OrderService { + private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class); + private final MessageBroker broker; + + public OrderService(MessageBroker broker) { + this.broker = broker; + } + + public void createOrder(String orderId) { + Message message = new Message("Order Created: " + orderId); + broker.publish("order-topic", message); + LOGGER.info("Published order message: {}", orderId); + } +} +``` + +The `InventoryService` is a message consumer that processes inventory updates. + +```java +public class InventoryService { + private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class); + + public void handleMessage(Message message) { + LOGGER.info("Inventory Service received: {}", message.getContent()); + LOGGER.info("Updating inventory..."); + } +} +``` + +The `PaymentService` handles payment processing messages. + +```java +public class PaymentService { + private static final Logger LOGGER = LoggerFactory.getLogger(PaymentService.class); + + public void handleMessage(Message message) { + LOGGER.info("Payment Service received: {}", message.getContent()); + LOGGER.info("Processing payment..."); + } +} +``` + +The `main` application demonstrates the messaging pattern in action. + +```java +public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void main(String[] args) throws InterruptedException { + final MessageBroker broker = new MessageBroker(); + + final InventoryService inventoryService = new InventoryService(); + final PaymentService paymentService = new PaymentService(); + + broker.subscribe("order-topic", inventoryService::handleMessage); + broker.subscribe("order-topic", paymentService::handleMessage); + + final OrderService orderService = new OrderService(broker); + + orderService.createOrder("ORDER-123"); + + Thread.sleep(1000); + } +} +``` + +Console output: + +``` +Published order message: ORDER-123 +Inventory Service received: Order Created: ORDER-123 +Updating inventory... +Payment Service received: Order Created: ORDER-123 +Processing payment... +``` + +Sequence Diagram + +![Microservices Messaging sequence_diagram](./etc/microservices-messaging-sequence-diagram.png) + +## How to Run the Application + +### Option 1: Automated Script (Recommended) + +Run the helper script from the module directory, which automatically starts Kafka via Docker Compose (if Docker is installed and Kafka is not already running) and launches the application: + +* **Windows (PowerShell)**: + ```powershell + powershell -ExecutionPolicy Bypass -File .\run-app.ps1 + ``` +* **Linux / macOS**: + ```bash + ./run-app.sh + ``` + +### Option 2: Docker Compose + +Start the Kafka container manually via Docker Compose and run the application: + +```bash +# Start Kafka container on port 9092 +docker compose up -d + +# Run the application +../mvnw compile exec:java -Dexec.mainClass="com.iluwatar.messaging.App" + +# Stop Kafka container when finished +docker compose down +``` + +## When to Use the Microservices Messaging Pattern in Java + +* When services need to communicate without blocking each other. +* In systems requiring loose coupling between components. +* For event-driven architectures where multiple services react to events. +* When you need to handle traffic spikes by buffering messages. +* In distributed systems where services may be temporarily unavailable. + +## Real-World Applications of Microservices Messaging Pattern in Java + +* Java applications using Apache Kafka, RabbitMQ, or ActiveMQ for service communication. +* E-commerce platforms for order processing and inventory management. +* Financial services for transaction processing and notifications. +* IoT systems for sensor data processing and event handling. + +## Benefits and Trade-offs of Microservices Messaging Pattern + +* Services are loosely coupled and can be developed and deployed independently. +* Message buffering improves system resilience when services are temporarily unavailable. +* Supports multiple communication patterns like publish/subscribe and request/reply. +* Enhances scalability by allowing parallel message processing. +* Natural support for event-driven architectures. + +Trade-offs: + +* Introduces additional complexity with the message broker infrastructure. +* Requires high availability setup for the message broker. +* Eventual consistency instead of immediate consistency. +* Debugging asynchronous flows is more complex than synchronous calls. +* Need to handle message duplication and ensure idempotent consumers. + +## Related Java Design Patterns + +* [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Uses messaging to coordinate distributed transactions. +* [CQRS Pattern](https://java-design-patterns.com/patterns/cqrs/): Often uses messaging to separate read and write operations. +* [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Stores state changes as messages. +* [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Complements messaging for synchronous requests. + +## References and Credits + +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3vLKqET) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) +* [Building Event-Driven Microservices: Leveraging Organizational Data at Scale](https://amzn.to/3PihS9R) +* [Pattern: Messaging (microservices.io)](https://microservices.io/patterns/communication-style/messaging.html) +* [Apache Kafka Documentation](https://kafka.apache.org/documentation/) \ No newline at end of file diff --git a/microservices-messaging/docker-compose.yml b/microservices-messaging/docker-compose.yml new file mode 100644 index 000000000000..b77ee549cd51 --- /dev/null +++ b/microservices-messaging/docker-compose.yml @@ -0,0 +1,53 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +version: '3.8' + +services: + kafka: + image: confluentinc/cp-kafka:7.5.0 + container_name: kafka-messaging-demo + ports: + - "9092:9092" + environment: + KAFKA_NODE_ID: 1 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT' + KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092' + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 + KAFKA_PROCESS_ROLES: 'broker,controller' + KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka:29093' + KAFKA_LISTENERS: 'PLAINTEXT://kafka:29092,CONTROLLER://kafka:29093,PLAINTEXT_HOST://0.0.0.0:9092' + KAFKA_INTER_BROKER_LISTENER_NAME: 'PLAINTEXT' + KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER' + KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs' + CLUSTER_ID: 'MkU3OEVBNTcwNTJENDM2Qk' + healthcheck: + test: ["CMD-SHELL", "kafka-topics --bootstrap-server localhost:9092 --list"] + interval: 5s + timeout: 10s + retries: 5 diff --git a/microservices-messaging/etc/microservices-messaging-flowchart.png b/microservices-messaging/etc/microservices-messaging-flowchart.png new file mode 100644 index 000000000000..dd26a2e2ce4a Binary files /dev/null and b/microservices-messaging/etc/microservices-messaging-flowchart.png differ diff --git a/microservices-messaging/etc/microservices-messaging-sequence-diagram.png b/microservices-messaging/etc/microservices-messaging-sequence-diagram.png new file mode 100644 index 000000000000..d22be5acbb5d Binary files /dev/null and b/microservices-messaging/etc/microservices-messaging-sequence-diagram.png differ diff --git a/microservices-messaging/pom.xml b/microservices-messaging/pom.xml new file mode 100644 index 000000000000..8fb9d59c4f74 --- /dev/null +++ b/microservices-messaging/pom.xml @@ -0,0 +1,118 @@ + + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + microservices-messaging + 1.26.0-SNAPSHOT + + + 3.6.1 + + + + + + org.apache.kafka + kafka-clients + ${kafka.version} + + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + + com.fasterxml.jackson.core + jackson-databind + 2.16.1 + + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.19.2 + compile + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.messaging.App + + + + + + + + + \ No newline at end of file diff --git a/microservices-messaging/run-app.ps1 b/microservices-messaging/run-app.ps1 new file mode 100644 index 000000000000..6fd4da50dfbe --- /dev/null +++ b/microservices-messaging/run-app.ps1 @@ -0,0 +1,89 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# PowerShell script to start Kafka container (if Docker is available) and run the Microservices Messaging App + +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition +Set-Location $ScriptDir + +Write-Host "======================================================" -ForegroundColor Cyan +Write-Host " Starting Microservices Messaging Pattern Application" -ForegroundColor Cyan +Write-Host "======================================================" -ForegroundColor Cyan + +# Check if Kafka is already running on port 9092 +$portActive = $false +try { + $socket = New-Object System.Net.Sockets.TcpClient("localhost", 9092) + if ($socket.Connected) { + $portActive = $true + $socket.Close() + } +} catch { + $portActive = $false +} + +if ($portActive) { + Write-Host "[INFO] Kafka is already running on port 9092." -ForegroundColor Green +} else { + # Check if Docker is available, or add Docker Desktop to PATH + if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { + $dockerPath = "$env:LOCALAPPDATA\Programs\DockerDesktop\resources\bin" + if (Test-Path $dockerPath) { + $env:PATH += ";$dockerPath" + } + } + $dockerCmd = Get-Command docker -ErrorAction SilentlyContinue + if ($dockerCmd) { + Write-Host "[INFO] Starting Kafka container via Docker Compose..." -ForegroundColor Yellow + docker compose up -d + + Write-Host "[INFO] Waiting for Kafka to become ready on port 9092..." -ForegroundColor Yellow + $retryCount = 0 + while (-not $portActive -and $retryCount -lt 20) { + Start-Sleep -Seconds 2 + try { + $socket = New-Object System.Net.Sockets.TcpClient("localhost", 9092) + if ($socket.Connected) { + $portActive = $true + $socket.Close() + } + } catch { + $retryCount++ + } + } + + if ($portActive) { + Write-Host "[INFO] Kafka container started successfully!" -ForegroundColor Green + } else { + Write-Host "[WARNING] Kafka did not become ready on port 9092 within timeout." -ForegroundColor Red + } + } else { + Write-Host "[WARNING] Docker is not installed or not in PATH." -ForegroundColor Yellow + Write-Host "[INFO] Please ensure Kafka is running locally on localhost:9092 before running the app." -ForegroundColor Yellow + } +} + +Write-Host "[INFO] Compiling and running App.java..." -ForegroundColor Cyan +& "..\mvnw.cmd" compile exec:java "-Dexec.mainClass=com.iluwatar.messaging.App" diff --git a/microservices-messaging/run-app.sh b/microservices-messaging/run-app.sh new file mode 100644 index 000000000000..8c31c185190e --- /dev/null +++ b/microservices-messaging/run-app.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# Shell script to start Kafka container (if Docker is available) and run the Microservices Messaging App + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$SCRIPT_DIR" + +echo "======================================================" +echo " Starting Microservices Messaging Pattern Application" +echo "======================================================" + +if nc -z localhost 9092 2>/dev/null || (echo > /dev/tcp/localhost/9092) 2>/dev/null; then + echo "[INFO] Kafka is already running on port 9092." +else + if command -v docker &> /dev/null; then + echo "[INFO] Starting Kafka container via Docker Compose..." + docker compose up -d + + echo "[INFO] Waiting for Kafka to become ready on port 9092..." + retry=0 + until nc -z localhost 9092 2>/dev/null || (echo > /dev/tcp/localhost/9092) 2>/dev/null || [ $retry -eq 20 ]; do + sleep 2 + retry=$((retry+1)) + done + + if [ $retry -lt 20 ]; then + echo "[INFO] Kafka container started successfully!" + else + echo "[WARNING] Kafka did not become ready on port 9092 within timeout." + fi + else + echo "[WARNING] Docker is not installed or not in PATH." + echo "[INFO] Please ensure Kafka is running locally on localhost:9092." + fi +fi + +echo "[INFO] Compiling and running App.java..." +../mvnw compile exec:java -Dexec.mainClass="com.iluwatar.messaging.App" diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/App.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/App.java new file mode 100644 index 000000000000..73c47c5ef1cf --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/App.java @@ -0,0 +1,161 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Microservices Messaging pattern enables asynchronous communication between services through + * Apache Kafka. This example demonstrates how services can communicate without tight coupling. + * + *

In this example: + * + *

    + *
  • OrderService acts as a message producer, publishing order events to Kafka + *
  • InventoryService, PaymentService, and NotificationService act as consumers + *
  • Apache Kafka acts as the message broker, routing messages between services + *
+ * + *

Key benefits demonstrated: + * + *

    + *
  • Loose coupling - services don't directly depend on each other + *
  • Asynchronous processing - producers don't wait for consumers + *
  • Scalability - multiple consumers can process messages independently + *
  • Resilience - if one consumer fails, others continue processing + *
  • Message persistence - Kafka stores messages for reliability + *
+ * + *

Prerequisites: This example requires a running Kafka instance. Start Kafka locally: + * + *

+ * # Start Zookeeper
+ * bin/zookeeper-server-start.sh config/zookeeper.properties
+ *
+ * # Start Kafka
+ * bin/kafka-server-start.sh config/server.properties
+ *
+ * # Create topic
+ * bin/kafka-topics.sh --create --topic order-topic --bootstrap-server localhost:9092
+ * 
+ */ +public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final String BOOTSTRAP_SERVERS = "localhost:9092"; + + /** Sleep duration between operations in milliseconds. Package-private for testing. */ + static long sleepMs = 2000; + + /** + * Program entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) throws InterruptedException { + KafkaMessageProducer producer = new KafkaMessageProducer(BOOTSTRAP_SERVERS); + + InventoryService inventoryService = new InventoryService(); + PaymentService paymentService = new PaymentService(); + NotificationService notificationService = new NotificationService(); + + KafkaMessageConsumer inventoryConsumer = + new KafkaMessageConsumer( + BOOTSTRAP_SERVERS, "inventory-group", "order-topic", inventoryService::handleMessage); + + KafkaMessageConsumer paymentConsumer = + new KafkaMessageConsumer( + BOOTSTRAP_SERVERS, "payment-group", "order-topic", paymentService::handleMessage); + + KafkaMessageConsumer notificationConsumer = + new KafkaMessageConsumer( + BOOTSTRAP_SERVERS, + "notification-group", + "order-topic", + notificationService::handleMessage); + + run(producer, inventoryConsumer, paymentConsumer, notificationConsumer); + } + + /** + * Runs the Microservices Messaging Pattern demonstration. + * + * @param producer the Kafka message producer + * @param inventoryConsumer the inventory service consumer + * @param paymentConsumer the payment service consumer + * @param notificationConsumer the notification service consumer + */ + static void run( + KafkaMessageProducer producer, + KafkaMessageConsumer inventoryConsumer, + KafkaMessageConsumer paymentConsumer, + KafkaMessageConsumer notificationConsumer) + throws InterruptedException { + LOGGER.info("Starting Microservices Messaging Pattern with Apache Kafka"); + + // Start consumers in separate threads + ExecutorService executor = Executors.newFixedThreadPool(3); + executor.submit(inventoryConsumer); + executor.submit(paymentConsumer); + executor.submit(notificationConsumer); + + // Give consumers time to subscribe + Thread.sleep(sleepMs); + + // Create producer service + OrderService orderService = new OrderService(producer); + + // Demonstrate the messaging pattern + LOGGER.info("\n=== Creating Order ==="); + orderService.createOrder("ORDER-001"); + + Thread.sleep(sleepMs); + + LOGGER.info("\n=== Updating Order ==="); + orderService.updateOrder("ORDER-001"); + + Thread.sleep(sleepMs); + + LOGGER.info("\n=== Cancelling Order ==="); + orderService.cancelOrder("ORDER-001"); + + Thread.sleep(sleepMs); + + // Cleanup + LOGGER.info("\nShutting down..."); + inventoryConsumer.stop(); + paymentConsumer.stop(); + notificationConsumer.stop(); + producer.close(); + + executor.shutdown(); + executor.awaitTermination(5, TimeUnit.SECONDS); + + LOGGER.info("Microservices Messaging Pattern demonstration completed"); + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/InventoryService.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/InventoryService.java new file mode 100644 index 000000000000..9552e867d1ee --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/InventoryService.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * InventoryService is a message consumer that processes inventory-related messages from Kafka. It + * listens to order events and updates inventory accordingly. + * + *

This service runs in its own Kafka consumer group (inventory-group) which allows it to: + * + *

    + *
  • Process messages independently from other services + *
  • Scale horizontally by adding more instances to the consumer group + *
  • Resume from last committed offset if the service restarts + *
+ */ +public class InventoryService { + private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class); + + /** + * Handles incoming messages related to orders from Kafka. + * + * @param message the message to process + */ + public void handleMessage(Message message) { + LOGGER.info( + "Inventory Service received message [{}]: {}", message.getId(), message.getContent()); + + if (message.getContent().contains("Order Created")) { + updateInventory(message); + } else if (message.getContent().contains("Order Cancelled")) { + restoreInventory(message); + } else { + LOGGER.debug("No inventory action needed for: {}", message.getContent()); + } + } + + private void updateInventory(Message message) { + LOGGER.info("Updating inventory for message: {}", message.getId()); + // Simulate inventory update - reserve stock for the order + try { + Thread.sleep(100); + LOGGER.info("Inventory updated successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Inventory update interrupted", e); + } + } + + private void restoreInventory(Message message) { + LOGGER.info("Restoring inventory for message: {}", message.getId()); + // Simulate inventory restoration - release reserved stock + try { + Thread.sleep(100); + LOGGER.info("Inventory restored successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Inventory restore interrupted", e); + } + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageConsumer.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageConsumer.java new file mode 100644 index 000000000000..71130e114dd8 --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageConsumer.java @@ -0,0 +1,125 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Kafka message consumer that subscribes to topics and processes messages. */ +public class KafkaMessageConsumer implements AutoCloseable, Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(KafkaMessageConsumer.class); + private final Consumer consumer; + private final ObjectMapper objectMapper; + private final String topic; + private final java.util.function.Consumer messageHandler; + private final AtomicBoolean running = new AtomicBoolean(true); + + /** + * Creates a new Kafka message consumer. + * + * @param bootstrapServers Kafka bootstrap servers + * @param groupId consumer group ID + * @param topic topic to subscribe to + * @param messageHandler handler for received messages + */ + public KafkaMessageConsumer( + String bootstrapServers, + String groupId, + String topic, + java.util.function.Consumer messageHandler) { + this(createDefaultConsumer(bootstrapServers, groupId), topic, messageHandler); + } + + KafkaMessageConsumer( + Consumer consumer, + String topic, + java.util.function.Consumer messageHandler) { + this.consumer = consumer; + this.objectMapper = new ObjectMapper(); + this.objectMapper.registerModule(new JavaTimeModule()); + this.topic = topic; + this.messageHandler = messageHandler; + } + + private static Consumer createDefaultConsumer( + String bootstrapServers, String groupId) { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); + return new KafkaConsumer<>(props); + } + + @Override + public void run() { + try { + consumer.subscribe(Collections.singletonList(topic)); + LOGGER.info("Consumer subscribed to topic: {}", topic); + + while (running.get()) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + records.forEach( + record -> { + try { + Message message = objectMapper.readValue(record.value(), Message.class); + LOGGER.info("Received message from topic '{}': {}", topic, message.getId()); + messageHandler.accept(message); + } catch (Exception e) { + LOGGER.error("Error processing message: {}", e.getMessage(), e); + } + }); + } + } catch (Exception e) { + LOGGER.error("Consumer error: {}", e.getMessage(), e); + } finally { + consumer.close(); + LOGGER.info("Consumer closed for topic: {}", topic); + } + } + + /** Stops the consumer. */ + public void stop() { + running.set(false); + } + + @Override + public void close() { + stop(); + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageProducer.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageProducer.java new file mode 100644 index 000000000000..56154152c008 --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/KafkaMessageProducer.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.util.Properties; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.serialization.StringSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Kafka message producer that publishes messages to Kafka topics. */ +public class KafkaMessageProducer implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(KafkaMessageProducer.class); + private final Producer producer; + private final ObjectMapper objectMapper; + + /** + * Creates a new Kafka message producer. + * + * @param bootstrapServers Kafka bootstrap servers + */ + public KafkaMessageProducer(String bootstrapServers) { + this(createDefaultProducer(bootstrapServers)); + } + + KafkaMessageProducer(Producer producer) { + this.producer = producer; + this.objectMapper = new ObjectMapper(); + this.objectMapper.registerModule(new JavaTimeModule()); + } + + private static Producer createDefaultProducer(String bootstrapServers) { + Properties props = new Properties(); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.ACKS_CONFIG, "all"); + props.put(ProducerConfig.RETRIES_CONFIG, 3); + return new KafkaProducer<>(props); + } + + /** + * Publishes a message to a Kafka topic. + * + * @param topic the topic to publish to + * @param message the message to publish + */ + public void publish(String topic, Message message) { + try { + String json = objectMapper.writeValueAsString(message); + ProducerRecord record = new ProducerRecord<>(topic, message.getId(), json); + + producer.send( + record, + (metadata, exception) -> { + if (exception != null) { + LOGGER.error( + "Failed to publish message to topic {}: {}", topic, exception.getMessage()); + } else { + LOGGER.info( + "Published message to topic '{}' [partition={}, offset={}]", + topic, + metadata.partition(), + metadata.offset()); + } + }); + + } catch (Exception e) { + LOGGER.error("Error serializing message: {}", e.getMessage(), e); + } + } + + @Override + public void close() { + if (producer != null) { + producer.flush(); + producer.close(); + LOGGER.info("Kafka producer closed"); + } + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/Message.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/Message.java new file mode 100644 index 000000000000..5d0e9f96769c --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/Message.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.time.LocalDateTime; +import java.util.UUID; +import lombok.Getter; + +/** Represents a message exchanged between services. */ +@Getter +public class Message { + private final String id; + private final String content; + private final LocalDateTime timestamp; + + /** + * Creates a new message with the given content. + * + * @param content the message content + */ + public Message(String content) { + this.id = UUID.randomUUID().toString(); + this.content = content; + this.timestamp = LocalDateTime.now(); + } + + /** JSON constructor for deserialization. */ + @JsonCreator + public Message( + @JsonProperty("id") String id, + @JsonProperty("content") String content, + @JsonProperty("timestamp") LocalDateTime timestamp) { + this.id = id; + this.content = content; + this.timestamp = timestamp; + } + + @Override + public String toString() { + return "Message{" + + "id='" + + id + + '\'' + + ", content='" + + content + + '\'' + + ", timestamp=" + + timestamp + + '}'; + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/NotificationService.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/NotificationService.java new file mode 100644 index 000000000000..461b1a326efb --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/NotificationService.java @@ -0,0 +1,100 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * NotificationService is a message consumer that processes notification-related messages from + * Kafka. It listens to order events and sends notifications to customers. + * + *

This service runs in its own Kafka consumer group (notification-group) which allows it to: + * + *

    + *
  • Process messages independently from other services + *
  • Scale horizontally by adding more instances to the consumer group + *
  • Resume from last committed offset if the service restarts + *
+ */ +public class NotificationService { + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class); + + /** + * Handles incoming messages related to orders from Kafka. + * + * @param message the message to process + */ + public void handleMessage(Message message) { + LOGGER.info( + "Notification Service received message [{}]: {}", message.getId(), message.getContent()); + + if (message.getContent().contains("Order Created")) { + sendOrderConfirmation(message); + } else if (message.getContent().contains("Order Updated")) { + sendOrderUpdate(message); + } else if (message.getContent().contains("Order Cancelled")) { + sendCancellationNotice(message); + } else { + LOGGER.debug("No notification action needed for: {}", message.getContent()); + } + } + + private void sendOrderConfirmation(Message message) { + LOGGER.info("Sending order confirmation for message: {}", message.getId()); + // Simulate sending email/SMS notification to customer + try { + Thread.sleep(50); + LOGGER.info("Order confirmation sent successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Notification send interrupted", e); + } + } + + private void sendOrderUpdate(Message message) { + LOGGER.info("Sending order update notification for message: {}", message.getId()); + // Simulate sending update notification + try { + Thread.sleep(50); + LOGGER.info("Order update notification sent successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Notification send interrupted", e); + } + } + + private void sendCancellationNotice(Message message) { + LOGGER.info("Sending cancellation notice for message: {}", message.getId()); + // Simulate sending cancellation notification + try { + Thread.sleep(50); + LOGGER.info("Cancellation notice sent successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Notification send interrupted", e); + } + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/OrderService.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/OrderService.java new file mode 100644 index 000000000000..d059e4e3e0fd --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/OrderService.java @@ -0,0 +1,76 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** OrderService is a message producer that publishes order-related messages using Kafka. */ +public class OrderService { + private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class); + private static final String ORDER_TOPIC = "order-topic"; + + private final KafkaMessageProducer producer; + + public OrderService(KafkaMessageProducer producer) { + this.producer = producer; + } + + /** + * Creates an order and publishes a message to notify other services. + * + * @param orderId the ID of the order to create + */ + public void createOrder(String orderId) { + LOGGER.info("Creating order: {}", orderId); + Message message = new Message("Order Created: " + orderId); + producer.publish(ORDER_TOPIC, message); + LOGGER.info("Order creation message published for: {}", orderId); + } + + /** + * Updates an order and publishes a message to notify other services. + * + * @param orderId the ID of the order to update + */ + public void updateOrder(String orderId) { + LOGGER.info("Updating order: {}", orderId); + Message message = new Message("Order Updated: " + orderId); + producer.publish(ORDER_TOPIC, message); + LOGGER.info("Order update message published for: {}", orderId); + } + + /** + * Cancels an order and publishes a message to notify other services. + * + * @param orderId the ID of the order to cancel + */ + public void cancelOrder(String orderId) { + LOGGER.info("Cancelling order: {}", orderId); + Message message = new Message("Order Cancelled: " + orderId); + producer.publish(ORDER_TOPIC, message); + LOGGER.info("Order cancellation message published for: {}", orderId); + } +} diff --git a/microservices-messaging/src/main/java/com/iluwatar/messaging/PaymentService.java b/microservices-messaging/src/main/java/com/iluwatar/messaging/PaymentService.java new file mode 100644 index 000000000000..4c90897a6e8f --- /dev/null +++ b/microservices-messaging/src/main/java/com/iluwatar/messaging/PaymentService.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * PaymentService is a message consumer that processes payment-related messages from Kafka. It + * listens to order events and handles payment processing. + * + *

This service runs in its own Kafka consumer group (payment-group) which allows it to: + * + *

    + *
  • Process messages independently from other services + *
  • Scale horizontally by adding more instances to the consumer group + *
  • Resume from last committed offset if the service restarts + *
+ */ +public class PaymentService { + private static final Logger LOGGER = LoggerFactory.getLogger(PaymentService.class); + + /** + * Handles incoming messages related to orders from Kafka. + * + * @param message the message to process + */ + public void handleMessage(Message message) { + LOGGER.info("Payment Service received message [{}]: {}", message.getId(), message.getContent()); + + if (message.getContent().contains("Order Created")) { + processPayment(message); + } else if (message.getContent().contains("Order Cancelled")) { + refundPayment(message); + } else { + LOGGER.debug("No payment action needed for: {}", message.getContent()); + } + } + + private void processPayment(Message message) { + LOGGER.info("Processing payment for message: {}", message.getId()); + // Simulate payment processing - charge the customer + try { + Thread.sleep(150); + LOGGER.info("Payment processed successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Payment processing interrupted", e); + } + } + + private void refundPayment(Message message) { + LOGGER.info("Refunding payment for message: {}", message.getId()); + // Simulate payment refund - return money to customer + try { + Thread.sleep(150); + LOGGER.info("Payment refunded successfully for: {}", message.getContent()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Payment refund interrupted", e); + } + } +} diff --git a/microservices-messaging/src/main/resources/logback.xml b/microservices-messaging/src/main/resources/logback.xml new file mode 100644 index 000000000000..7f40741c0ff1 --- /dev/null +++ b/microservices-messaging/src/main/resources/logback.xml @@ -0,0 +1,40 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + \ No newline at end of file diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/AppTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/AppTest.java new file mode 100644 index 000000000000..430b44812e66 --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/AppTest.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link App}. Tests main application entry point. */ +class AppTest { + + @BeforeEach + void setUp() { + // Speed up sleeps so tests finish instantly + App.sleepMs = 0; + } + + @AfterEach + void tearDown() { + // Restore default so other contexts are unaffected + App.sleepMs = 2000; + } + + @Test + void testAppConstructor() { + assertNotNull(new App(), "App should be instantiable"); + } + + @Test + void testRunWithMockObjects() { + // Build mock-backed producer and consumers — no Kafka broker required + MockProducer mockProducer = + new MockProducer<>(true, new StringSerializer(), new StringSerializer()); + KafkaMessageProducer producer = new KafkaMessageProducer(mockProducer); + + MockConsumer mc1 = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + MockConsumer mc2 = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + MockConsumer mc3 = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + + KafkaMessageConsumer inventoryConsumer = + new KafkaMessageConsumer(mc1, "order-topic", msg -> {}); + KafkaMessageConsumer paymentConsumer = new KafkaMessageConsumer(mc2, "order-topic", msg -> {}); + KafkaMessageConsumer notificationConsumer = + new KafkaMessageConsumer(mc3, "order-topic", msg -> {}); + + // Stop consumers immediately so their poll loops exit right away in the executor threads + inventoryConsumer.stop(); + paymentConsumer.stop(); + notificationConsumer.stop(); + + // sleepMs == 0, so all Thread.sleep(sleepMs) return instantly — full run() coverage + assertDoesNotThrow( + () -> App.run(producer, inventoryConsumer, paymentConsumer, notificationConsumer), + "App.run() should complete without throwing"); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/InventoryServiceTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/InventoryServiceTest.java new file mode 100644 index 000000000000..bb0842ce7aef --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/InventoryServiceTest.java @@ -0,0 +1,118 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link InventoryService}. Tests service behavior with various message types + * without Kafka dependencies. + */ +class InventoryServiceTest { + + private InventoryService inventoryService; + + @BeforeEach + void setUp() { + inventoryService = new InventoryService(); + } + + @Test + void testServiceCanBeInstantiated() { + // Arrange & Act & Assert + assertNotNull(inventoryService, "InventoryService should be instantiated"); + } + + @Test + void testHandleOrderCreatedMessage() { + // Arrange + var message = new Message("Order Created: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> inventoryService.handleMessage(message), + "Should handle order created message without error"); + } + + @Test + void testHandleOrderCancelledMessage() { + // Arrange + var message = new Message("Order Cancelled: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> inventoryService.handleMessage(message), + "Should handle order cancelled message without error"); + } + + @Test + void testHandleOrderUpdatedMessage() { + // Arrange + var message = new Message("Order Updated: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> inventoryService.handleMessage(message), + "Should handle order updated message without error"); + } + + @Test + void testHandleUnknownMessage() { + // Arrange + var message = new Message("Unknown Event: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> inventoryService.handleMessage(message), + "Should handle unknown message without error"); + } + + @Test + void testHandleMultipleMessages() { + // Act & Assert + assertDoesNotThrow( + () -> { + inventoryService.handleMessage(new Message("Order Created: ORDER-001")); + inventoryService.handleMessage(new Message("Order Updated: ORDER-001")); + inventoryService.handleMessage(new Message("Order Cancelled: ORDER-001")); + }, + "Should handle multiple messages without error"); + } + + @Test + void testHandleMessagesWhenInterrupted() { + Thread.currentThread().interrupt(); + inventoryService.handleMessage(new Message("Order Created: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + + Thread.currentThread().interrupt(); + inventoryService.handleMessage(new Message("Order Cancelled: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageConsumerTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageConsumerTest.java new file mode 100644 index 000000000000..2977f7448c56 --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageConsumerTest.java @@ -0,0 +1,137 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.util.Collections; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link KafkaMessageConsumer}. */ +class KafkaMessageConsumerTest { + + private MockConsumer mockConsumer; + private KafkaMessageConsumer kafkaMessageConsumer; + private AtomicBoolean handlerCalled; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + handlerCalled = new AtomicBoolean(false); + kafkaMessageConsumer = + new KafkaMessageConsumer(mockConsumer, "test-topic", msg -> handlerCalled.set(true)); + } + + @Test + void testConsumerCanBeInstantiated() { + assertNotNull(kafkaMessageConsumer, "KafkaMessageConsumer should be instantiated"); + } + + @Test + void testRunProcessesValidMessageAndStops() throws Exception { + ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()); + Message msg = new Message("Order Created: 123"); + String jsonStr = mapper.writeValueAsString(msg); + + TopicPartition tp = new TopicPartition("test-topic", 0); + mockConsumer.updateBeginningOffsets( + new HashMap<>() { + { + put(tp, 0L); + } + }); + + mockConsumer.schedulePollTask( + () -> { + mockConsumer.rebalance(Collections.singletonList(tp)); + mockConsumer.addRecord(new ConsumerRecord<>("test-topic", 0, 0L, "key", jsonStr)); + }); + + mockConsumer.schedulePollTask(() -> kafkaMessageConsumer.stop()); + + kafkaMessageConsumer.run(); + + assertTrue(handlerCalled.get(), "Handler should have been invoked"); + assertTrue(mockConsumer.closed(), "Consumer should be closed"); + } + + @Test + void testRunHandlesInvalidJsonMessage() { + TopicPartition tp = new TopicPartition("test-topic", 0); + mockConsumer.updateBeginningOffsets( + new HashMap<>() { + { + put(tp, 0L); + } + }); + + mockConsumer.schedulePollTask( + () -> { + mockConsumer.rebalance(Collections.singletonList(tp)); + mockConsumer.addRecord(new ConsumerRecord<>("test-topic", 0, 0L, "key", "{invalid json")); + }); + + mockConsumer.schedulePollTask(() -> kafkaMessageConsumer.stop()); + + assertDoesNotThrow(() -> kafkaMessageConsumer.run()); + assertTrue(mockConsumer.closed(), "Consumer should be closed"); + } + + @Test + void testCloseStopsConsumer() { + assertDoesNotThrow(() -> kafkaMessageConsumer.close()); + } + + @Test + void testRunWhenAlreadyStopped() { + // Stop the consumer before run() so the while loop exits immediately + kafkaMessageConsumer.stop(); + + // run() should complete without processing any records + assertDoesNotThrow(() -> kafkaMessageConsumer.run()); + assertTrue(mockConsumer.closed(), "Consumer should be closed even when stopped before run"); + } + + @Test + void testRunHandlesConsumerException() { + // Schedule a WakeupException during poll to trigger the outer catch block + mockConsumer.schedulePollTask(() -> mockConsumer.wakeup()); + + // run() must not propagate the exception + assertDoesNotThrow(() -> kafkaMessageConsumer.run()); + assertTrue(mockConsumer.closed(), "Consumer should be closed after exception"); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageProducerTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageProducerTest.java new file mode 100644 index 000000000000..1257495813a3 --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageProducerTest.java @@ -0,0 +1,93 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link KafkaMessageProducer}. */ +class KafkaMessageProducerTest { + + private MockProducer mockProducer; + private KafkaMessageProducer kafkaMessageProducer; + + @BeforeEach + void setUp() { + mockProducer = new MockProducer<>(true, new StringSerializer(), new StringSerializer()); + kafkaMessageProducer = new KafkaMessageProducer(mockProducer); + } + + @Test + void testProducerCanBeInstantiated() { + assertNotNull(kafkaMessageProducer, "KafkaMessageProducer should be instantiated"); + } + + @Test + void testPublishMessageSuccess() { + Message message = new Message("Test Order"); + + assertDoesNotThrow(() -> kafkaMessageProducer.publish("test-topic", message)); + assertEquals(1, mockProducer.history().size()); + assertEquals("test-topic", mockProducer.history().get(0).topic()); + assertEquals(message.getId(), mockProducer.history().get(0).key()); + } + + @Test + void testPublishMessageErrorCallback() { + MockProducer failingProducer = + new MockProducer<>(false, new StringSerializer(), new StringSerializer()); + KafkaMessageProducer producerWithError = new KafkaMessageProducer(failingProducer); + Message message = new Message("Test Order"); + + assertDoesNotThrow(() -> producerWithError.publish("test-topic", message)); + assertEquals(1, failingProducer.history().size()); + + // Trigger error callback BEFORE closing so the exception != null branch is covered + failingProducer.errorNext(new RuntimeException("Kafka publish error")); + + assertDoesNotThrow(() -> producerWithError.close()); + assertTrue(failingProducer.closed()); + } + + @Test + void testClose() { + assertDoesNotThrow(() -> kafkaMessageProducer.close()); + assertTrue(mockProducer.closed()); + } + + @Test + void testPublishNullMessageCatchesException() { + // Passing null causes message.getId() to throw NPE, which is caught by the + // catch(Exception e) block — covering the "Error serializing message" log branch. + assertDoesNotThrow(() -> kafkaMessageProducer.publish("test-topic", null)); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/MessageTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/MessageTest.java new file mode 100644 index 000000000000..d80cc2b806ca --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/MessageTest.java @@ -0,0 +1,165 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.time.LocalDateTime; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link Message}. Tests follow FIRST principles: Fast, Isolated, Repeatable, + * Self-validating, Timely. + */ +class MessageTest { + + private ObjectMapper objectMapper; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + } + + @Test + void testMessageCreation() { + // Arrange & Act + var message = new Message("Test content"); + + // Assert + assertNotNull(message.getId(), "Message ID should not be null"); + assertEquals("Test content", message.getContent(), "Content should match"); + assertNotNull(message.getTimestamp(), "Timestamp should not be null"); + } + + @Test + void testMessageIdIsUnique() { + // Arrange & Act + var message1 = new Message("Content 1"); + var message2 = new Message("Content 2"); + + // Assert + assertNotEquals(message1.getId(), message2.getId(), "Each message should have unique ID"); + } + + @Test + void testMessageTimestamp() { + // Arrange + var beforeCreation = LocalDateTime.now(); + + // Act + var message = new Message("Test"); + var afterCreation = LocalDateTime.now(); + + // Assert + assertTrue( + message.getTimestamp().isAfter(beforeCreation.minusSeconds(1)) + && message.getTimestamp().isBefore(afterCreation.plusSeconds(1)), + "Timestamp should be close to creation time"); + } + + @Test + void testJsonSerialization() throws Exception { + // Arrange + var originalMessage = new Message("Test content"); + + // Act + var json = objectMapper.writeValueAsString(originalMessage); + + // Assert + assertNotNull(json, "JSON should not be null"); + assertTrue(json.contains("Test content"), "JSON should contain content"); + assertTrue(json.contains(originalMessage.getId()), "JSON should contain ID"); + } + + @Test + void testJsonDeserialization() throws Exception { + // Arrange + var originalMessage = new Message("Test content"); + var json = objectMapper.writeValueAsString(originalMessage); + + // Act + var deserializedMessage = objectMapper.readValue(json, Message.class); + + // Assert + assertNotNull(deserializedMessage, "Deserialized message should not be null"); + assertEquals(originalMessage.getId(), deserializedMessage.getId(), "IDs should match"); + assertEquals( + originalMessage.getContent(), deserializedMessage.getContent(), "Content should match"); + } + + @Test + void testToString() { + // Arrange + var message = new Message("Test content"); + + // Act + var result = message.toString(); + + // Assert + assertNotNull(result, "ToString should not return null"); + assertTrue(result.contains("Message{"), "ToString should contain class name"); + assertTrue(result.contains("Test content"), "ToString should contain content"); + assertTrue(result.contains(message.getId()), "ToString should contain ID"); + } + + @Test + void testMessageWithEmptyContent() { + // Arrange & Act + var message = new Message(""); + + // Assert + assertNotNull(message.getId(), "ID should be generated even for empty content"); + assertEquals("", message.getContent(), "Empty content should be preserved"); + } + + @Test + void testMessageWithNullContent() { + // Arrange & Act + var message = new Message(null); + + // Assert + assertNotNull(message.getId(), "ID should be generated even for null content"); + assertEquals(null, message.getContent(), "Null content should be preserved"); + } + + @Test + void testMessageWithSpecialCharacters() { + // Arrange + var specialContent = "Test with special chars: @#$%^&*()"; + + // Act + var message = new Message(specialContent); + + // Assert + assertEquals(specialContent, message.getContent(), "Special characters should be preserved"); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/NotificationServiceTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/NotificationServiceTest.java new file mode 100644 index 000000000000..142e59087b5c --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/NotificationServiceTest.java @@ -0,0 +1,134 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link NotificationService}. Tests service behavior with various message types + * without Kafka dependencies. + */ +class NotificationServiceTest { + + private NotificationService notificationService; + + @BeforeEach + void setUp() { + notificationService = new NotificationService(); + } + + @Test + void testServiceCanBeInstantiated() { + // Arrange & Act & Assert + assertNotNull(notificationService, "NotificationService should be instantiated"); + } + + @Test + void testHandleOrderCreatedMessage() { + // Arrange + var message = new Message("Order Created: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> notificationService.handleMessage(message), + "Should handle order created message without error"); + } + + @Test + void testHandleOrderUpdatedMessage() { + // Arrange + var message = new Message("Order Updated: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> notificationService.handleMessage(message), + "Should handle order updated message without error"); + } + + @Test + void testHandleOrderCancelledMessage() { + // Arrange + var message = new Message("Order Cancelled: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> notificationService.handleMessage(message), + "Should handle order cancelled message without error"); + } + + @Test + void testHandleUnknownMessage() { + // Arrange + var message = new Message("Unknown Event: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> notificationService.handleMessage(message), + "Should handle unknown message without error"); + } + + @Test + void testHandleAllMessageTypes() { + // Act & Assert + assertDoesNotThrow( + () -> { + notificationService.handleMessage(new Message("Order Created: ORDER-001")); + notificationService.handleMessage(new Message("Order Updated: ORDER-001")); + notificationService.handleMessage(new Message("Order Cancelled: ORDER-001")); + }, + "Should handle all message types without error"); + } + + @Test + void testHandleMultipleOrdersSequentially() { + // Act & Assert + assertDoesNotThrow( + () -> { + notificationService.handleMessage(new Message("Order Created: ORDER-001")); + notificationService.handleMessage(new Message("Order Created: ORDER-002")); + notificationService.handleMessage(new Message("Order Created: ORDER-003")); + }, + "Should handle multiple orders sequentially without error"); + } + + @Test + void testHandleMessagesWhenInterrupted() { + Thread.currentThread().interrupt(); + notificationService.handleMessage(new Message("Order Created: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + + Thread.currentThread().interrupt(); + notificationService.handleMessage(new Message("Order Updated: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + + Thread.currentThread().interrupt(); + notificationService.handleMessage(new Message("Order Cancelled: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/OrderServiceTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/OrderServiceTest.java new file mode 100644 index 000000000000..2b3f38584a20 --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/OrderServiceTest.java @@ -0,0 +1,109 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link OrderService}. Tests follow Arrange-Act-Assert pattern. */ +class OrderServiceTest { + + private MockProducer mockKafkaProducer; + private KafkaMessageProducer messageProducer; + private OrderService orderService; + + @BeforeEach + void setUp() { + mockKafkaProducer = new MockProducer<>(true, new StringSerializer(), new StringSerializer()); + messageProducer = new KafkaMessageProducer(mockKafkaProducer); + orderService = new OrderService(messageProducer); + } + + @Test + void testCreateOrder() { + // Arrange + var orderId = "ORDER-001"; + + // Act + assertDoesNotThrow(() -> orderService.createOrder(orderId)); + + // Assert + assertEquals(1, mockKafkaProducer.history().size()); + } + + @Test + void testUpdateOrder() { + // Arrange + var orderId = "ORDER-002"; + + // Act + assertDoesNotThrow(() -> orderService.updateOrder(orderId)); + + // Assert + assertEquals(1, mockKafkaProducer.history().size()); + } + + @Test + void testCancelOrder() { + // Arrange + var orderId = "ORDER-003"; + + // Act + assertDoesNotThrow(() -> orderService.cancelOrder(orderId)); + + // Assert + assertEquals(1, mockKafkaProducer.history().size()); + } + + @Test + void testMultipleOrderOperations() { + // Arrange + var orderId = "ORDER-004"; + + // Act + orderService.createOrder(orderId); + orderService.updateOrder(orderId); + orderService.cancelOrder(orderId); + + // Assert + assertEquals(3, mockKafkaProducer.history().size()); + } + + @Test + void testCreateOrderWithDifferentIds() { + // Act + orderService.createOrder("ORDER-001"); + orderService.createOrder("ORDER-002"); + orderService.createOrder("ORDER-003"); + + // Assert + assertEquals(3, mockKafkaProducer.history().size()); + } +} diff --git a/microservices-messaging/src/test/java/com/iluwatar/messaging/PaymentServiceTest.java b/microservices-messaging/src/test/java/com/iluwatar/messaging/PaymentServiceTest.java new file mode 100644 index 000000000000..608a64549c87 --- /dev/null +++ b/microservices-messaging/src/test/java/com/iluwatar/messaging/PaymentServiceTest.java @@ -0,0 +1,116 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.messaging; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link PaymentService}. Tests service behavior with various message types without + * Kafka dependencies. + */ +class PaymentServiceTest { + + private PaymentService paymentService; + + @BeforeEach + void setUp() { + paymentService = new PaymentService(); + } + + @Test + void testServiceCanBeInstantiated() { + // Arrange & Act & Assert + assertNotNull(paymentService, "PaymentService should be instantiated"); + } + + @Test + void testHandleOrderCreatedMessage() { + // Arrange + var message = new Message("Order Created: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> paymentService.handleMessage(message), + "Should handle order created message without error"); + } + + @Test + void testHandleOrderCancelledMessage() { + // Arrange + var message = new Message("Order Cancelled: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> paymentService.handleMessage(message), + "Should handle order cancelled message without error"); + } + + @Test + void testHandleOrderUpdatedMessage() { + // Arrange + var message = new Message("Order Updated: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> paymentService.handleMessage(message), + "Should handle order updated message without error"); + } + + @Test + void testHandleUnknownMessage() { + // Arrange + var message = new Message("Unknown Event: ORDER-001"); + + // Act & Assert + assertDoesNotThrow( + () -> paymentService.handleMessage(message), "Should handle unknown message without error"); + } + + @Test + void testHandleMultipleMessages() { + // Act & Assert + assertDoesNotThrow( + () -> { + paymentService.handleMessage(new Message("Order Created: ORDER-001")); + paymentService.handleMessage(new Message("Order Cancelled: ORDER-001")); + }, + "Should handle multiple messages without error"); + } + + @Test + void testHandleMessagesWhenInterrupted() { + Thread.currentThread().interrupt(); + paymentService.handleMessage(new Message("Order Created: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + + Thread.currentThread().interrupt(); + paymentService.handleMessage(new Message("Order Cancelled: ORDER-001")); + org.junit.jupiter.api.Assertions.assertTrue(Thread.interrupted()); + } +} diff --git a/microservices-self-registration/README.md b/microservices-self-registration/README.md new file mode 100644 index 000000000000..bfc837817c57 --- /dev/null +++ b/microservices-self-registration/README.md @@ -0,0 +1,236 @@ +--- +title: "Microservices Self-Registration Pattern in Java with Spring Boot and Eureka" +shortTitle: Microservices Pattern - Self-Registration +description: "Dynamically register and discover Java microservices using Spring Boot and Eureka for resilient, scalable communication." +category: Service Discovery +language: en +tag: + - Microservices + - Self-Registration + - Service Discovery + - Eureka + - Spring Boot + - Spring Cloud + - Java + - Dynamic Configuration + - Resilience +--- + +## Intent of Microservices Self-Registration Pattern + +The intent of the Self-Registration pattern is to enable microservices to automatically announce their presence and location to a central registry (like Eureka) upon startup, simplifying service discovery and allowing other services to find and communicate with them without manual configuration or hardcoded addresses. This promotes dynamic and resilient microservices architectures. + +## What's in the Project + +This project demonstrates the Microservices Self-Registration pattern using Java, Spring Boot (version 3.4.4), and Eureka for service discovery. It consists of three main components: a Eureka Server and two simple microservices, a Greeting Service and a Context Service, which discover and communicate with each other. + +### Project Structure +* **`eureka-server`:** The central service registry where microservices register themselves. +* **`greeting-service`:** A simple microservice that provides a greeting. +* **`context-service`:** A microservice that consumes the greeting from the Greeting Service and adds context. + + The **Eureka Server** acts as the discovery service. Microservices register themselves with the Eureka Server, providing their network location. + + package com.example.eurekaserver; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + + @SpringBootApplication + @EnableEurekaServer + public class EurekaServerApplication { + + public static void main(String[] args) { + SpringApplication.run(EurekaServerApplication.class, args); + } + } + + The **Greeting Service** is a simple microservice that exposes an endpoint to retrieve a greeting. + + package com.example.greetingservice; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + + @SpringBootApplication + @EnableDiscoveryClient + public class GreetingServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(GreetingServiceApplication.class, args); + } + } + + Greeting Controller + + package com.example.greetingservice.controller; + + import org.springframework.web.bind.annotation.GetMapping; + import org.springframework.web.bind.annotation.RestController; + + @RestController + public class GreetingController { + + @GetMapping("/greeting") + public String getGreeting() { + return "Hello"; + } + } + +The **Context Service** consumes the greeting from the Greeting Service using OpenFeign and adds contextual information. + + package com.example.contextservice; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + import org.springframework.cloud.openfeign.EnableFeignClients; + + @SpringBootApplication + @EnableDiscoveryClient + @EnableFeignClients + public class ContextServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(ContextServiceApplication.class, args); + } + } + + Feign Client : Spring Cloud OpenFeign is a declarative HTTP client that makes it easier to consume RESTful web services in your Spring Cloud applications. Instead of writing the boilerplate code for making HTTP requests, you simply declare interface with annotations that describe the web service you want to consume. + + package com.example.contextservice.client; + + import org.springframework.cloud.openfeign.FeignClient; + import org.springframework.web.bind.annotation.GetMapping; + + @FeignClient(name = "greeting-service") + public interface GreetingServiceClient { + + @GetMapping("/greeting") + String getGreeting(); + } + + Context Controller + + package com.example.contextservice.controller; + + import com.example.contextservice.client.GreetingServiceClient; + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.beans.factory.annotation.Value; + import org.springframework.web.bind.annotation.GetMapping; + import org.springframework.web.bind.annotation.RestController; + + @RestController + public class ContextController { + + @Autowired + private GreetingServiceClient greetingServiceClient; + + @Value("${user.region}") + private String userRegion; + + @GetMapping("/context") + public String getContext() { + String greeting = greetingServiceClient.getGreeting(); + return "The Greeting Service says: " + greeting + " from " + userRegion + "!"; + } + } + + 1. Both the Greeting Service and the Context Service register themselves with the Eureka Server upon startup using the _@EnableDiscoveryClient_ annotation. + 2. The Context Service, annotated with _@EnableFeignClients_, uses the GreetingServiceClient interface with _@FeignClient(name = "greeting-service")_ to declare its intent to communicate with the service named "greeting-service" in Eureka. + 3. When the /context endpoint of the Context Service is accessed, it calls the _getGreeting()_ method of the GreetingServiceClient. + 4. OpenFeign, leveraging the service discovery information from Eureka, resolves the network location of an available instance of the Greeting Service and makes an HTTP GET request to its /greeting endpoint. + 5. The Greeting Service responds with "Hello", and the Context Service then adds the configured user.region to the response. + + This project utilizes Spring Boot Actuator, which is included as a dependency, to provide health check endpoints for each microservice. These endpoints (e.g., /actuator/health) can be used by Eureka Server to monitor the health of the registered instances. + +## Steps to use for this Project + +Prerequisites: + - Java Development Kit (JDK): Make sure you have a compatible JDK installed (ideally Java 17 or later, as Spring Boot 3.x requires it). + - Maven or Gradle: You'll need either Maven (if you chose Maven during Spring Initializr setup) or Gradle (if you chose Gradle) installed on your system. + - An IDE (Optional but Recommended): IntelliJ IDEA, Eclipse, or Spring Tool Suite (STS) can make it easier to work with the project. + - Web Browser: You'll need a web browser to access the Eureka dashboard and the microservice endpoints. + +Step : + - You'll need to build each microservice individually. Navigate to the root directory of each project in your terminal or command prompt and run the appropriate build command: + _cd eurekaserver + mvn clean install + cd ../greetingservice + mvn clean install + cd ../contextservice + mvn clean install_ +Step : + - Navigate to the root directory of your eurekaserver project in your terminal or command prompt + _mvn spring-boot:run_ + - Wait for the Eureka Server application to start. You should see logs in the console indicating that it has started on port 8761 (as configured). + - Open your web browser and go to http://localhost:8761/. You should see the Eureka Server dashboard. Initially, the list of registered instances will be empty. +Step : + - Run the Greeting Service + - Open a new terminal or command prompt. + - Navigate to the root directory of your greetingservice project. + - Run the Spring Boot application: _mvn spring-boot:run_ + - Wait for the Greeting Service to start. You should see logs indicating that it has registered with the Eureka Server. + - Go back to your Eureka Server dashboard in the browser (http://localhost:8761/). You should now see GREETINGSERVICE listed under the "Instances currently registered with Eureka". Its status should be "UP". +Step : + - Run the Context Service + - Open a new terminal or command prompt. + - Navigate to the root directory of your contextservice project. + - Run the Spring Boot application: _mvn spring-boot:run_ + - Wait for the Context Service to start. You should see logs indicating that it has registered with the Eureka Server. + - Go back to your Eureka Server dashboard in the browser (http://localhost:8761/). You should now see CONTEXTSERVICE listed under the "Instances currently registered with Eureka". Its status should be "UP". +STEP : + - Test the Greeting Service Directly: Open your web browser and go to http://localhost:8081/greeting. You should see the output: Hello. + - Test the Context Service (which calls the Greeting Service): Open your web browser and go to http://localhost:8082/context. You should see the output: The Greeting Service says: Hello from Chennai, Tamil Nadu, India!. This confirms that the Context Service successfully discovered and called the Greeting Service through Eureka. + +Optional: Check Health Endpoints + +You can also verify the health status of each service using Spring Boot Actuator: + - Greeting Service Health: http://localhost:8081/actuator/health (should return {"status":"UP"}) + - Context Service Health: http://localhost:8082/actuator/health (should return {"status":"UP"}) + - Eureka Server Health: http://localhost:8761/actuator/health (should return {"status":"UP"}) + +## When to use Microservices Self-Registration Pattern + + - **Dynamic Environments:** When your microservices are frequently deployed, scaled up or down, or their network locations (IP addresses and ports) change often. This is common in cloud-based or containerized environments (like Docker and Kubernetes). + - **Large Number of Services:** As the number of microservices in your system grows, manually managing their configurations and dependencies becomes complex and error-prone. Self-registration automates this process. + - **Need for Automatic Service** Discovery: When services need to find and communicate with each other without hardcoding network locations. This allows for greater flexibility and reduces coupling. + - **Implementing Load Balancing:** Service registries like Eureka often integrate with load balancers, enabling them to automatically distribute traffic across available instances of a service that have registered themselves. + - **Improving System Resilience:** If a service instance fails, the registry will eventually be updated (through heartbeats or health checks), and other services can discover and communicate with the remaining healthy instances. + - **DevOps Automation:** This pattern aligns well with DevOps practices, allowing for more automated deployment and management of microservices. + +## Real-World Applications of Self-Registration pattern + + - E-Commerce platforms have numerous independent services for product catalogs, order processing, payments, shipping, etc. Self-registration allows these services to dynamically discover and communicate with each other as the system scales during peak loads or as new features are deployed. + - Streaming services rely on many microservices for user authentication, content delivery networks (CDNs), recommendation engines, billing systems, etc. Self-registration helps these services adapt to varying user demands and infrastructure changes. + - Social media These platforms use microservices for managing user profiles, timelines, messaging, advertising, and more. Self-registration enables these services to scale independently and handle the massive traffic they experience. + +## Advantages + + - Microservices can dynamically locate and communicate with each other without needing to know their specific network addresses beforehand. This is crucial in dynamic environments where IP addresses and ports can change frequently. + - Reduces the need for manual configuration of service locations in each microservice. Services don't need to be updated every time another service's location changes. + - Scaling microservices up or down becomes easier. New instances automatically register themselves with the service registry, making them immediately discoverable by other services without manual intervention. + - If a service instance fails, it will eventually stop sending heartbeats to the registry and will be removed. Consumers can then discover and connect to other healthy instances, improving the system's overall resilience. + - Services are less tightly coupled as they don't have direct dependencies on the physical locations of other services. This makes deployments and updates more flexible. + - Service registries often integrate with load balancers. When a new service instance registers, the load balancer can automatically include it in the pool of available instances, distributing traffic effectively. + - Microservices can be deployed across different environments (development, testing, production) without significant changes to their discovery mechanism, as long as they are configured to connect to the appropriate service registry for that environment. + +## Trade-offs + + - Introducing a service registry adds another component to your system that needs to be set up, managed, and monitored. This increases the overall complexity of the infrastructure. + - The service registry itself becomes a critical component. If the service registry becomes unavailable, it can disrupt communication between microservices. High availability for the service registry is therefore essential. + - Microservices need to communicate with the service registry for registration, sending heartbeats, and querying for other services. This can lead to increased network traffic. + - There might be a slight delay between when a microservice instance starts and when it becomes fully registered and discoverable in the service registry. This needs to be considered, especially during scaling events. + - You need to consider how your microservices will behave if they fail to register with the service registry upon startup. Robust error handling and retry mechanisms are often necessary. + - Microservices need to include and configure client libraries (like the Eureka Discovery Client) to interact with the service registry. This adds a dependency to your application code. + - In distributed service registries, ensuring consistency of the registry data across all nodes can be a challenge. Different registries might have different consistency models (e.g., eventual consistency). + +## References + + - Microservices Patterns: https://microservices.io/ + - Eureka Documentation: https://github.com/Netflix/eureka | https://spring.io/projects/spring-cloud-netflix + - Spring Boot Documentation: https://spring.io/projects/spring-boot + - Spring Cloud OpenFeignDocumentation: https://spring.io/projects/spring-cloud-openfeign + - Spring Boot Actuator Documentation: https://www.baeldung.com/spring-boot-actuators \ No newline at end of file diff --git a/microservices-self-registration/application.log.2025-04-09.0.gz b/microservices-self-registration/application.log.2025-04-09.0.gz new file mode 100644 index 000000000000..d51965d73d7a Binary files /dev/null and b/microservices-self-registration/application.log.2025-04-09.0.gz differ diff --git a/microservices-self-registration/contextservice/.gitattributes b/microservices-self-registration/contextservice/.gitattributes new file mode 100644 index 000000000000..3b41682ac579 --- /dev/null +++ b/microservices-self-registration/contextservice/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/microservices-self-registration/contextservice/.gitignore b/microservices-self-registration/contextservice/.gitignore new file mode 100644 index 000000000000..549e00a2a96f --- /dev/null +++ b/microservices-self-registration/contextservice/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/microservices-self-registration/contextservice/application.log.2025-04-05.0.gz b/microservices-self-registration/contextservice/application.log.2025-04-05.0.gz new file mode 100644 index 000000000000..6ceb03b833a7 Binary files /dev/null and b/microservices-self-registration/contextservice/application.log.2025-04-05.0.gz differ diff --git a/microservices-self-registration/contextservice/application.log.2025-04-07.0.gz b/microservices-self-registration/contextservice/application.log.2025-04-07.0.gz new file mode 100644 index 000000000000..eb2a63ce194e Binary files /dev/null and b/microservices-self-registration/contextservice/application.log.2025-04-07.0.gz differ diff --git a/microservices-self-registration/contextservice/application.log.2025-04-09.0.gz b/microservices-self-registration/contextservice/application.log.2025-04-09.0.gz new file mode 100644 index 000000000000..bd773dc8ba59 Binary files /dev/null and b/microservices-self-registration/contextservice/application.log.2025-04-09.0.gz differ diff --git a/microservices-self-registration/contextservice/pom.xml b/microservices-self-registration/contextservice/pom.xml new file mode 100644 index 000000000000..964ebdecee4e --- /dev/null +++ b/microservices-self-registration/contextservice/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + com.learning + contextservice + 0.0.1-SNAPSHOT + contextservice + contextservice + + + 2024.0.1 + + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + 1.18.38 + provided + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + com.diffplug.spotless + spotless-maven-plugin + 3.8.0 + + + + check + apply + + + + + + + 1.17.0 + + + + + + + + \ No newline at end of file diff --git a/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/ContextserviceApplication.java b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/ContextserviceApplication.java new file mode 100644 index 000000000000..01335dcc28c1 --- /dev/null +++ b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/ContextserviceApplication.java @@ -0,0 +1,16 @@ +package com.learning.contextservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableDiscoveryClient +@EnableFeignClients +public class ContextserviceApplication { + + public static void main(String[] args) { + SpringApplication.run(ContextserviceApplication.class, args); + } +} diff --git a/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/MyCustomHealthCheck.java b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/MyCustomHealthCheck.java new file mode 100644 index 000000000000..554ab2e83aef --- /dev/null +++ b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/MyCustomHealthCheck.java @@ -0,0 +1,43 @@ +package com.learning.contextservice; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component("myCustomHealthCheck") +public class MyCustomHealthCheck implements HealthIndicator { + + private static final Logger log = LoggerFactory.getLogger(MyCustomHealthCheck.class); + + private volatile boolean isHealthy = true; + + @Scheduled(fixedRate = 5000) // Run every 5 seconds + public void updateHealthStatus() { + // Perform checks here to determine the current health + // For example, check database connectivity, external service availability, etc. + isHealthy = performHealthCheck(); + log.info("Update health status : {}", isHealthy); + } + + boolean performHealthCheck() { + boolean current = System.currentTimeMillis() % 10000 < 5000; // Simulate fluctuating health + log.debug("Performing health check, current status: {}", current); + return current; // Simulate fluctuating health + } + + @Override + public Health health() { + if (isHealthy) { + log.info("Health check successful, service is UP"); + return Health.up() + .withDetail("message", "Service is running and scheduled checks are OK") + .build(); + } else { + log.warn("Health check failed, service is DOWN"); + return Health.down().withDetail("error", "Scheduled health checks failed").build(); + } + } +} diff --git a/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/client/GreetingServiceClient.java b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/client/GreetingServiceClient.java new file mode 100644 index 000000000000..367a3bdd496c --- /dev/null +++ b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/client/GreetingServiceClient.java @@ -0,0 +1,11 @@ +package com.learning.contextservice.client; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +@FeignClient(name = "greetingservice") +public interface GreetingServiceClient { + + @GetMapping("/greeting") + String getGreeting(); +} diff --git a/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/controller/ContextController.java b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/controller/ContextController.java new file mode 100644 index 000000000000..3b5febb80028 --- /dev/null +++ b/microservices-self-registration/contextservice/src/main/java/com/learning/contextservice/controller/ContextController.java @@ -0,0 +1,27 @@ +package com.learning.contextservice.controller; + +import com.learning.contextservice.client.GreetingServiceClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ContextController { + + private final GreetingServiceClient greetingServiceClient; + private final String userRegion; + + @Autowired + public ContextController( + GreetingServiceClient greetingServiceClient, @Value("${user.region}") String userRegion) { + this.greetingServiceClient = greetingServiceClient; + this.userRegion = userRegion; + } + + @GetMapping("/context") + public String getContext() { + String greeting = greetingServiceClient.getGreeting(); + return "The Greeting Service says: " + greeting + " from " + userRegion; + } +} diff --git a/microservices-self-registration/contextservice/src/main/resources/application.yml b/microservices-self-registration/contextservice/src/main/resources/application.yml new file mode 100644 index 000000000000..dfef73bbbeec --- /dev/null +++ b/microservices-self-registration/contextservice/src/main/resources/application.yml @@ -0,0 +1,25 @@ +server: + port: 8082 + +spring: + application: + name: contextservice + +eureka: + client: + service-url.defaultZone: http://localhost:8761/eureka + +user: + region: Chennai, Tamil Nadu, India + +management: + endpoint: + health: + show-details: always + web: + exposure: + include: health + +logging: + file: + name: application.log diff --git a/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextControllerTest.java b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextControllerTest.java new file mode 100644 index 000000000000..8fba01f0c3b5 --- /dev/null +++ b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextControllerTest.java @@ -0,0 +1,50 @@ +package com.learning.contextservice; + +import com.learning.contextservice.client.GreetingServiceClient; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@SpringBootTest(classes = ContextserviceApplication.class) +@AutoConfigureMockMvc +@Import(TestConfig.class) +class ContextControllerTest { + + @Autowired private MockMvc mockMvc; + + @MockitoBean private GreetingServiceClient greetingServiceClient; + + @Value("${user.region}") + private String userRegion; + + @Test + void shouldReturnContextGreeting() throws Exception { + Mockito.when(greetingServiceClient.getGreeting()).thenReturn("Mocked Hello"); + + mockMvc + .perform(MockMvcRequestBuilders.get("/context").accept(MediaType.TEXT_PLAIN)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect( + MockMvcResultMatchers.content() + .string("The Greeting Service says: Mocked Hello from Chennai, Tamil Nadu, India")); + } + + @Test + void shouldReturnContextServiceHealthStatusUp() throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.get("/actuator/health")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect( + MockMvcResultMatchers.content().string(Matchers.containsString("\"status\":\"UP\""))); + } +} diff --git a/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextserviceApplicationTests.java b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextserviceApplicationTests.java new file mode 100644 index 000000000000..aa789ad92cbd --- /dev/null +++ b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/ContextserviceApplicationTests.java @@ -0,0 +1,18 @@ +package com.learning.contextservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ContextserviceApplicationTests { + + @Test + void contextLoads() { + // This is a basic integration test that checks if the Spring Application Context loads + // successfully. + // If the context loads without any exceptions, the test is considered passing. + // It is often left empty as the act of loading the context is the primary verification. + // You can add specific assertions here if you want to verify the presence or state of certain + // beans. + } +} diff --git a/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/TestConfig.java b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/TestConfig.java new file mode 100644 index 000000000000..f378f46f59df --- /dev/null +++ b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/TestConfig.java @@ -0,0 +1,17 @@ +package com.learning.contextservice; + +import com.learning.contextservice.client.GreetingServiceClient; +import org.mockito.Mockito; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TestConfig { + + @Bean + public GreetingServiceClient greetingServiceClient() { + GreetingServiceClient mockClient = Mockito.mock(GreetingServiceClient.class); + Mockito.when(mockClient.getGreeting()).thenReturn("Mocked Hello"); + return mockClient; + } +} diff --git a/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/myCustomHealthCheckTest.java b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/myCustomHealthCheckTest.java new file mode 100644 index 000000000000..d771a1eed9ae --- /dev/null +++ b/microservices-self-registration/contextservice/src/test/java/com/learning/contextservice/myCustomHealthCheckTest.java @@ -0,0 +1,34 @@ +package com.learning.contextservice; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.test.util.ReflectionTestUtils; + +class MyCustomHealthCheckTest { + + @Test + void testHealthUp() { + MyCustomHealthCheck healthCheck = new MyCustomHealthCheck(); + // Simulate a healthy state + ReflectionTestUtils.setField(healthCheck, "isHealthy", true); + Health health = healthCheck.health(); + assertEquals(Status.UP, health.getStatus()); + assertTrue(health.getDetails().containsKey("message")); + assertEquals( + "Service is running and scheduled checks are OK", health.getDetails().get("message")); + } + + @Test + void testHealthDown() { + MyCustomHealthCheck healthCheck = new MyCustomHealthCheck(); + // Simulate an unhealthy state + ReflectionTestUtils.setField(healthCheck, "isHealthy", false); + Health health = healthCheck.health(); + assertEquals(Status.DOWN, health.getStatus()); + assertTrue(health.getDetails().containsKey("error")); + assertEquals("Scheduled health checks failed", health.getDetails().get("error")); + } +} diff --git a/microservices-self-registration/eurekaserver/.gitattributes b/microservices-self-registration/eurekaserver/.gitattributes new file mode 100644 index 000000000000..3b41682ac579 --- /dev/null +++ b/microservices-self-registration/eurekaserver/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/microservices-self-registration/eurekaserver/.gitignore b/microservices-self-registration/eurekaserver/.gitignore new file mode 100644 index 000000000000..549e00a2a96f --- /dev/null +++ b/microservices-self-registration/eurekaserver/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/microservices-self-registration/eurekaserver/pom.xml b/microservices-self-registration/eurekaserver/pom.xml new file mode 100644 index 000000000000..d8b923b813cf --- /dev/null +++ b/microservices-self-registration/eurekaserver/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + com.learning + eurekaserver + 0.0.1-SNAPSHOT + eurekaserver + eurekaserver + + + 2024.0.1 + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + com.diffplug.spotless + spotless-maven-plugin + 3.8.0 + + + + check + apply + + + + + + + 1.17.0 + + + + + + + + \ No newline at end of file diff --git a/microservices-self-registration/eurekaserver/src/main/java/com/learning/eurekaserver/EurekaserverApplication.java b/microservices-self-registration/eurekaserver/src/main/java/com/learning/eurekaserver/EurekaserverApplication.java new file mode 100644 index 000000000000..80b888f5910c --- /dev/null +++ b/microservices-self-registration/eurekaserver/src/main/java/com/learning/eurekaserver/EurekaserverApplication.java @@ -0,0 +1,14 @@ +package com.learning.eurekaserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class EurekaserverApplication { + + public static void main(String[] args) { + SpringApplication.run(EurekaserverApplication.class, args); + } +} diff --git a/microservices-self-registration/eurekaserver/src/main/resources/application.yml b/microservices-self-registration/eurekaserver/src/main/resources/application.yml new file mode 100644 index 000000000000..51f8a815d251 --- /dev/null +++ b/microservices-self-registration/eurekaserver/src/main/resources/application.yml @@ -0,0 +1,10 @@ +server: + port: 8761 + +eureka: + client: + register-with-eureka: false + fetch-registry: false + server: + enable-self-preservation: true + diff --git a/microservices-self-registration/eurekaserver/src/test/java/com/learning/eurekaserver/EurekaserverApplicationTests.java b/microservices-self-registration/eurekaserver/src/test/java/com/learning/eurekaserver/EurekaserverApplicationTests.java new file mode 100644 index 000000000000..4f846888281d --- /dev/null +++ b/microservices-self-registration/eurekaserver/src/test/java/com/learning/eurekaserver/EurekaserverApplicationTests.java @@ -0,0 +1,18 @@ +package com.learning.eurekaserver; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EurekaserverApplicationTests { + + @Test + void contextLoads() { + // This is a basic integration test that checks if the Spring Application Context loads + // successfully. + // If the context loads without any exceptions, the test is considered passing. + // It is often left empty as the act of loading the context is the primary verification. + // You can add specific assertions here if you want to verify the presence or state of certain + // beans. + } +} diff --git a/microservices-self-registration/greetingservice/.gitattributes b/microservices-self-registration/greetingservice/.gitattributes new file mode 100644 index 000000000000..3b41682ac579 --- /dev/null +++ b/microservices-self-registration/greetingservice/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/microservices-self-registration/greetingservice/.gitignore b/microservices-self-registration/greetingservice/.gitignore new file mode 100644 index 000000000000..549e00a2a96f --- /dev/null +++ b/microservices-self-registration/greetingservice/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/microservices-self-registration/greetingservice/application.log.2025-04-05.0.gz b/microservices-self-registration/greetingservice/application.log.2025-04-05.0.gz new file mode 100644 index 000000000000..93d6a2e62ac1 Binary files /dev/null and b/microservices-self-registration/greetingservice/application.log.2025-04-05.0.gz differ diff --git a/microservices-self-registration/greetingservice/application.log.2025-04-07.0.gz b/microservices-self-registration/greetingservice/application.log.2025-04-07.0.gz new file mode 100644 index 000000000000..40c96f702853 Binary files /dev/null and b/microservices-self-registration/greetingservice/application.log.2025-04-07.0.gz differ diff --git a/microservices-self-registration/greetingservice/application.log.2025-04-09.0.gz b/microservices-self-registration/greetingservice/application.log.2025-04-09.0.gz new file mode 100644 index 000000000000..59f2cbc3c8df Binary files /dev/null and b/microservices-self-registration/greetingservice/application.log.2025-04-09.0.gz differ diff --git a/microservices-self-registration/greetingservice/application.log.2025-04-11.0.gz b/microservices-self-registration/greetingservice/application.log.2025-04-11.0.gz new file mode 100644 index 000000000000..62d73c3020c1 Binary files /dev/null and b/microservices-self-registration/greetingservice/application.log.2025-04-11.0.gz differ diff --git a/microservices-self-registration/greetingservice/pom.xml b/microservices-self-registration/greetingservice/pom.xml new file mode 100644 index 000000000000..b6a92aabc8a3 --- /dev/null +++ b/microservices-self-registration/greetingservice/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + com.learning + greetingservice + 0.0.1-SNAPSHOT + greetingservice + greetingservice + + + 2024.0.1 + + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + 1.18.38 + provided + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + com.diffplug.spotless + spotless-maven-plugin + 3.8.0 + + + + check + apply + + + + + + + 1.17.0 + + + + + + + + \ No newline at end of file diff --git a/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/GreetingserviceApplication.java b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/GreetingserviceApplication.java new file mode 100644 index 000000000000..93b3d3041996 --- /dev/null +++ b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/GreetingserviceApplication.java @@ -0,0 +1,16 @@ +package com.learning.greetingservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@EnableDiscoveryClient +@ComponentScan("com.learning.greetingservice.controller") +public class GreetingserviceApplication { + + public static void main(String[] args) { + SpringApplication.run(GreetingserviceApplication.class, args); + } +} diff --git a/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/MyCustomHealthCheck.java b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/MyCustomHealthCheck.java new file mode 100644 index 000000000000..639a402fc70a --- /dev/null +++ b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/MyCustomHealthCheck.java @@ -0,0 +1,43 @@ +package com.learning.greetingservice; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component("myCustomHealthCheck") +public class MyCustomHealthCheck implements HealthIndicator { + + private static final Logger log = LoggerFactory.getLogger(MyCustomHealthCheck.class); + + private volatile boolean isHealthy = true; + + @Scheduled(fixedRate = 5000) // Run every 5 seconds + public void updateHealthStatus() { + // Perform checks here to determine the current health + // For example, check database connectivity, external service availability, etc. + isHealthy = performHealthCheck(); + log.info("Update health status : {}", isHealthy); + } + + boolean performHealthCheck() { + boolean current = System.currentTimeMillis() % 10000 < 5000; // Simulate fluctuating health + log.debug("Performing health check, current status: {}", current); + return current; // Simulate fluctuating health + } + + @Override + public Health health() { + if (isHealthy) { + log.info("Health check successful, service is UP"); + return Health.up() + .withDetail("message", "Service is running and scheduled checks are OK") + .build(); + } else { + log.warn("Health check failed, service is DOWN"); + return Health.down().withDetail("error", "Scheduled health checks failed").build(); + } + } +} diff --git a/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/controller/GreetingsController.java b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/controller/GreetingsController.java new file mode 100644 index 000000000000..ea385beb1abe --- /dev/null +++ b/microservices-self-registration/greetingservice/src/main/java/com/learning/greetingservice/controller/GreetingsController.java @@ -0,0 +1,13 @@ +package com.learning.greetingservice.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GreetingsController { + + @GetMapping("/greeting") + public String getGreeting() { + return "Hello"; + } +} diff --git a/microservices-self-registration/greetingservice/src/main/resources/application.yml b/microservices-self-registration/greetingservice/src/main/resources/application.yml new file mode 100644 index 000000000000..adcfac884c2b --- /dev/null +++ b/microservices-self-registration/greetingservice/src/main/resources/application.yml @@ -0,0 +1,22 @@ +server: + port: 8081 + +spring: + application: + name: greetingservice +eureka: + client: + service-url.defaultZone: http://localhost:8761/eureka + +management: + endpoint: + health: + show-details: always + web: + exposure: + include: health + +logging: + file: + name: application.log + diff --git a/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/GreetingserviceApplicationTests.java b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/GreetingserviceApplicationTests.java new file mode 100644 index 000000000000..0f00c8ab435c --- /dev/null +++ b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/GreetingserviceApplicationTests.java @@ -0,0 +1,18 @@ +package com.learning.greetingservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class GreetingserviceApplicationTests { + + @Test + void contextLoads() { + // This is a basic integration test that checks if the Spring Application Context loads + // successfully. + // If the context loads without any exceptions, the test is considered passing. + // It is often left empty as the act of loading the context is the primary verification. + // You can add specific assertions here if you want to verify the presence or state of certain + // beans. + } +} diff --git a/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/MyCustomHealthCheckTest.java b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/MyCustomHealthCheckTest.java new file mode 100644 index 000000000000..6e67f875c154 --- /dev/null +++ b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/MyCustomHealthCheckTest.java @@ -0,0 +1,23 @@ +package com.learning.greetingservice; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.test.util.ReflectionTestUtils; + +class MyCustomHealthCheckTest { + + @Test + void testHealthUp() { + MyCustomHealthCheck healthCheck = new MyCustomHealthCheck(); + // Simulate a healthy state + ReflectionTestUtils.setField(healthCheck, "isHealthy", true); + Health health = healthCheck.health(); + assertEquals(Status.UP, health.getStatus()); + assertTrue(health.getDetails().containsKey("message")); + assertEquals( + "Service is running and scheduled checks are OK", health.getDetails().get("message")); + } +} diff --git a/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/controller/GreetingControllerTest.java b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/controller/GreetingControllerTest.java new file mode 100644 index 000000000000..22fa8ecf3568 --- /dev/null +++ b/microservices-self-registration/greetingservice/src/test/java/com/learning/greetingservice/controller/GreetingControllerTest.java @@ -0,0 +1,38 @@ +package com.learning.greetingservice.controller; + +import com.learning.greetingservice.GreetingserviceApplication; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@SpringBootTest(classes = GreetingserviceApplication.class) +@AutoConfigureMockMvc +@ActiveProfiles("test") +class GreetingControllerTest { + + @Autowired private MockMvc mockMvc; + + @Test + void shouldReturnGreeting() throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.get("/greeting").accept(MediaType.TEXT_PLAIN)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("Hello")); + } + + @Test + void shouldReturnHealthStatusUp() throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.get("/actuator/health")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect( + MockMvcResultMatchers.content() + .string(org.hamcrest.Matchers.containsString("\"status\":\"UP\""))); + } +} diff --git a/microservices-self-registration/pom.xml b/microservices-self-registration/pom.xml new file mode 100644 index 000000000000..fd98b12d8587 --- /dev/null +++ b/microservices-self-registration/pom.xml @@ -0,0 +1,42 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + microservices-self-registration + pom + + eurekaserver + greetingservice + contextservice + + diff --git a/model-view-viewmodel/pom.xml b/model-view-viewmodel/pom.xml index 248eb9e7d507..e77d53ef7396 100644 --- a/model-view-viewmodel/pom.xml +++ b/model-view-viewmodel/pom.xml @@ -37,7 +37,7 @@ 10.0.0-jakarta 11.0.24 - 3.4.0 + 3.5.1 yyyy-MM-dd -${project.version}-FL-${maven.build.timestamp} diff --git a/onion-architecture/README.md b/onion-architecture/README.md new file mode 100644 index 000000000000..1a7fc394638d --- /dev/null +++ b/onion-architecture/README.md @@ -0,0 +1,292 @@ +--- +title: "Onion Architecture in Java: A Layered Approach to Building Maintainable and Testable Applications" +shortTitle: Onion Architecture +description: "Learn how the Onion Architecture pattern promotes maintainability, testability, and separation of concerns in Java applications. Explore examples, benefits, and best practices." +category: Architectural +language: en +tag: + - Decoupling + - Enterprise patterns + - Integration + - Microservices + - Scalability + - Security +--- +## Intent of Microservices API Gateway Design Pattern + +In this project, the implementation demonstrates **Onion Architecture** with clear dependency direction: infrastructure and application depend on domain, but domain is independent. + +The central intent is to keep business rules in `domain`, orchestrate use cases in `application`, and isolate delivery/persistence/API details in `infrastructure`. + +Current implementation highlights: + +* `domain`: `Person`, `Category`, `PersonRepository`, `DomainException` +* `application`: `SavePersonUseCase`, `GetPersonUseCase`, DTO records +* `infrastructure`: Spring Boot REST controller, JPA entities, repository adapter, bean wiring + +## Also known as + +* Ports and Adapters Architecture +* Hexagonal-style layering (conceptually related) +* Dependency-rule-first architecture + +## Detailed Explanation of Onion Architecture Pattern with Real-World Examples + +Real-world example + +> Imagine a people-management service where business validation must stay consistent no matter how data is stored or exposed. In this codebase, `Person` and `Category` enforce invariants (e.g., age >= 18, required email/category), use cases coordinate behavior, and infrastructure adapts HTTP + JPA concerns. This allows the persistence or web layer to evolve without changing core domain rules. + +In plain words + +> The project keeps business logic in the center and treats frameworks as replaceable details around it. + +Wikipedia says + +> Onion Architecture is a software architecture pattern that emphasizes separation of concerns and dependency inversion by organizing code in concentric layers, with the domain model at the center. + +Sequence diagram + +![Onion Architecture class diagram](./etc/onion-architecture.png) + +Request flow in this implementation: + +1. Client calls REST endpoint in `PersonController` (`/api/persons`, `/api/persons/{id}`) +2. Controller delegates to `SavePersonUseCase` or `GetPersonUseCase` +3. Use case interacts with `PersonRepository` abstraction from `domain` +4. `PersonRepositoryAdapter` maps domain <-> JPA and delegates to `SpringDataPersonRepository` +5. Response DTO (`PersonResponse`) is returned to the client + +## Programmatic Example of Onion Architecture in Java + +This repository exposes a simple person API backed by use cases and domain models. + +Controller (infrastructure layer): + +```java +@RestController +@RequestMapping("/api") +public class PersonController { + + @GetMapping("/persons/{id}") + public ResponseEntity getPerson(@PathVariable Long id) { + var person = getPersonUseCase.execute(id); + return ResponseEntity.ok(person); + } + + @GetMapping("/persons") + public ResponseEntity> getAllPersons() { + var persons = getPersonUseCase.executeAll(); + return ResponseEntity.ok(persons); + } + + @PostMapping("/persons") + public ResponseEntity savePerson(@RequestBody SavePersonCommand command) { + try { + var savedPerson = savePersonUseCase.execute(command); + return ResponseEntity.status(HttpStatus.OK).body(savedPerson); + } catch (DomainException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); + } + } +} +``` + +Use case (application layer): + +```java +public class SavePersonUseCase { + + private final PersonRepository repository; + + public PersonResponse execute(SavePersonCommand command) { + var category = new Category(command.categoryId(), command.categoryType()); + var person = new Person( + null, + command.firstName(), + command.lastName(), + command.age(), + command.phoneNumber(), + command.email(), + category); + + var savedPerson = repository.save(person); + return new PersonResponse( + savedPerson.getId(), + savedPerson.getFirstName(), + savedPerson.getLastName(), + savedPerson.getAge(), + savedPerson.getPhoneNumber(), + savedPerson.getEmail(), + savedPerson.getCategory().getId(), + savedPerson.getCategory().getType() + ); + } +} +``` + +Domain validation (domain layer): + +```java +public class Person { + public Person(Long id, String firstName, String lastName, int age, + String phoneNumber, String email, Category category) { + validateNames(firstName, lastName); + validateAge(age); + validatePhone(phoneNumber); + validateEmail(email); + validateCategory(category); + // assign fields... + } +} +``` + +Repository adapter (infrastructure -> domain port): + +```java +@Repository +public class PersonRepositoryAdapter implements PersonRepository { + + private final SpringDataPersonRepository repository; + + @Override + public Optional findById(Long id) { + return repository.findById(id).map(this::mapToDomain); + } + + @Override + public Person save(Person person) { + JpaPersonEntity savedEntity = repository.save(mapToEntity(person)); + return mapToDomain(savedEntity); + } +} +``` + +- **Maven 3.6.0** or higher + +### Build Steps + +1. **Navigate to the onion-architecture module directory:** + ```bash + cd java-design-patterns/onion-architecture + ``` + +2. **Build all modules:** + ```bash + mvn clean package + ``` + This will compile the `domain`, `application`, and `infrastructure` modules and package them into a Spring Boot executable JAR. + +3. **Run the Spring Boot application:** + ```bash + mvn -pl infrastructure spring-boot:run + ``` + Alternatively, after building, run the JAR directly: + ```bash + java -jar infrastructure/target/infrastructure-1.26.0-SNAPSHOT.jar + ``` + +### Accessing the API + +The application exposes REST endpoints at `http://localhost:8080/api`: +There is a Postman collection available in the `etc/postman` folder for testing the API. + +- **Get all persons:** + ```bash + GET http://localhost:8080/api/persons + ``` + +- **Get person by ID:** + ```bash + GET http://localhost:8080/api/persons/{id} + ``` + +- **Create a new person:** + ```bash + POST http://localhost:8080/api/persons + Content-Type: application/json + + { + "firstName": "John", + "lastName": "Doe", + "age": 30, + "phoneNumber": "555-1234", + "email": "john.doe@example.com", + "address": "123 Main St", + "categoryId": 1, + "categoryType": "individual" + } + ``` + +### Run Tests + +To execute unit tests across all modules: + +```bash +mvn clean test +``` + +To run tests for a specific module: + +```bash +mvn -pl domain test +mvn -pl application test +mvn -pl infrastructure test +``` + +### Database + +The application uses an **H2 in-memory database** for demonstration purposes. Configuration is in `infrastructure/src/main/resources/application.properties`: + +- **JDBC URL:** `jdbc:h2:mem:testdb` +- **Username:** `sa` +- **Password:** `password` + +Sample data is initialized from `infrastructure/src/main/resources/data.sql` on application startup. + +## When to Use the Onion Architecture Pattern in Java + +* When domain rules must be stable and independent from frameworks. +* When you want use cases to be testable without HTTP or database setup. +* When infrastructure details (web, JPA, database) should be replaceable. +* When dependency direction must be enforced from outer layers toward the domain core. + +## Onion Architecture Pattern Java Tutorials + +* [Clean Architecture with Spring Boot (Baeldung)](https://www.baeldung.com/spring-boot-clean-architecture) +* [Hexagonal Architecture Explained (Cockburn)](https://alistair.cockburn.us/hexagonal-architecture) +* [Spring Data JPA Reference](https://docs.spring.io/spring-data/jpa/reference/) + +## Benefits and Trade-offs of Microservices API Gateway Pattern + +Benefits: + +* Business validations are centralized in domain constructors (`Person`, `Category`). +* Use cases stay independent from Spring, JPA, and transport concerns. +* Repository abstraction (`PersonRepository`) keeps application logic persistence-agnostic. +* Testability is strong across layers (domain, use case, adapter, controller tests). + +Trade-offs: + +* Additional mapping code between domain models, DTOs, and JPA entities. +* More classes and modules than a simple CRUD-by-controller approach. +* Requires discipline to avoid leaking infrastructure concerns into domain/application. + +## Real-World Applications of Microservices API Gateway Pattern in Java + +* People/contact management services with strict data validation. +* Internal platforms where multiple delivery mechanisms (REST, batch, messaging) can share the same core domain. +* Systems that need incremental infrastructure evolution while preserving business logic. + +## Related Java Design Patterns + +* [Repository](https://martinfowler.com/eaaCatalog/repository.html) - `PersonRepository` defines the domain-facing persistence contract. +* [Adapter](https://refactoring.guru/design-patterns/adapter) - `PersonRepositoryAdapter` bridges domain model and Spring Data JPA. +* [Dependency Injection](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html) - `ApplicationConfig` wires use case beans with repository implementations. + +## References and Credits + +* Project modules: `domain`, `application`, `infrastructure` +* Java 21 + Maven multi-module setup +* Spring Boot 3.3 (`spring-boot-starter-web`, `spring-boot-starter-data-jpa`, H2) +* Layer-focused tests in each module validating domain invariants and use case behavior + diff --git a/onion-architecture/application/pom.xml b/onion-architecture/application/pom.xml new file mode 100644 index 000000000000..eccdaae2869a --- /dev/null +++ b/onion-architecture/application/pom.xml @@ -0,0 +1,66 @@ + + + + 4.0.0 + + com.iluwatar + onion-architecture + 1.26.0-SNAPSHOT + + application + Application + + + + com.iluwatar + domain + ${project.version} + + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.mockito + mockito-core + test + + + + org.mockito + mockito-junit-jupiter + test + + + diff --git a/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/PersonResponse.java b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/PersonResponse.java new file mode 100644 index 000000000000..1586f30e48a1 --- /dev/null +++ b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/PersonResponse.java @@ -0,0 +1,37 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.dto; + +public record PersonResponse( + Long id, + String firstName, + String lastName, + int age, + String phoneNumber, + String email, + Long categoryId, + String categoryType) {} diff --git a/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/SavePersonCommand.java b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/SavePersonCommand.java new file mode 100644 index 000000000000..649db88a4ab5 --- /dev/null +++ b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/dto/SavePersonCommand.java @@ -0,0 +1,37 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.dto; + +public record SavePersonCommand( + String firstName, + String lastName, + int age, + String phoneNumber, + String email, + String address, + Long categoryId, + String categoryType) {} diff --git a/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/GetPersonUseCase.java b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/GetPersonUseCase.java new file mode 100644 index 000000000000..abae6a32196a --- /dev/null +++ b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/GetPersonUseCase.java @@ -0,0 +1,75 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.usecase; + +import com.iluwatar.onion.application.dto.PersonResponse; +import com.iluwatar.onion.domain.repository.PersonRepository; +import java.util.Collection; +import java.util.List; + +public class GetPersonUseCase { + + private final PersonRepository repository; + + public GetPersonUseCase(PersonRepository repository) { + this.repository = repository; + } + + public PersonResponse execute(Long id) { + var person = + repository + .findById(id) + .orElseThrow(() -> new RuntimeException("Person not found with id: " + id)); + + return new PersonResponse( + person.getId(), + person.getFirstName(), + person.getLastName(), + person.getAge(), + person.getPhoneNumber(), + person.getEmail(), + person.getCategory().getId(), + person.getCategory().getType()); + } + + public List executeAll() { + return repository.findAll().stream() + .flatMap(Collection::stream) + .map( + person -> + new PersonResponse( + person.getId(), + person.getFirstName(), + person.getLastName(), + person.getAge(), + person.getPhoneNumber(), + person.getEmail(), + person.getCategory().getId(), + person.getCategory().getType())) + .toList(); + } +} diff --git a/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/SavePersonUseCase.java b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/SavePersonUseCase.java new file mode 100644 index 000000000000..8d63e2612fab --- /dev/null +++ b/onion-architecture/application/src/main/java/com/iluwatar/onion/application/usecase/SavePersonUseCase.java @@ -0,0 +1,67 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.usecase; + +import com.iluwatar.onion.application.dto.PersonResponse; +import com.iluwatar.onion.application.dto.SavePersonCommand; +import com.iluwatar.onion.domain.model.Category; +import com.iluwatar.onion.domain.model.Person; +import com.iluwatar.onion.domain.repository.PersonRepository; + +public class SavePersonUseCase { + + private final PersonRepository repository; + + public SavePersonUseCase(PersonRepository repository) { + this.repository = repository; + } + + public PersonResponse execute(SavePersonCommand command) { + var category = new Category(command.categoryId(), command.categoryType()); + var person = + new Person( + null, + command.firstName(), + command.lastName(), + command.age(), + command.phoneNumber(), + command.email(), + category); + + var savedPerson = repository.save(person); + + return new PersonResponse( + savedPerson.getId(), + savedPerson.getFirstName(), + savedPerson.getLastName(), + savedPerson.getAge(), + savedPerson.getPhoneNumber(), + savedPerson.getEmail(), + savedPerson.getCategory().getId(), + savedPerson.getCategory().getType()); + } +} diff --git a/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/GetPersonUseCaseTest.java b/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/GetPersonUseCaseTest.java new file mode 100644 index 000000000000..f9de119c2309 --- /dev/null +++ b/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/GetPersonUseCaseTest.java @@ -0,0 +1,193 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.usecase; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import com.iluwatar.onion.application.dto.PersonResponse; +import com.iluwatar.onion.domain.model.Category; +import com.iluwatar.onion.domain.model.Person; +import com.iluwatar.onion.domain.repository.PersonRepository; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class GetPersonUseCaseTest { + + @Mock private PersonRepository personRepository; + + private GetPersonUseCase getPersonUseCase; + + @BeforeEach + void setUp() { + getPersonUseCase = new GetPersonUseCase(personRepository); + } + + @Nested + @DisplayName("Execute by ID - Happy Path") + class ExecuteByIdHappyPath { + + @Test + @DisplayName("Should return PersonResponse when person exists") + void shouldReturnPersonResponseWhenPersonExists() { + // Arrange + var person = + new Person( + 1L, + "John", + "Doe", + 25, + "+1234567890", + "john.doe@example.com", + new Category(1L, "Professional")); + + when(personRepository.findById(1L)).thenReturn(Optional.of(person)); + + // Act + var response = getPersonUseCase.execute(1L); + + // Assert + assertNotNull(response); + assertEquals(1L, response.id()); + assertEquals("John", response.firstName()); + assertEquals("Doe", response.lastName()); + assertEquals(25, response.age()); + assertEquals("+1234567890", response.phoneNumber()); + assertEquals("john.doe@example.com", response.email()); + assertEquals(1L, response.categoryId()); + assertEquals("Professional", response.categoryType()); + + verify(personRepository, times(1)).findById(1L); + } + } + + @Nested + @DisplayName("Execute by ID - Error Cases") + class ExecuteByIdErrorCases { + + @Test + @DisplayName("Should throw RuntimeException when person not found") + void shouldThrowExceptionWhenPersonNotFound() { + // Arrange + when(personRepository.findById(999L)).thenReturn(Optional.empty()); + + // Act & Assert + var exception = assertThrows(RuntimeException.class, () -> getPersonUseCase.execute(999L)); + assertTrue(exception.getMessage().contains("Person not found with id: 999")); + + verify(personRepository, times(1)).findById(999L); + } + + @Test + @DisplayName("Should propagate exception when repository throws exception") + void shouldPropagateExceptionWhenRepositoryFails() { + // Arrange + when(personRepository.findById(anyLong())).thenThrow(new RuntimeException("Database error")); + + // Act & Assert + var exception = assertThrows(RuntimeException.class, () -> getPersonUseCase.execute(1L)); + assertTrue(exception.getMessage().contains("Database error")); + + verify(personRepository, times(1)).findById(1L); + } + } + + @Nested + @DisplayName("Execute All - Happy Path") + class ExecuteAllHappyPath { + + @Test + @DisplayName("Should return list of PersonResponses") + void shouldReturnListOfPersonResponses() { + // Arrange + var person1 = + new Person( + 1L, + "John", + "Doe", + 30, + "+9876543255", + "john.doe@example.com", + new Category(2L, "Personal")); + + var person2 = + new Person( + 2L, + "Jane", + "Smith", + 25, + "+9876543210", + "jane.smith@example.com", + new Category(2L, "Personal")); + + when(personRepository.findAll()).thenReturn(Optional.of(List.of(person1, person2))); + + // Act + var responses = getPersonUseCase.executeAll(); + + // Assert + assertNotNull(responses); + assertEquals(2, responses.size()); + + PersonResponse response1 = responses.get(0); + assertEquals(1L, response1.id()); + assertEquals("John", response1.firstName()); + assertEquals("Doe", response1.lastName()); + + PersonResponse response2 = responses.get(1); + assertEquals(2L, response2.id()); + assertEquals("Jane", response2.firstName()); + assertEquals("Smith", response2.lastName()); + + verify(personRepository, times(1)).findAll(); + } + + @Test + @DisplayName("Should return empty list when no persons found") + void shouldReturnEmptyListWhenNoPersonsFound() { + // Arrange + when(personRepository.findAll()).thenReturn(Optional.of(List.of())); + + // Act + List responses = getPersonUseCase.executeAll(); + + // Assert + assertNotNull(responses); + assertTrue(responses.isEmpty()); + + verify(personRepository, times(1)).findAll(); + } + } +} diff --git a/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/SavePersonUseCaseTest.java b/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/SavePersonUseCaseTest.java new file mode 100644 index 000000000000..434147ae6495 --- /dev/null +++ b/onion-architecture/application/src/test/java/com/iluwatar/onion/application/usecase/SavePersonUseCaseTest.java @@ -0,0 +1,253 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.application.usecase; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.iluwatar.onion.application.dto.SavePersonCommand; +import com.iluwatar.onion.domain.exception.DomainException; +import com.iluwatar.onion.domain.model.Category; +import com.iluwatar.onion.domain.model.Person; +import com.iluwatar.onion.domain.repository.PersonRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class SavePersonUseCaseTest { + + @Mock private PersonRepository personRepository; + + @Captor private ArgumentCaptor personCaptor; + + private SavePersonUseCase savePersonUseCase; + + @BeforeEach + void setUp() { + savePersonUseCase = new SavePersonUseCase(personRepository); + } + + @Nested + @DisplayName("Execute - Happy Path") + class ExecuteHappyPath { + + @Test + @DisplayName("Should save person and return PersonResponse") + void shouldSavePersonAndReturnResponse() { + // Arrange + var command = + new SavePersonCommand( + "John", + "Doe", + 25, + "+1234567890", + "john.doe@example.com", + "123 Main St", + 1L, + "Professional"); + + var category = new Category(1L, "Professional"); + var savedPerson = + new Person( + 100L, // ID generated by database + "John", + "Doe", + 25, + "+1234567890", + "john.doe@example.com", + category); + + when(personRepository.save(any(Person.class))).thenReturn(savedPerson); + + // Act + var response = savePersonUseCase.execute(command); + + // Assert + assertNotNull(response); + assertEquals(100L, response.id()); + assertEquals("John", response.firstName()); + assertEquals("Doe", response.lastName()); + assertEquals(25, response.age()); + assertEquals("+1234567890", response.phoneNumber()); + assertEquals("john.doe@example.com", response.email()); + assertEquals(1L, response.categoryId()); + assertEquals("Professional", response.categoryType()); + + // Verify repository interaction + verify(personRepository, times(1)).save(any(Person.class)); + } + + @Test + @DisplayName("Should pass correct Person object to repository") + void shouldPassCorrectPersonToRepository() { + // Arrange + var command = + new SavePersonCommand( + "Jane", + "Smith", + 30, + "+9876543210", + "jane.smith@example.com", + "456 Oak Ave", + 2L, + "Personal"); + + var category = new Category(2L, "Personal"); + var savedPerson = + new Person(200L, "Jane", "Smith", 30, "+9876543210", "jane.smith@example.com", category); + + when(personRepository.save(any(Person.class))).thenReturn(savedPerson); + + // Act + savePersonUseCase.execute(command); + + // Assert - Verify what was passed to repository + verify(personRepository).save(personCaptor.capture()); + var capturedPerson = personCaptor.getValue(); + + assertNull(capturedPerson.getId()); // New person should have null ID + assertEquals("Jane", capturedPerson.getFirstName()); + assertEquals("Smith", capturedPerson.getLastName()); + assertEquals(30, capturedPerson.getAge()); + assertEquals("+9876543210", capturedPerson.getPhoneNumber()); + assertEquals("jane.smith@example.com", capturedPerson.getEmail()); + assertEquals("Personal", capturedPerson.getCategory().getType()); + } + } + + @Nested + @DisplayName("Execute - Validation Failures") + class ExecuteValidationFailures { + + @Test + @DisplayName("Should throw DomainException when age is less than 18") + void shouldThrowExceptionWhenAgeIsInvalid() { + // Arrange + var command = + new SavePersonCommand( + "Young", + "Person", + 17, // Invalid age + "+1234567890", + "young@example.com", + "123 Main St", + 1L, + "Student"); + + // Act & Assert + var exception = assertThrows(DomainException.class, () -> savePersonUseCase.execute(command)); + assertTrue(exception.getMessage().contains("Age cannot be less than 18")); + + // Verify repository was never called + verify(personRepository, never()).save(any(Person.class)); + } + + @Test + @DisplayName("Should throw DomainException when email is empty") + void shouldThrowExceptionWhenEmailIsEmpty() { + // Arrange + var command = + new SavePersonCommand( + "John", + "Doe", + 25, + "+1234567890", + "", // Empty email + "123 Main St", + 1L, + "Professional"); + + // Act & Assert + var exception = assertThrows(DomainException.class, () -> savePersonUseCase.execute(command)); + assertTrue(exception.getMessage().contains("Email cannot be null or empty")); + + verify(personRepository, never()).save(any(Person.class)); + } + + @Test + @DisplayName("Should throw DomainException when category type is invalid") + void shouldThrowExceptionWhenCategoryTypeIsInvalid() { + // Arrange + var command = + new SavePersonCommand( + "John", + "Doe", + 25, + "+1234567890", + "john@example.com", + "123 Main St", + 1L, + "" // Empty category type + ); + + // Act & Assert + var exception = assertThrows(DomainException.class, () -> savePersonUseCase.execute(command)); + assertTrue(exception.getMessage().contains("Type is null or empty")); + + verify(personRepository, never()).save(any(Person.class)); + } + } + + @Nested + @DisplayName("Execute - Repository Exceptions") + class ExecuteRepositoryExceptions { + + @Test + @DisplayName("Should propagate exception when repository fails") + void shouldPropagateExceptionWhenRepositoryFails() { + // Arrange + var command = + new SavePersonCommand( + "John", + "Doe", + 25, + "+1234567890", + "john.doe@example.com", + "123 Main St", + 1L, + "Professional"); + + when(personRepository.save(any(Person.class))) + .thenThrow(new RuntimeException("Database connection failed")); + + // Act & Assert + var exception = + assertThrows(RuntimeException.class, () -> savePersonUseCase.execute(command)); + assertTrue(exception.getMessage().contains("Database connection failed")); + + verify(personRepository, times(1)).save(any(Person.class)); + } + } +} diff --git a/onion-architecture/domain/pom.xml b/onion-architecture/domain/pom.xml new file mode 100644 index 000000000000..d1efc50def12 --- /dev/null +++ b/onion-architecture/domain/pom.xml @@ -0,0 +1,47 @@ + + + + 4.0.0 + + com.iluwatar + onion-architecture + 1.26.0-SNAPSHOT + + domain + Domain + + + + + org.junit.jupiter + junit-jupiter-engine + test + + + diff --git a/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/exception/DomainException.java b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/exception/DomainException.java new file mode 100644 index 000000000000..5e0831a57c02 --- /dev/null +++ b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/exception/DomainException.java @@ -0,0 +1,34 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.exception; + +public class DomainException extends RuntimeException { + + public DomainException(String message) { + super(message); + } +} diff --git a/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Category.java b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Category.java new file mode 100644 index 000000000000..8380f4e849ee --- /dev/null +++ b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Category.java @@ -0,0 +1,51 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.model; + +import com.iluwatar.onion.domain.exception.DomainException; + +public class Category { + + private final Long id; + private final String type; + + public Category(Long id, String type) { + if (type == null || type.isEmpty()) { + throw new DomainException("Type is null or empty. Category type is required."); + } + this.id = id; + this.type = type; + } + + public Long getId() { + return id; + } + + public String getType() { + return type; + } +} diff --git a/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Person.java b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Person.java new file mode 100644 index 000000000000..55eced0be29a --- /dev/null +++ b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/model/Person.java @@ -0,0 +1,121 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.model; + +import com.iluwatar.onion.domain.exception.DomainException; + +public class Person { + + private final Long id; + private final String firstName; + private final String lastName; + private final int age; + private final String phoneNumber; + private final String email; + private final Category category; + + public Person( + Long id, + String firstName, + String lastName, + int age, + String phoneNumber, + String email, + Category category) { + validateNames(firstName, lastName); + validateAge(age); + validatePhone(phoneNumber); + validateEmail(email); + validateCategory(category); + + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.phoneNumber = phoneNumber; + this.email = email; + this.category = category; + } + + private void validateNames(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new DomainException("First name and last name cannot be null."); + } + } + + private void validateAge(int age) { + if (age < 18) { + throw new DomainException("Age cannot be less than 18."); + } + } + + private void validatePhone(String phone) { + if (phone == null || phone.isEmpty()) { + throw new DomainException("Phone number cannot be null or empty."); + } + } + + private void validateEmail(String email) { + if (email == null || email.isEmpty()) { + throw new DomainException("Email cannot be null or empty."); + } + } + + private void validateCategory(Category category) { + if (category == null || category.getType().isEmpty()) { + throw new DomainException("Category cannot be null or empty."); + } + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public int getAge() { + return age; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public String getEmail() { + return email; + } + + public Category getCategory() { + return category; + } +} diff --git a/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/repository/PersonRepository.java b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/repository/PersonRepository.java new file mode 100644 index 000000000000..c14aa24a8ef6 --- /dev/null +++ b/onion-architecture/domain/src/main/java/com/iluwatar/onion/domain/repository/PersonRepository.java @@ -0,0 +1,45 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.repository; + +import com.iluwatar.onion.domain.model.Person; +import java.util.List; +import java.util.Optional; + +public interface PersonRepository { + Optional findById(Long id); + + Optional findByFirstName(String firstName); + + Optional findByLastName(String lastName); + + Optional> findAll(); + + Person save(Person person); + + boolean deleteById(Long id); +} diff --git a/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/CategoryTest.java b/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/CategoryTest.java new file mode 100644 index 000000000000..82e88285c35b --- /dev/null +++ b/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/CategoryTest.java @@ -0,0 +1,75 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.model; + +import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.onion.domain.exception.DomainException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class CategoryTest { + + @Test + @DisplayName("Should create category with valid data") + void shouldCreateCategoryWithValidData() { + // Arrange & Act + var category = new Category(1L, "Professional"); + + // Assert + assertNotNull(category); + assertEquals(1L, category.getId()); + assertEquals("Professional", category.getType()); + } + + @Test + @DisplayName("Should create category with null id") + void shouldCreateCategoryWithNullId() { + // Arrange & Act + var category = new Category(null, "Personal"); + + // Assert + assertNull(category.getId()); + assertEquals("Personal", category.getType()); + } + + @Test + @DisplayName("Should throw exception when type is null") + void shouldThrowExceptionWhenTypeIsNull() { + // Act & Assert + var exception = assertThrows(DomainException.class, () -> new Category(1L, null)); + assertTrue(exception.getMessage().contains("Type is null or empty")); + } + + @Test + @DisplayName("Should throw exception when type is empty") + void shouldThrowExceptionWhenTypeIsEmpty() { + // Act & Assert + var exception = assertThrows(DomainException.class, () -> new Category(1L, "")); + assertTrue(exception.getMessage().contains("Type is null or empty")); + } +} diff --git a/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/PersonTest.java b/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/PersonTest.java new file mode 100644 index 000000000000..8f5bef0da1a6 --- /dev/null +++ b/onion-architecture/domain/src/test/java/com/iluwatar/onion/domain/model/PersonTest.java @@ -0,0 +1,179 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.domain.model; + +import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.onion.domain.exception.DomainException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +class PersonTest { + + private final Category validCategory = new Category(1L, "Professional"); + + @Nested + @DisplayName("Person Creation - Valid Cases") + class ValidPersonCreation { + + @Test + @DisplayName("Should create person with valid data") + void shouldCreatePersonWithValidData() { + // Arrange & Act + var person = + new Person(1L, "John", "Doe", 25, "+1234567890", "john.doe@example.com", validCategory); + + // Assert + assertNotNull(person); + assertEquals(1L, person.getId()); + assertEquals("John", person.getFirstName()); + assertEquals("Doe", person.getLastName()); + assertEquals(25, person.getAge()); + assertEquals("+1234567890", person.getPhoneNumber()); + assertEquals("john.doe@example.com", person.getEmail()); + assertEquals(validCategory, person.getCategory()); + } + + @Test + @DisplayName("Should create person with minimum valid age (18)") + void shouldCreatePersonWithMinimumValidAge() { + // Arrange & Act + var person = + new Person( + null, + "Jane", + "Smith", + 18, // minimum valid age + "+9876543210", + "jane@example.com", + validCategory); + + // Assert + assertEquals(18, person.getAge()); + } + } + + @Nested + @DisplayName("Person Creation - Invalid Cases") + class InvalidPersonCreation { + + @Test + @DisplayName("Should throw exception when first name is null") + void shouldThrowExceptionWhenFirstNameIsNull() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> + new Person( + 1L, null, "Doe", 25, "+1234567890", "john@example.com", validCategory)); + assertTrue(exception.getMessage().contains("First name and last name cannot be null")); + } + + @Test + @DisplayName("Should throw exception when last name is null") + void shouldThrowExceptionWhenLastNameIsNull() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> + new Person( + 1L, "John", null, 25, "+1234567890", "john@example.com", validCategory)); + assertTrue(exception.getMessage().contains("First name and last name cannot be null")); + } + + @Test + @DisplayName("Should throw exception when age is less than 18") + void shouldThrowExceptionWhenAgeIsLessThan18() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> + new Person( + 1L, "John", "Doe", 17, "+1234567890", "john@example.com", validCategory)); + assertTrue(exception.getMessage().contains("Age cannot be less than 18")); + } + + @Test + @DisplayName("Should throw exception when phone number is null") + void shouldThrowExceptionWhenPhoneIsNull() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> new Person(1L, "John", "Doe", 25, null, "john@example.com", validCategory)); + assertTrue(exception.getMessage().contains("Phone number cannot be null or empty")); + } + + @Test + @DisplayName("Should throw exception when phone number is empty") + void shouldThrowExceptionWhenPhoneIsEmpty() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> new Person(1L, "John", "Doe", 25, "", "john@example.com", validCategory)); + assertTrue(exception.getMessage().contains("Phone number cannot be null or empty")); + } + + @Test + @DisplayName("Should throw exception when email is null") + void shouldThrowExceptionWhenEmailIsNull() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> new Person(1L, "John", "Doe", 25, "+1234567890", null, validCategory)); + assertTrue(exception.getMessage().contains("Email cannot be null or empty")); + } + + @Test + @DisplayName("Should throw exception when email is empty") + void shouldThrowExceptionWhenEmailIsEmpty() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> new Person(1L, "John", "Doe", 25, "+1234567890", "", validCategory)); + assertTrue(exception.getMessage().contains("Email cannot be null or empty")); + } + + @Test + @DisplayName("Should throw exception when category is null") + void shouldThrowExceptionWhenCategoryIsNull() { + // Act & Assert + var exception = + assertThrows( + DomainException.class, + () -> new Person(1L, "John", "Doe", 25, "+1234567890", "john@example.com", null)); + assertTrue(exception.getMessage().contains("Category cannot be null or empty")); + } + } +} diff --git a/onion-architecture/etc/onion-architecture.png b/onion-architecture/etc/onion-architecture.png new file mode 100644 index 000000000000..82f34e3d7fd1 Binary files /dev/null and b/onion-architecture/etc/onion-architecture.png differ diff --git a/onion-architecture/etc/onion-architecture.puml b/onion-architecture/etc/onion-architecture.puml new file mode 100644 index 000000000000..0e00429de2e6 --- /dev/null +++ b/onion-architecture/etc/onion-architecture.puml @@ -0,0 +1,237 @@ +@startuml onion-architecture + +skinparam packageStyle rectangle +skinparam shadowing false +skinparam defaultFontName Arial +skinparam defaultFontSize 11 +skinparam classAttributeIconSize 0 +skinparam ArrowColor #444444 +skinparam ArrowThickness 1.2 + +skinparam package { + BackgroundColor<> #FFF9C4 + BorderColor<> #F9A825 + FontColor<> #5D4037 + FontStyle<> bold +} + +skinparam package { + BackgroundColor<> #C8E6C9 + BorderColor<> #388E3C + FontColor<> #1B5E20 + FontStyle<> bold +} + +skinparam package { + BackgroundColor<> #BBDEFB + BorderColor<> #1976D2 + FontColor<> #0D47A1 + FontStyle<> bold +} + +' ───────────────────────────────────────────────────────────────────────────── +' DOMAIN LAYER (innermost) +' ───────────────────────────────────────────────────────────────────────────── +package "Domain Layer" <> { + + package "model" { + class Person { + - id : Long + - firstName : String + - lastName : String + - age : int + - phoneNumber : String + - email : String + - category : Category + + getId() : Long + + getFirstName() : String + + getLastName() : String + + getAge() : int + + getPhoneNumber() : String + + getEmail() : String + + getCategory() : Category + } + + class Category { + - id : Long + - type : String + + getId() : Long + + getType() : String + } + } + + package "repository" { + interface PersonRepository { + + findById(id : Long) : Optional + + findByFirstName(firstName : String) : Optional + + findByLastName(lastName : String) : Optional + + findAll() : Optional> + + save(person : Person) : Person + + deleteById(id : Long) : boolean + } + } + + package "exception" { + class DomainException { + + DomainException(message : String) + } + } +} + +' ───────────────────────────────────────────────────────────────────────────── +' APPLICATION LAYER +' ───────────────────────────────────────────────────────────────────────────── +package "Application Layer" <> { + + package "usecase" { + class SavePersonUseCase { + - repository : PersonRepository + + SavePersonUseCase(repository : PersonRepository) + + execute(command : SavePersonCommand) : PersonResponse + } + + class GetPersonUseCase { + - repository : PersonRepository + + GetPersonUseCase(repository : PersonRepository) + + execute(id : Long) : PersonResponse + + executeAll() : List + } + } + + package "dto" { + class SavePersonCommand <> { + firstName : String + lastName : String + age : int + phoneNumber : String + email : String + address : String + categoryId : Long + categoryType : String + } + + class PersonResponse <> { + id : Long + firstName : String + lastName : String + age : int + phoneNumber : String + email : String + categoryId : Long + categoryType : String + } + } +} + +' ───────────────────────────────────────────────────────────────────────────── +' INFRASTRUCTURE LAYER (outermost) +' ───────────────────────────────────────────────────────────────────────────── +package "Infrastructure Layer" <> { + + package "web" { + class PersonController { + - savePersonUseCase : SavePersonUseCase + - getPersonUseCase : GetPersonUseCase + + getPerson(id : Long) : ResponseEntity + + getAllPersons() : ResponseEntity> + + savePerson(command : SavePersonCommand) : ResponseEntity + } + } + + package "persistence" { + class PersonRepositoryAdapter { + - repository : SpringDataPersonRepository + + findById(id : Long) : Optional + + findByFirstName(firstName : String) : Optional + + findByLastName(lastName : String) : Optional + + findAll() : Optional> + + save(person : Person) : Person + + deleteById(id : Long) : boolean + } + + interface SpringDataPersonRepository { + + findByFirstName(firstName : String) : Optional + + findByLastName(lastName : String) : Optional + } + + class JpaPersonEntity { + - id : Long + - firstName : String + - lastName : String + - age : int + - phoneNumber : String + - email : String + - category : JpaCategoryEntity + } + + class JpaCategoryEntity { + - id : Long + - type : String + } + } + + package "config" { + class ApplicationConfig <<@Configuration>> { + + savePersonUseCase(repo : PersonRepository) : SavePersonUseCase + + getPersonUseCase(repo : PersonRepository) : GetPersonUseCase + } + + class Application <<@SpringBootApplication>> { + + main(args : String[]) + } + } +} + +' ───────────────────────────────────────────────────────────────────────────── +' DOMAIN: internal relationships +' ───────────────────────────────────────────────────────────────────────────── +Person "1" *-- "1" Category : has +Person ..> DomainException : <> +Category ..> DomainException : <> + +' ───────────────────────────────────────────────────────────────────────────── +' APPLICATION → DOMAIN +' ───────────────────────────────────────────────────────────────────────────── +SavePersonUseCase --> PersonRepository : uses +SavePersonUseCase ..> Person : creates +SavePersonUseCase ..> Category : creates +SavePersonUseCase ..> PersonResponse : returns +SavePersonUseCase ..> SavePersonCommand : receives + +GetPersonUseCase --> PersonRepository : uses +GetPersonUseCase ..> PersonResponse : returns + +' ───────────────────────────────────────────────────────────────────────────── +' INFRASTRUCTURE → APPLICATION / DOMAIN +' ───────────────────────────────────────────────────────────────────────────── +PersonController --> SavePersonUseCase : delegates to +PersonController --> GetPersonUseCase : delegates to +PersonController ..> DomainException : catches + +PersonRepositoryAdapter ..|> PersonRepository : implements +PersonRepositoryAdapter --> SpringDataPersonRepository : uses +PersonRepositoryAdapter ..> JpaPersonEntity : maps +PersonRepositoryAdapter ..> JpaCategoryEntity : maps +PersonRepositoryAdapter ..> Person : maps to / from +PersonRepositoryAdapter ..> Category : maps to / from + +SpringDataPersonRepository --> JpaPersonEntity : manages +JpaPersonEntity "1" *-- "1" JpaCategoryEntity : contains + +ApplicationConfig ..> SavePersonUseCase : <<@Bean>> +ApplicationConfig ..> GetPersonUseCase : <<@Bean>> +ApplicationConfig --> PersonRepository : injects + +legend right + Layer dependency rule + Infrastructure → Application → Domain + Outer layers depend on inner layers. + Domain has NO external dependencies. + ---- + ■ Domain Layer + ■ Application Layer + ■ Infrastructure Layer +endlegend + +@enduml + diff --git a/onion-architecture/etc/postman/onion-architecture.postman_collection.json b/onion-architecture/etc/postman/onion-architecture.postman_collection.json new file mode 100644 index 000000000000..ed0cbd5c58f5 --- /dev/null +++ b/onion-architecture/etc/postman/onion-architecture.postman_collection.json @@ -0,0 +1,83 @@ +{ + "info": { + "_postman_id": "79aca374-7080-46c1-938f-89b327a84d6a", + "name": "onion-architecture", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "51221021", + "_collection_link": "https://go.postman.co/collection/51221021-79aca374-7080-46c1-938f-89b327a84d6a?source=collection_link" + }, + "item": [ + { + "name": "savePerson", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"number1\": 5,\r\n \"number2\": 3,\r\n \"operation\": \"multiply\"\r\n }" + }, + "url": { + "raw": "http://localhost:8080/api/persons", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "api", + "persons" + ] + } + }, + "response": [] + }, + { + "name": "getPersons", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"number1\": 5,\r\n \"number2\": 3,\r\n \"operation\": \"multiply\"\r\n }" + }, + "url": { + "raw": "http://localhost:8080/api/persons", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "api", + "persons" + ] + } + }, + "response": [] + }, + { + "name": "getPersonById", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/api/persons/1", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "api", + "persons", + "1" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/onion-architecture/infrastructure/pom.xml b/onion-architecture/infrastructure/pom.xml new file mode 100644 index 000000000000..d26e2a7ef69d --- /dev/null +++ b/onion-architecture/infrastructure/pom.xml @@ -0,0 +1,87 @@ + + + + 4.0.0 + + com.iluwatar + onion-architecture + 1.26.0-SNAPSHOT + + infrastructure + Infrastructure + + + + com.iluwatar + domain + ${project.version} + + + + com.iluwatar + application + ${project.version} + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + com.h2database + h2 + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/Application.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/Application.java new file mode 100644 index 000000000000..c86c95740599 --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/Application.java @@ -0,0 +1,38 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/config/ApplicationConfig.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/config/ApplicationConfig.java new file mode 100644 index 000000000000..7794c91e3bcf --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/config/ApplicationConfig.java @@ -0,0 +1,47 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.config; + +import com.iluwatar.onion.application.usecase.GetPersonUseCase; +import com.iluwatar.onion.application.usecase.SavePersonUseCase; +import com.iluwatar.onion.domain.repository.PersonRepository; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfig { + + @Bean + public SavePersonUseCase savePersonUseCase(PersonRepository repository) { + return new SavePersonUseCase(repository); + } + + @Bean + public GetPersonUseCase getPersonUseCase(PersonRepository repository) { + return new GetPersonUseCase(repository); + } +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaCategoryEntity.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaCategoryEntity.java new file mode 100644 index 000000000000..aafd242992be --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaCategoryEntity.java @@ -0,0 +1,55 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.persistence; + +import jakarta.persistence.*; + +@Entity +@Table(name = "category") +public class JpaCategoryEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String type; + + public JpaCategoryEntity() {} + + public JpaCategoryEntity(Long id, String type) { + this.id = id; + this.type = type; + } + + public Long getId() { + return id; + } + + public String getType() { + return type; + } +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaPersonEntity.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaPersonEntity.java new file mode 100644 index 000000000000..bf71b5306c92 --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/JpaPersonEntity.java @@ -0,0 +1,93 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.persistence; + +import jakarta.persistence.*; + +@Entity +@Table(name = "person") +public class JpaPersonEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String firstName; + private String lastName; + private int age; + private String phoneNumber; + private String email; + + @ManyToOne private JpaCategoryEntity category; + + public JpaPersonEntity() {} + + public JpaPersonEntity( + Long id, + String firstName, + String lastName, + int age, + String phoneNumber, + String email, + JpaCategoryEntity category) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.phoneNumber = phoneNumber; + this.email = email; + this.category = category; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public int getAge() { + return age; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public String getEmail() { + return email; + } + + public JpaCategoryEntity getCategory() { + return category; + } +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapter.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapter.java new file mode 100644 index 000000000000..4c4aa267493a --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapter.java @@ -0,0 +1,102 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.persistence; + +import com.iluwatar.onion.domain.model.Category; +import com.iluwatar.onion.domain.model.Person; +import com.iluwatar.onion.domain.repository.PersonRepository; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.springframework.stereotype.Repository; + +@Repository +public class PersonRepositoryAdapter implements PersonRepository { + + private final SpringDataPersonRepository repository; + + public PersonRepositoryAdapter(SpringDataPersonRepository repository) { + this.repository = repository; + } + + @Override + public Optional findById(Long id) { + return repository.findById(id).map(this::mapToDomain); + } + + @Override + public Optional findByFirstName(String firstName) { + return repository.findByFirstName(firstName).map(this::mapToDomain); + } + + @Override + public Optional findByLastName(String lastName) { + return repository.findByLastName(lastName).map(this::mapToDomain); + } + + @Override + public Optional> findAll() { + return repository.findAll().stream() + .map(this::mapToDomain) + .collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of)); + } + + @Override + public Person save(Person person) { + JpaPersonEntity entity = mapToEntity(person); + JpaPersonEntity savedEntity = repository.save(entity); + return mapToDomain(savedEntity); + } + + @Override + public boolean deleteById(Long id) { + repository.deleteById(id); + return repository.findById(id).isEmpty(); + } + + private JpaPersonEntity mapToEntity(Person person) { + return new JpaPersonEntity( + person.getId(), + person.getFirstName(), + person.getLastName(), + person.getAge(), + person.getPhoneNumber(), + person.getEmail(), + new JpaCategoryEntity(person.getCategory().getId(), person.getCategory().getType())); + } + + private Person mapToDomain(JpaPersonEntity entity) { + return new Person( + entity.getId(), + entity.getFirstName(), + entity.getLastName(), + entity.getAge(), + entity.getPhoneNumber(), + entity.getEmail(), + new Category(entity.getCategory().getId(), entity.getCategory().getType())); + } +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/SpringDataPersonRepository.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/SpringDataPersonRepository.java new file mode 100644 index 000000000000..35f86515c70b --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/persistence/SpringDataPersonRepository.java @@ -0,0 +1,37 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.persistence; + +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SpringDataPersonRepository extends JpaRepository { + + Optional findByFirstName(String firstName); + + Optional findByLastName(String lastName); +} diff --git a/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/web/PersonController.java b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/web/PersonController.java new file mode 100644 index 000000000000..417e749f41a6 --- /dev/null +++ b/onion-architecture/infrastructure/src/main/java/com/iluwatar/onion/infrastructure/web/PersonController.java @@ -0,0 +1,72 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.web; + +import com.iluwatar.onion.application.dto.PersonResponse; +import com.iluwatar.onion.application.dto.SavePersonCommand; +import com.iluwatar.onion.application.usecase.GetPersonUseCase; +import com.iluwatar.onion.application.usecase.SavePersonUseCase; +import com.iluwatar.onion.domain.exception.DomainException; +import java.util.List; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api") +public class PersonController { + + private final SavePersonUseCase savePersonUseCase; + private final GetPersonUseCase getPersonUseCase; + + public PersonController(SavePersonUseCase savePersonUseCase, GetPersonUseCase getPersonUseCase) { + this.savePersonUseCase = savePersonUseCase; + this.getPersonUseCase = getPersonUseCase; + } + + @GetMapping("/persons/{id}") + public ResponseEntity getPerson(@PathVariable("id") Long id) { + var person = getPersonUseCase.execute(id); + return ResponseEntity.ok(person); + } + + @GetMapping("/persons") + public ResponseEntity> getAllPersons() { + var persons = getPersonUseCase.executeAll(); + return ResponseEntity.ok(persons); + } + + @PostMapping("/persons") + public ResponseEntity savePerson(@RequestBody SavePersonCommand command) { + try { + var savedPerson = savePersonUseCase.execute(command); + return ResponseEntity.status(HttpStatus.OK).body(savedPerson); + } catch (DomainException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); + } + } +} diff --git a/onion-architecture/infrastructure/src/main/resources/application.properties b/onion-architecture/infrastructure/src/main/resources/application.properties new file mode 100644 index 000000000000..6a3ed156f558 --- /dev/null +++ b/onion-architecture/infrastructure/src/main/resources/application.properties @@ -0,0 +1,19 @@ +# You can also specify the server port in the application.properties file. +# Uncomment the following line and set the desired port number to change +# the default port (8080) to a different value. +#server.port=8080 + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=password +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +# Force Spring Boot to always run SQL initialization scripts on startup +spring.sql.init.mode=always + +# If using Spring Data JPA / Hibernate, defer data insertion until AFTER entities are generated +spring.jpa.defer-datasource-initialization=true + +# Keep Hibernate's DDL generation active (or set to 'update') +spring.jpa.hibernate.ddl-auto=create-drop diff --git a/onion-architecture/infrastructure/src/main/resources/data.sql b/onion-architecture/infrastructure/src/main/resources/data.sql new file mode 100644 index 000000000000..6291dd984e31 --- /dev/null +++ b/onion-architecture/infrastructure/src/main/resources/data.sql @@ -0,0 +1,4 @@ +INSERT INTO category (id, type) VALUES (1, 'Teenage'); +INSERT INTO category (id, type) VALUES (2, 'Young Adult'); +INSERT INTO category (id, type) VALUES (3, 'Adult'); +INSERT INTO category (id, type) VALUES (4, 'Senior'); \ No newline at end of file diff --git a/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapterTest.java b/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapterTest.java new file mode 100644 index 000000000000..49fd2816f172 --- /dev/null +++ b/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/persistence/PersonRepositoryAdapterTest.java @@ -0,0 +1,332 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.persistence; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.iluwatar.onion.domain.model.Category; +import com.iluwatar.onion.domain.model.Person; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class PersonRepositoryAdapterTest { + + @Mock private SpringDataPersonRepository springDataRepository; + + @Captor private ArgumentCaptor entityCaptor; + + private PersonRepositoryAdapter personRepositoryAdapter; + private JpaPersonEntity jpaPersonEntity; + + @BeforeEach + void setUp() { + personRepositoryAdapter = new PersonRepositoryAdapter(springDataRepository); + + // Setup test data + var jpaCategory = new JpaCategoryEntity(1L, "Professional"); + jpaPersonEntity = + new JpaPersonEntity( + 1L, "John", "Doe", 25, "+1234567890", "john.doe@example.com", jpaCategory); + } + + @Nested + @DisplayName("Find By ID") + class FindById { + + @Test + @DisplayName("Should return Person when entity exists") + void shouldReturnPersonWhenEntityExists() { + // Arrange + when(springDataRepository.findById(1L)).thenReturn(Optional.of(jpaPersonEntity)); + + // Act + var result = personRepositoryAdapter.findById(1L); + + // Assert + assertTrue(result.isPresent()); + Person person = result.get(); + assertEquals(1L, person.getId()); + assertEquals("John", person.getFirstName()); + assertEquals("Doe", person.getLastName()); + assertEquals(25, person.getAge()); + assertEquals("+1234567890", person.getPhoneNumber()); + assertEquals("john.doe@example.com", person.getEmail()); + assertEquals(1L, person.getCategory().getId()); + assertEquals("Professional", person.getCategory().getType()); + + verify(springDataRepository, times(1)).findById(1L); + } + + @Test + @DisplayName("Should return empty Optional when entity not found") + void shouldReturnEmptyWhenEntityNotFound() { + // Arrange + when(springDataRepository.findById(999L)).thenReturn(Optional.empty()); + + // Act + var result = personRepositoryAdapter.findById(999L); + + // Assert + assertTrue(result.isEmpty()); + verify(springDataRepository, times(1)).findById(999L); + } + } + + @Nested + @DisplayName("Find By First Name") + class FindByFirstName { + + @Test + @DisplayName("Should return Person when entity with first name exists") + void shouldReturnPersonWhenEntityExists() { + // Arrange + when(springDataRepository.findByFirstName("John")).thenReturn(Optional.of(jpaPersonEntity)); + + // Act + var result = personRepositoryAdapter.findByFirstName("John"); + + // Assert + assertTrue(result.isPresent()); + assertEquals("John", result.get().getFirstName()); + verify(springDataRepository, times(1)).findByFirstName("John"); + } + + @Test + @DisplayName("Should return empty Optional when no entity found") + void shouldReturnEmptyWhenNotFound() { + // Arrange + when(springDataRepository.findByFirstName("Unknown")).thenReturn(Optional.empty()); + + // Act + var result = personRepositoryAdapter.findByFirstName("Unknown"); + + // Assert + assertTrue(result.isEmpty()); + verify(springDataRepository, times(1)).findByFirstName("Unknown"); + } + } + + @Nested + @DisplayName("Find By Last Name") + class FindByLastName { + + @Test + @DisplayName("Should return Person when entity with last name exists") + void shouldReturnPersonWhenEntityExists() { + // Arrange + when(springDataRepository.findByLastName("Doe")).thenReturn(Optional.of(jpaPersonEntity)); + + // Act + var result = personRepositoryAdapter.findByLastName("Doe"); + + // Assert + assertTrue(result.isPresent()); + assertEquals("Doe", result.get().getLastName()); + verify(springDataRepository, times(1)).findByLastName("Doe"); + } + } + + @Nested + @DisplayName("Find All") + class FindAll { + + @Test + @DisplayName("Should return list of Persons when entities exist") + void shouldReturnListOfPersons() { + // Arrange + var category2 = new JpaCategoryEntity(2L, "Personal"); + var person2 = + new JpaPersonEntity( + 2L, "Jane", "Smith", 30, "+9876543210", "jane@example.com", category2); + + when(springDataRepository.findAll()).thenReturn(List.of(jpaPersonEntity, person2)); + + // Act + var result = personRepositoryAdapter.findAll(); + + // Assert + assertTrue(result.isPresent()); + var persons = result.get(); + assertEquals(2, persons.size()); + assertEquals("John", persons.get(0).getFirstName()); + assertEquals("Jane", persons.get(1).getFirstName()); + + verify(springDataRepository, times(1)).findAll(); + } + + @Test + @DisplayName("Should return empty list when no entities exist") + void shouldReturnEmptyListWhenNoEntities() { + // Arrange + when(springDataRepository.findAll()).thenReturn(List.of()); + + // Act + var result = personRepositoryAdapter.findAll(); + + // Assert + assertTrue(result.isPresent()); + assertTrue(result.get().isEmpty()); + verify(springDataRepository, times(1)).findAll(); + } + } + + @Nested + @DisplayName("Save") + class Save { + + @Test + @DisplayName("Should save person and return domain model") + void shouldSavePersonAndReturnDomainModel() { + // Arrange + var personToSave = + new Person( + null, // New person without ID + "Jane", + "Smith", + 28, + "+1111111111", + "jane@example.com", + new Category(2L, "Personal")); + + var savedCategory = new JpaCategoryEntity(2L, "Personal"); + var savedEntity = + new JpaPersonEntity( + 100L, // ID assigned by database + "Jane", + "Smith", + 28, + "+1111111111", + "jane@example.com", + savedCategory); + + when(springDataRepository.save(any(JpaPersonEntity.class))).thenReturn(savedEntity); + + // Act + var result = personRepositoryAdapter.save(personToSave); + + // Assert + assertNotNull(result); + assertEquals(100L, result.getId()); + assertEquals("Jane", result.getFirstName()); + assertEquals("Smith", result.getLastName()); + assertEquals(28, result.getAge()); + + verify(springDataRepository, times(1)).save(any(JpaPersonEntity.class)); + } + + @Test + @DisplayName("Should correctly map domain model to JPA entity") + void shouldCorrectlyMapDomainToEntity() { + // Arrange + var personToSave = + new Person( + null, + "Bob", + "Johnson", + 35, + "+2222222222", + "bob@example.com", + new Category(3L, "Business")); + + var savedEntity = + new JpaPersonEntity( + 200L, + "Bob", + "Johnson", + 35, + "+2222222222", + "bob@example.com", + new JpaCategoryEntity(3L, "Business")); + + when(springDataRepository.save(any(JpaPersonEntity.class))).thenReturn(savedEntity); + + // Act + personRepositoryAdapter.save(personToSave); + + // Assert - Verify what was passed to Spring Data repository + verify(springDataRepository).save(entityCaptor.capture()); + JpaPersonEntity capturedEntity = entityCaptor.getValue(); + + assertEquals("Bob", capturedEntity.getFirstName()); + assertEquals("Johnson", capturedEntity.getLastName()); + assertEquals(35, capturedEntity.getAge()); + assertEquals("+2222222222", capturedEntity.getPhoneNumber()); + assertEquals("bob@example.com", capturedEntity.getEmail()); + assertEquals(3L, capturedEntity.getCategory().getId()); + assertEquals("Business", capturedEntity.getCategory().getType()); + } + } + + @Nested + @DisplayName("Delete By ID") + class DeleteById { + + @Test + @DisplayName("Should return true when person is successfully deleted") + void shouldReturnTrueWhenDeleted() { + // Arrange + doNothing().when(springDataRepository).deleteById(1L); + when(springDataRepository.findById(1L)).thenReturn(Optional.empty()); + + // Act + boolean result = personRepositoryAdapter.deleteById(1L); + + // Assert + assertTrue(result); + verify(springDataRepository, times(1)).deleteById(1L); + verify(springDataRepository, times(1)).findById(1L); + } + + @Test + @DisplayName("Should return false when person still exists after deletion") + void shouldReturnFalseWhenStillExists() { + // Arrange + doNothing().when(springDataRepository).deleteById(1L); + when(springDataRepository.findById(1L)).thenReturn(Optional.of(jpaPersonEntity)); + + // Act + boolean result = personRepositoryAdapter.deleteById(1L); + + // Assert + assertFalse(result); + verify(springDataRepository, times(1)).deleteById(1L); + verify(springDataRepository, times(1)).findById(1L); + } + } +} diff --git a/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/web/PersonControllerTest.java b/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/web/PersonControllerTest.java new file mode 100644 index 000000000000..9e0369b985c8 --- /dev/null +++ b/onion-architecture/infrastructure/src/test/java/com/iluwatar/onion/infrastructure/web/PersonControllerTest.java @@ -0,0 +1,348 @@ +/* + * + * * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * + * * The MIT License + * * Copyright © 2014-2022 Ilkka Seppälä + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in + * * all copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * * THE SOFTWARE. + * + */ +package com.iluwatar.onion.infrastructure.web; + +import static org.hamcrest.Matchers.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iluwatar.onion.application.dto.PersonResponse; +import com.iluwatar.onion.application.dto.SavePersonCommand; +import com.iluwatar.onion.application.usecase.GetPersonUseCase; +import com.iluwatar.onion.application.usecase.SavePersonUseCase; +import com.iluwatar.onion.domain.exception.DomainException; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + @Autowired private MockMvc mockMvc; + + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private SavePersonUseCase savePersonUseCase; + + @MockitoBean private GetPersonUseCase getPersonUseCase; + + @Nested + @DisplayName("GET /api/persons/{id}") + class GetPersonById { + + @Test + @DisplayName("Should return person when person exists") + void shouldReturnPersonWhenExists() throws Exception { + // Arrange + var response = + new PersonResponse( + 1L, "John", "Doe", 25, "+1234567890", "john.doe@example.com", 1L, "Professional"); + + when(getPersonUseCase.execute(1L)).thenReturn(response); + + // Act & Assert + mockMvc + .perform(get("/api/persons/1").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id").value(1)) + .andExpect(jsonPath("$.firstName").value("John")) + .andExpect(jsonPath("$.lastName").value("Doe")) + .andExpect(jsonPath("$.age").value(25)) + .andExpect(jsonPath("$.phoneNumber").value("+1234567890")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.categoryId").value(1)) + .andExpect(jsonPath("$.categoryType").value("Professional")); + + verify(getPersonUseCase, times(1)).execute(1L); + } + + @Test + @DisplayName("Should handle different person IDs") + void shouldHandleDifferentPersonIds() throws Exception { + // Arrange + var response = + new PersonResponse( + 42L, "Jane", "Smith", 30, "+9876543210", "jane@example.com", 2L, "Personal"); + + when(getPersonUseCase.execute(42L)).thenReturn(response); + + // Act & Assert + mockMvc + .perform(get("/api/persons/42").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(42)) + .andExpect(jsonPath("$.firstName").value("Jane")); + + verify(getPersonUseCase, times(1)).execute(42L); + } + } + + @Nested + @DisplayName("GET /api/persons") + class GetAllPersons { + + @Test + @DisplayName("Should return list of persons") + void shouldReturnListOfPersons() throws Exception { + // Arrange + var person1 = + new PersonResponse( + 1L, "John", "Doe", 25, "+1234567890", "john@example.com", 1L, "Professional"); + var person2 = + new PersonResponse( + 2L, "Jane", "Smith", 30, "+9876543210", "jane@example.com", 2L, "Personal"); + + var persons = List.of(person1, person2); + when(getPersonUseCase.executeAll()).thenReturn(persons); + + // Act & Assert + mockMvc + .perform(get("/api/persons").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].id").value(1)) + .andExpect(jsonPath("$[0].firstName").value("John")) + .andExpect(jsonPath("$[1].id").value(2)) + .andExpect(jsonPath("$[1].firstName").value("Jane")); + + verify(getPersonUseCase, times(1)).executeAll(); + } + + @Test + @DisplayName("Should return empty list when no persons exist") + void shouldReturnEmptyListWhenNoPersons() throws Exception { + // Arrange + when(getPersonUseCase.executeAll()).thenReturn(List.of()); + + // Act & Assert + mockMvc + .perform(get("/api/persons").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(0))); + + verify(getPersonUseCase, times(1)).executeAll(); + } + + @Test + @DisplayName("Should handle large list of persons") + void shouldHandleLargeListOfPersons() throws Exception { + // Arrange + var persons = + List.of( + new PersonResponse(1L, "Person1", "Last1", 25, "+1", "p1@example.com", 1L, "Cat1"), + new PersonResponse(2L, "Person2", "Last2", 26, "+2", "p2@example.com", 1L, "Cat1"), + new PersonResponse(3L, "Person3", "Last3", 27, "+3", "p3@example.com", 1L, "Cat1")); + + when(getPersonUseCase.executeAll()).thenReturn(persons); + + // Act & Assert + mockMvc + .perform(get("/api/persons").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))); + + verify(getPersonUseCase, times(1)).executeAll(); + } + } + + @Nested + @DisplayName("POST /api/persons") + class SavePerson { + + @Test + @DisplayName("Should create person with valid data") + void shouldCreatePersonWithValidData() throws Exception { + // Arrange + var command = + new SavePersonCommand( + "John", + "Doe", + 25, + "+1234567890", + "john.doe@example.com", + "123 Main St", + 1L, + "Professional"); + + var response = + new PersonResponse( + 1L, "John", "Doe", 25, "+1234567890", "john.doe@example.com", 1L, "Professional"); + + when(savePersonUseCase.execute(any(SavePersonCommand.class))).thenReturn(response); + + // Act & Assert + mockMvc + .perform( + post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(command))) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id").value(1)) + .andExpect(jsonPath("$.firstName").value("John")) + .andExpect(jsonPath("$.lastName").value("Doe")) + .andExpect(jsonPath("$.age").value(25)) + .andExpect(jsonPath("$.phoneNumber").value("+1234567890")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.categoryId").value(1)) + .andExpect(jsonPath("$.categoryType").value("Professional")); + + verify(savePersonUseCase, times(1)).execute(any(SavePersonCommand.class)); + } + + @Test + @DisplayName("Should handle validation errors from use case") + void shouldPropagateValidationErrors() throws Exception { + // Arrange + var command = + new SavePersonCommand( + "Young", + "Person", + 17, // Invalid age + "+1234567890", + "young@example.com", + "123 Main St", + 1L, + "Student"); + + when(savePersonUseCase.execute(any(SavePersonCommand.class))) + .thenThrow(new DomainException("Age cannot be less than 18")); + + // Act & Assert + mockMvc + .perform( + post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(command))) + .andExpect(status().is4xxClientError()); + + verify(savePersonUseCase, times(1)).execute(any(SavePersonCommand.class)); + } + + @Test + @DisplayName("Should handle malformed JSON") + void shouldHandleMalformedJson() throws Exception { + // Act & Assert + mockMvc + .perform( + post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content("{invalid json}")) + .andExpect(status().isBadRequest()); + + verify(savePersonUseCase, never()).execute(any(SavePersonCommand.class)); + } + + @Test + @DisplayName("Should accept all required fields in command") + void shouldAcceptAllRequiredFields() throws Exception { + // Arrange + var command = + new SavePersonCommand( + "Complete", + "Person", + 30, + "+1111111111", + "complete@example.com", + "456 Oak Ave", + 5L, + "Business"); + + var response = + new PersonResponse( + 10L, "Complete", "Person", 30, "+1111111111", "complete@example.com", 5L, "Business"); + + when(savePersonUseCase.execute(any(SavePersonCommand.class))).thenReturn(response); + + // Act & Assert + mockMvc + .perform( + post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(command))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.categoryType").value("Business")); + + verify(savePersonUseCase, times(1)).execute(any(SavePersonCommand.class)); + } + } + + @Nested + @DisplayName("Controller Integration") + class ControllerIntegration { + + @Test + @DisplayName("Should handle multiple requests sequentially") + void shouldHandleMultipleRequestsSequentially() throws Exception { + // Arrange + var getResponse = + new PersonResponse( + 1L, "John", "Doe", 25, "+1234567890", "john@example.com", 1L, "Professional"); + + var savePersonCommand = + new SavePersonCommand( + "Jane", "Smith", 30, "+9876543210", "jane@example.com", "456 Oak", 2L, "Personal"); + + var savePersonResponse = + new PersonResponse( + 2L, "Jane", "Smith", 30, "+9876543210", "jane@example.com", 2L, "Personal"); + + when(getPersonUseCase.execute(1L)).thenReturn(getResponse); + when(savePersonUseCase.execute(any(SavePersonCommand.class))).thenReturn(savePersonResponse); + + // Act & Assert - GET request + mockMvc + .perform(get("/api/persons/1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.firstName").value("John")); + + // Act & Assert - POST request + mockMvc + .perform( + post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(savePersonCommand))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.firstName").value("Jane")); + + verify(getPersonUseCase, times(1)).execute(1L); + verify(savePersonUseCase, times(1)).execute(any(SavePersonCommand.class)); + } + } +} diff --git a/onion-architecture/pom.xml b/onion-architecture/pom.xml new file mode 100644 index 000000000000..07df2a1224c1 --- /dev/null +++ b/onion-architecture/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + onion-architecture + pom + + + 5.10.0 + 5.23.0 + 3.24.2 + + + + domain + application + infrastructure + + diff --git a/page-controller/pom.xml b/page-controller/pom.xml index c314459e9d14..564f73418ded 100644 --- a/page-controller/pom.xml +++ b/page-controller/pom.xml @@ -56,7 +56,7 @@ org.springframework.boot spring-boot-starter-thymeleaf - 3.4.4 + 4.0.6 org.junit.jupiter diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/App.java b/page-controller/src/main/java/com/iluwatar/page/controller/App.java index 076ebf081c24..57f8a9a16c25 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/App.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/App.java @@ -44,6 +44,11 @@ public class App { * @param args command line args */ public static void main(final String[] args) { - SpringApplication.run(App.class, args); + var context = SpringApplication.run(App.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } } diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java index b3d374210dfe..eb49969ee3b4 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java @@ -32,6 +32,6 @@ public class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[] {})); + assertDoesNotThrow(() -> App.main(new String[] {"test"})); } } diff --git a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java index aaf19fb0cee2..feac06124a7e 100644 --- a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java @@ -27,6 +27,7 @@ import java.awt.Desktop; import java.io.File; import java.io.IOException; +import java.util.Locale; import lombok.extern.slf4j.Slf4j; /** @@ -77,8 +78,28 @@ public static void main(String[] args) { Desktop.getDesktop().open(applicationFile); } else { - // java Desktop not supported - above unlikely to work for Windows so try instead... - Runtime.getRuntime().exec("cmd.exe start " + applicationFile); + // java Desktop not supported - use ProcessBuilder for cross-platform support + var os = System.getProperty("os.name").toLowerCase(Locale.ROOT); + ProcessBuilder pb; + if (os.contains("win")) { + // Empty string title arg prevents cmd start treating a quoted path as the window title + var systemRoot = System.getenv("SystemRoot"); + if (systemRoot == null) { + systemRoot = "C:\\Windows"; + } + pb = + new ProcessBuilder( + systemRoot + "\\System32\\cmd.exe", + "/c", + "start", + "", + applicationFile.getAbsolutePath()); + } else if (os.contains("mac")) { + pb = new ProcessBuilder("open", applicationFile.getAbsolutePath()); // NOSONAR + } else { + pb = new ProcessBuilder("xdg-open", applicationFile.getAbsolutePath()); // NOSONAR + } + pb.start(); } } catch (IOException ex) { diff --git a/page-object/src/main/java/com/iluwatar/pageobject/App.java b/page-object/src/main/java/com/iluwatar/pageobject/App.java index a0eda082f726..2b104a583edb 100644 --- a/page-object/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/src/main/java/com/iluwatar/pageobject/App.java @@ -27,6 +27,7 @@ import java.awt.Desktop; import java.io.File; import java.io.IOException; +import java.util.Locale; /** * Page Object pattern wraps an UI component with an application specific API allowing you to @@ -75,9 +76,28 @@ public static void main(String[] args) { Desktop.getDesktop().open(applicationFile); } else { - // Java Desktop not supported - above unlikely to work for Windows so try the - // following instead... - Runtime.getRuntime().exec("cmd.exe start " + applicationFile); + // java Desktop not supported - use ProcessBuilder for cross-platform support + var os = System.getProperty("os.name").toLowerCase(Locale.ROOT); + ProcessBuilder pb; + if (os.contains("win")) { + // Empty string title arg prevents cmd start treating a quoted path as the window title + var systemRoot = System.getenv("SystemRoot"); + if (systemRoot == null) { + systemRoot = "C:\\Windows"; + } + pb = + new ProcessBuilder( + systemRoot + "\\System32\\cmd.exe", + "/c", + "start", + "", + applicationFile.getAbsolutePath()); + } else if (os.contains("mac")) { + pb = new ProcessBuilder("open", applicationFile.getAbsolutePath()); // NOSONAR + } else { + pb = new ProcessBuilder("xdg-open", applicationFile.getAbsolutePath()); // NOSONAR + } + pb.start(); } } catch (IOException ex) { diff --git a/polling-publisher/README.md b/polling-publisher/README.md new file mode 100644 index 000000000000..45e02ac59d21 --- /dev/null +++ b/polling-publisher/README.md @@ -0,0 +1,119 @@ +--- +title: "Polling Publisher-Subscriber Pattern in Java: Mastering Asynchronous Messaging Elegantly" +shortTitle: Polling Pub/Sub +description: "Learn how to implement a Polling Publisher-Subscriber system in Java using Spring Boot and Kafka. Explore the architecture, real-world analogies, and benefits of asynchronous communication with clean code examples." +category: Architectural +language: en +tag: + - Spring Boot + - Kafka + - Microservices + - Asynchronous Messaging + - Decoupling +--- + +## Also known as + +* Event-Driven Architecture +* Asynchronous Pub/Sub Pattern +* Message Queue-Based Polling System + +## Intent of Polling Publisher-Subscriber Pattern + +The Polling Publisher-Subscriber pattern decouples data producers from consumers by enabling asynchronous, message-driven communication. A service polls a data source and publishes messages to a message broker (e.g., Kafka), which are then consumed by one or more subscriber services. + +## Detailed Explanation of the Pattern with Real-World Examples + +### Real-world analogy + +> A news agency constantly polls for the latest news updates. Once it receives new information, it publishes them to different news outlets (TV, newspapers, apps). Each outlet consumes and displays the updates independently. + +### In plain words + +> One service regularly checks for updates (polls) and sends messages to Kafka. Another service listens to Kafka and processes the messages asynchronously. + +### Wikipedia says + +> This pattern closely resembles the [Publish–subscribe model](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern), where messages are sent by publishers and received by subscribers without them knowing each other. + +### Architecture Flow + +``` ++------------+ +--------+ +-------------+ +| Publisher | ---> | Kafka | ---> | Subscriber | ++------------+ +--------+ +-------------+ +``` + +## Programmatic Example (Spring Boot + Kafka) + +### Publisher Service + +- Uses Spring's `@Scheduled` to poll data periodically. +- Publishes data to a Kafka topic. +- Optionally exposes a REST API for manual data publishing. + +```java +@Scheduled(fixedRate = 5000) +public void pollAndPublish() { + String data = pollingService.getLatestData(); + kafkaTemplate.send("updates-topic", data); +} +``` + +### Subscriber Service + +- Listens to Kafka topic using `@KafkaListener`. +- Processes messages asynchronously. + +```java +@KafkaListener(topics = "updates-topic") +public void processUpdate(String message) { + log.info("Received update: {}", message); + updateProcessor.handle(message); +} +``` + +## When to Use the Polling Publisher-Subscriber Pattern + +Use this pattern when: + +* Real-time push from the producer is not possible. +* Loose coupling between producers and consumers is desired. +* You need asynchronous, scalable event processing. +* You are building an event-driven microservices architecture. + +## Real-World Applications + +* Real-time reporting dashboards +* Health check aggregators for distributed systems +* IoT telemetry processing +* Notification and alerting systems + +## Benefits and Trade-offs of Polling Pub/Sub Pattern + +### Benefits + +* Loose coupling between services +* Asynchronous and scalable architecture +* Fault-tolerant with message persistence in Kafka +* Easy to extend with new consumers or publishers + +### Trade-Offs + +* Polling introduces latency between data generation and consumption +* Requires managing and configuring Kafka (or other brokers) +* Slightly more complex deployment and infrastructure setup + +## Related Java Design Patterns + +* [Observer Pattern](https://java-design-patterns.com/patterns/observer/) +* [Mediator Pattern](https://java-design-patterns.com/patterns/mediator/) +* [Message Queue Pattern](https://java-design-patterns.com/patterns/event-queue/) + +## References and Credits + +* [Apache Kafka Documentation](https://kafka.apache.org/documentation/) +* [Spring Kafka Documentation](https://docs.spring.io/spring-kafka) +* [Spring Scheduled Tasks](https://www.baeldung.com/spring-scheduled-tasks) +* [Spring Kafka Tutorial – Baeldung](https://www.baeldung.com/spring-kafka) +* Inspired by: [iluwatar/java-design-patterns](https://github.com/iluwatar/java-design-patterns) \ No newline at end of file diff --git a/polling-publisher/etc/polling-publisher.urm.puml b/polling-publisher/etc/polling-publisher.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/polling-publisher/etc/polling-publisher.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/polling-publisher/polling-service/etc/polling-service.urm.puml b/polling-publisher/polling-service/etc/polling-service.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/polling-publisher/polling-service/etc/polling-service.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/polling-publisher/polling-service/pom.xml b/polling-publisher/polling-service/pom.xml new file mode 100644 index 000000000000..a587a96521fe --- /dev/null +++ b/polling-publisher/polling-service/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + com.iluwatar + polling-publisher + 1.26.0-SNAPSHOT + + + polling-service + jar + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.polling-service.App + + + + + + + + + + diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/App.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/App.java new file mode 100644 index 000000000000..bd437846b9ed --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/App.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** Polling-Publisher pattern paradigm. */ +@SpringBootApplication +@EnableScheduling +public class App { + + /** + * Program entry point. + * + * @param args command line args. + */ + public static void main(String[] args) { + var context = SpringApplication.run(App.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } + } +} diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataRepository.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataRepository.java new file mode 100644 index 000000000000..61483e9dedcf --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataRepository.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import java.util.HashMap; +import java.util.Map; +import javax.annotation.PostConstruct; +import org.springframework.stereotype.Repository; + +/** Data repository to keep or store data. */ +@Repository +public class DataRepository { + + private final Map dataStorage = new HashMap<>(); + + /** init after map creation ... to put dummy data. */ + @PostConstruct + public void init() { + // Injecting dummy data at startup + dataStorage.put(2, "Initial Dummy Data - two - 2"); + dataStorage.put(3, "Initial Dummy Data - three - 3"); + dataStorage.put(4, "Initial Dummy Data - four - 4"); + } + + /** Save data to the repository. */ + public void save(int id, String value) { + dataStorage.put(id, value); + } + + /** Retrieve data by ID. */ + public String findById(int id) { + return dataStorage.getOrDefault(id, "Data not found"); + } + + /** Delete data by ID. */ + public void delete(int id) { + dataStorage.remove(id); + } + + /** Get all data. */ + public Map findAll() { + return dataStorage; + } +} diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataSourceService.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataSourceService.java new file mode 100644 index 000000000000..70c091b90ce6 --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/DataSourceService.java @@ -0,0 +1,99 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import java.util.Map; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +/** This class is responsible for keeping the events. */ +@Service +public class DataSourceService { + + private static final Logger log = LoggerFactory.getLogger(DataSourceService.class); + + private final DataRepository repository; + private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + + /** Constructor & Scheduler to push random data. */ + @org.springframework.beans.factory.annotation.Autowired + public DataSourceService(DataRepository repository) { + this(repository, true); + } + + /** + * Constructor with option to start the scheduler. + * + * @param repository the data repository + * @param startScheduler true to start the data generation scheduler + */ + public DataSourceService(DataRepository repository, boolean startScheduler) { + this.repository = repository; + if (startScheduler) { + scheduleDataGeneration(); + } + } + + private void scheduleDataGeneration() { + Random random = new Random(); + scheduler.scheduleAtFixedRate( + () -> { + int id = random.nextInt(100); // Random ID + String value = "Auto-Data-" + id; + this.addData(id, value); + log.info("🔵 Data Added: {} -> {}", id, value); + }, + 0, + 3, + TimeUnit.SECONDS); + } + + public void addData(int id, String value) { + repository.save(id, value); + } + + public String getData(int id) { + return repository.findById(id); + } + + public void removeData(int id) { + repository.delete(id); + } + + public Map getAllData() { + return repository.findAll(); + } + + @javax.annotation.PreDestroy + public void shutdown() { + scheduler.shutdown(); + } +} diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/KafkaProducer.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/KafkaProducer.java new file mode 100644 index 000000000000..23479f83250a --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/KafkaProducer.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +/** This class is responsible for sending messages to Kafka. */ +@Component +public class KafkaProducer { + + @Autowired private final KafkaTemplate kafkaTemplate; + + public KafkaProducer(KafkaTemplate kafkaTemplate) { + this.kafkaTemplate = kafkaTemplate; + } + + /** + * Sends a message to the Kafka topic. + * + * @param message The message to send. + */ + public void sendMessage(String topic, String message) { + kafkaTemplate.send(topic, message); + } +} diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingController.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingController.java new file mode 100644 index 000000000000..cf78fc716c19 --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingController.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** This class is responsible for contolling polling tasks. */ +@RestController +public class PollingController { + + @Autowired private KafkaProducer kafkaProducer; + + @GetMapping("/health") + public String healthCheck() { + return "Polling Service is up and running!"; + } + + @PostMapping("/send") + public String sendMessage(@RequestParam("message") String message) { + kafkaProducer.sendMessage("API", message); + return "Message sent: " + message; + } +} diff --git a/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingScheduler.java b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingScheduler.java new file mode 100644 index 000000000000..5c8361c2ff67 --- /dev/null +++ b/polling-publisher/polling-service/src/main/java/com/iluwatar/polling/PollingScheduler.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import java.util.Random; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** This class is responsible for scheduling polling tasks. */ +@Component +public class PollingScheduler { + + private static final Logger log = LoggerFactory.getLogger(PollingScheduler.class); + @Autowired private DataSourceService dataSourceService; + @Autowired private KafkaProducer kafkaProducer; + + /** Scheduler for poll data on each 5 second. */ + @Scheduled(fixedRate = 5000) // Poll every 5 seconds + public void pollDataSource() { + try { + int id = new Random().nextInt(100); // Pick a random ID + String data = dataSourceService.getData(id); // Get data from service + + if (data != null) { + log.info("🟢 Publishing Data: {}", data); + kafkaProducer.sendMessage("updates", data); + } else { + log.info("🔴 No Data Found for ID: {}", id); + } + } catch (Exception e) { + log.error("Error while publishing data {}", e.getMessage()); + throw new RuntimeException(e); + } + } +} diff --git a/polling-publisher/polling-service/src/main/resources/application.yml b/polling-publisher/polling-service/src/main/resources/application.yml new file mode 100644 index 000000000000..3ad766e6d017 --- /dev/null +++ b/polling-publisher/polling-service/src/main/resources/application.yml @@ -0,0 +1,36 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +server: + port: 8081 + +spring: + kafka: + bootstrap-servers: localhost:9092 # Kafka broker address(es) + consumer: + group-id: subscriber-group # Consumer group ID + auto-offset-reset: earliest # How to reset offset on consumer startup + # Add other consumer properties here + diff --git a/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/AppTest.java b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/AppTest.java new file mode 100644 index 000000000000..458a29fba88e --- /dev/null +++ b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/AppTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.polling; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.test.context.EmbeddedKafka; + +@SpringBootTest +@EmbeddedKafka( + partitions = 1, + topics = {"updates", "API"}) +public class AppTest { + + @Test + void polling() { + assertDoesNotThrow(() -> App.main(new String[] {"test"})); + } +} diff --git a/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataRepositoryTest.java b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataRepositoryTest.java new file mode 100644 index 000000000000..034019462a02 --- /dev/null +++ b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataRepositoryTest.java @@ -0,0 +1,78 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.polling; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class DataRepositoryTest { + + private DataRepository repository; + + @BeforeEach + void setUp() { + repository = new DataRepository(); // Initialize before each test + } + + @Test + void testSaveAndFindById() { + repository.save(1, "Test Data"); + + String result = repository.findById(1); + + assertEquals("Test Data", result, "The retrieved data should match the stored value."); + } + + @Test + void testFindById_NotFound() { + String result = repository.findById(99); + + assertEquals("Data not found", result, "Should return 'Data not found' for missing entries."); + } + + @Test + void testDelete() { + repository.save(2, "To be deleted"); + repository.delete(2); + + String result = repository.findById(2); + + assertEquals("Data not found", result, "Deleted data should not be retrievable."); + } + + @Test + void testFindAll() { + repository.save(1, "First"); + repository.save(2, "Second"); + + Map allData = repository.findAll(); + + assertEquals(2, allData.size(), "The repository should contain two items."); + assertTrue(allData.containsKey(1) && allData.containsKey(2), "Both keys should exist."); + } +} diff --git a/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataSourceServiceTest.java b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataSourceServiceTest.java new file mode 100644 index 000000000000..bbcd881c7d59 --- /dev/null +++ b/polling-publisher/polling-service/src/test/java/com/iluwatar/polling/DataSourceServiceTest.java @@ -0,0 +1,84 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.polling; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; +import org.junit.jupiter.api.*; + +public class DataSourceServiceTest { + + private DataRepository repository; + private DataSourceService service; + + @BeforeEach + void setUp() { + repository = new DataRepository(); + service = new DataSourceService(repository, false); + } + + @Test + void testAddData() { + service.addData(1, "Test Data"); + + assertEquals("Test Data", repository.findById(1)); + } + + @Test + void testGetData() { + repository.save(1, "Test Data"); + + String result = service.getData(1); + + assertEquals("Test Data", result, "The retrieved data should match."); + } + + @Test + void testRemoveData() { + repository.save(2, "Some Data"); + + service.removeData(2); + + assertEquals( + "Data not found", repository.findById(2), "Deleted data should not be retrievable."); + } + + @Test + void testGetAllData() { + Map result = service.getAllData(); + + int size = result.size(); + repository.save(1, "First"); + repository.save(2, "Second"); + + Map result1 = service.getAllData(); + + assertEquals(size + 2, result1.size(), "Should return all stored data."); + assertEquals("First", result1.get(1), "Value for key 1 should be 'First'."); + assertEquals("Second", result1.get(2), "Value for key 2 should be 'Second'."); + } +} diff --git a/polling-publisher/pom.xml b/polling-publisher/pom.xml new file mode 100644 index 000000000000..1f69809390af --- /dev/null +++ b/polling-publisher/pom.xml @@ -0,0 +1,106 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + polling-publisher + pom + + + polling-service + subscriber-service + + + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + org.springframework.kafka + spring-kafka + 3.3.2 + + + + org.springframework.kafka + spring-kafka-test + 3.3.2 + test + + + + + org.springframework.boot + spring-boot + ${spring-boot.version} + + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + ch.qos.logback + logback-core + 1.5.34 + + + ch.qos.logback + logback-classic + 1.5.34 + + + + + diff --git a/polling-publisher/subscriber-service/etc/subscriber-service.urm.puml b/polling-publisher/subscriber-service/etc/subscriber-service.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/polling-publisher/subscriber-service/etc/subscriber-service.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/polling-publisher/subscriber-service/pom.xml b/polling-publisher/subscriber-service/pom.xml new file mode 100644 index 000000000000..384f1b66c244 --- /dev/null +++ b/polling-publisher/subscriber-service/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + com.iluwatar + polling-publisher + 1.26.0-SNAPSHOT + + + subscriber-service + jar + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.subscriber-service.App + + + + + + + + + + diff --git a/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/App.java b/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/App.java new file mode 100644 index 000000000000..140210899cab --- /dev/null +++ b/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/App.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subscriber; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** Polling-Publisher pattern paradigm. */ +@SpringBootApplication +public class App { + public static void main(String[] args) { + var context = SpringApplication.run(App.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } + } +} diff --git a/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/KafkaConsumer.java b/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/KafkaConsumer.java new file mode 100644 index 000000000000..c159b467dcf1 --- /dev/null +++ b/polling-publisher/subscriber-service/src/main/java/com/iluwatar/subscriber/KafkaConsumer.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subscriber; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Service; + +/** Kafka consumer service to consume messages / updates. */ +@Service +public class KafkaConsumer { + + private static final Logger log = LoggerFactory.getLogger(KafkaConsumer.class); + + @KafkaListener(topics = "updates", groupId = "subscriber-group") + public void listenUpdates(String message) { + log.info("[updates]: Received message: {}", message); + } + + @KafkaListener(topics = "API", groupId = "subscriber-group") + public void listenApi(String message) { + log.info("[API]: Received message from /send : {}", message); + } +} diff --git a/polling-publisher/subscriber-service/src/main/resources/application.yml b/polling-publisher/subscriber-service/src/main/resources/application.yml new file mode 100644 index 000000000000..16b8425f39b5 --- /dev/null +++ b/polling-publisher/subscriber-service/src/main/resources/application.yml @@ -0,0 +1,33 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +server: + port: 8082 + +spring: + kafka: + bootstrap-servers: localhost:9092 # Kafka broker address(es) + consumer: + group-id: subscriber-group \ No newline at end of file diff --git a/polling-publisher/subscriber-service/src/test/java/com/iluwatar/subscriber/AppTest.java b/polling-publisher/subscriber-service/src/test/java/com/iluwatar/subscriber/AppTest.java new file mode 100644 index 000000000000..c479eb5b832b --- /dev/null +++ b/polling-publisher/subscriber-service/src/test/java/com/iluwatar/subscriber/AppTest.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subscriber; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.test.context.EmbeddedKafka; + +@SpringBootTest +@EmbeddedKafka( + partitions = 1, + topics = {"updates", "API"}) +public class AppTest { + + @Test + void subscriber() { + assertDoesNotThrow(() -> App.main(new String[] {"test"})); + } +} diff --git a/pom.xml b/pom.xml index 46429c75af7c..4ed64e643219 100644 --- a/pom.xml +++ b/pom.xml @@ -39,16 +39,16 @@ UTF-8 - 3.4.4 + 3.4.5 5.11.4 5.14.2 - 1.5.18 - 2.0.17 + 1.5.34 + 2.0.18 0.8.13 1.4 - 4.7.0 + 4.17.0 2.11.0 6.0.0 1.1.0 @@ -59,11 +59,11 @@ 3.5.2 - 4.6 + 5.0.0 3.14.0 - 5.0.0.4389 + 5.1.0.4751 https://sonarcloud.io iluwatar iluwatar_java-design-patterns @@ -80,6 +80,7 @@ anti-corruption-layer arrange-act-assert async-method-invocation + backends-for-frontends balking bloc bridge @@ -106,6 +107,7 @@ converter curiously-recurring-template-pattern currying + dao-factory data-access-object data-bus data-locality @@ -137,6 +139,7 @@ fluent-interface flux flyweight + fork-join front-controller function-composition game-loop @@ -146,6 +149,7 @@ health-check hexagonal-architecture identity-map + immutable intercepting-filter interpreter iterator @@ -166,6 +170,8 @@ microservices-distributed-tracing microservices-idempotent-consumer microservices-log-aggregation + microservices-self-registration + microservices-messaging model-view-controller model-view-intent model-view-presenter @@ -189,6 +195,7 @@ partial-response pipeline poison-pill + polling-publisher presentation-model private-class-data producer-consumer @@ -204,6 +211,7 @@ resource-acquisition-is-initialization retry role-object + rule-engine saga separated-interface serialized-entity @@ -230,6 +238,8 @@ table-module template-method templateview + thread-pool-executor + thread-specific-storage throttling tolerant-reader trampoline @@ -240,9 +250,15 @@ update-method value-object version-number + view-helper virtual-proxy visitor - backpressure + write-ahead-log + backpressure + actor-model + rate-limiting-pattern + fallback + onion-architecture
@@ -316,12 +332,6 @@ ${junit.version} test - - org.junit.jupiter - junit-jupiter-params - ${junit.version} - test - org.junit.jupiter junit-jupiter-migrationsupport @@ -343,6 +353,11 @@ mockito-core ${mockito.version} + + org.mockito + mockito-junit-jupiter + ${mockito.version} + org.mongodb bson @@ -441,6 +456,7 @@ src/test/resources/** src/main/resources/** checkstyle-suppressions.xml + **/*.ps1 @@ -481,7 +497,7 @@ com.diffplug.spotless spotless-maven-plugin - 2.44.4 + 3.8.0 diff --git a/producer-consumer/README.md b/producer-consumer/README.md index bb62c799a08f..575be804cd45 100644 --- a/producer-consumer/README.md +++ b/producer-consumer/README.md @@ -181,10 +181,6 @@ Program output: 08:10:17.483 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [10] produced by [Producer_1] ``` -## Detailed Explanation of Producer-Consumer Pattern with Real-World Examples - -![Producer-Consumer](./etc/producer-consumer.png "Producer-Consumer") - ## When to Use the Producer-Consumer Pattern in Java * When you need to manage a buffer or queue where producers add data and consumers take data, often in a multithreaded environment. diff --git a/prototype/README.md b/prototype/README.md index 48f10868a86c..b97df0707ffc 100644 --- a/prototype/README.md +++ b/prototype/README.md @@ -156,10 +156,6 @@ Here's the console output from running the example. 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish wolf attacks with laser ``` -## Detailed Explanation of Prototype Pattern with Real-World Examples - -![alt text](./etc/prototype.urm.png "Prototype pattern class diagram") - ## When to Use the Prototype Pattern in Java * When the classes to instantiate are specified at run-time, for example, by dynamic loading. diff --git a/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/model/Topic.java b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/model/Topic.java index 4c421afe735a..2011f096a5eb 100644 --- a/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/model/Topic.java +++ b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/model/Topic.java @@ -51,7 +51,7 @@ public void addSubscriber(Subscriber subscriber) { } /** - * Remove a subscriber to the list of subscribers. + * Remove a subscriber from the list of subscribers. * * @param subscriber subscriber to remove */ diff --git a/rate-limiting-pattern/README.md b/rate-limiting-pattern/README.md new file mode 100644 index 000000000000..de7742a5d13f --- /dev/null +++ b/rate-limiting-pattern/README.md @@ -0,0 +1,328 @@ +--- +title: "Rate Limiting Pattern in Java: Controlling System Overload Gracefully" +shortTitle: Rate Limiting +description: "Explore multiple rate limiting strategies in Java—Token Bucket, Fixed Window, and Adaptive Limiting. Learn with diagrams, programmatic examples, and real-world simulation." +category: Behavioral +language: en +tag: + - Resilience + - System Overload Protection + - API Throttling + - Concurrency + - Cloud Patterns +--- + +## Also known as + +- Throttling +- Request Limiting +- API Rate Limiting + +--- + +## Intent of Rate Limiting Design Pattern + +To regulate the number of requests sent to a service in a specific time window, avoiding resource exhaustion and ensuring system stability. This is especially useful in distributed and cloud-native architectures. + +--- + +## Detailed Explanation of Rate Limiting with Real-World Examples + +### Real-world example + +Imagine you're entering a concert hall that only allows 50 people per minute. If too many fans arrive at once, the gate staff slows down entry, allowing only a few at a time. This prevents overcrowding and ensures safety. Similarly, the rate limiter controls how many requests are processed to avoid overloading a server. + +### In plain words + +Regulate the number of requests a system handles within a time frame to protect availability and performance. + + +### AWS says + +> "API Gateway limits the steady-state rate and burst rate of requests that it allows for each method in your REST APIs. When request rates exceed these limits, API Gateway begins to throttle requests." + +— [API Gateway quotas and important notes - AWS Documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html) + +--- + +## Architecture Diagram + +![UML Class Diagram](etc/UMLClassDiagram.png) + +This UML shows the key components: +- `RateLimiter` interface +- `TokenBucketRateLimiter`, `FixedWindowRateLimiter`, `AdaptiveRateLimiter` +- Supporting exception classes +- `FindCustomerRequest` as a rate-limited operation + +--- + +## Flowcharts + +### 1. Token Bucket Strategy + +![Token Bucket Rate Limiter](etc/TokenBucketRateLimiter.png) + +### 2. Fixed Window Strategy + +![Fixed Window Rate Limiter](etc/FixedWindowRateLimiter.png) + +### 3. Adaptive Rate Limiting Strategy + +![Adaptive Rate Limiter](etc/AdaptiveRateLimiter.png) + +--- + +### Programmatic Example of Rate Limiter Pattern in Java + +The **Rate Limiter** design pattern helps protect systems from overload by restricting the number of operations that can be performed in a given time window. It is especially useful when accessing shared resources, APIs, or services that are sensitive to spikes in traffic. + +This implementation demonstrates three strategies for rate limiting: + +- **Token Bucket Rate Limiter** +- **Fixed Window Rate Limiter** +- **Adaptive Rate Limiter** + +Let’s walk through the key components. + +--- + +#### 1. Token Bucket Rate Limiter + +The token bucket allows short bursts followed by a steady rate. Tokens are added periodically and requests are only allowed if a token is available. + +```java +public class TokenBucketRateLimiter implements RateLimiter { + private final int capacity; + private final int refillRate; + private final ConcurrentHashMap buckets = new ConcurrentHashMap<>(); + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + public TokenBucketRateLimiter(int capacity, int refillRate) { + this.capacity = capacity; + this.refillRate = refillRate; + scheduler.scheduleAtFixedRate(this::refillBuckets, 1, 1, TimeUnit.SECONDS); + } + + @Override + public void check(String serviceName, String operationName) throws RateLimitException { + String key = serviceName + ":" + operationName; + TokenBucket bucket = buckets.computeIfAbsent(key, k -> new TokenBucket(capacity)); + if (!bucket.tryConsume()) { + throw new ThrottlingException(serviceName, operationName, 1000); + } + } + + private void refillBuckets() { + buckets.forEach((k, b) -> b.refill(refillRate)); + } + + private static class TokenBucket { + private final int capacity; + private final AtomicInteger tokens; + + TokenBucket(int capacity) { + this.capacity = capacity; + this.tokens = new AtomicInteger(capacity); + } + + boolean tryConsume() { + while (true) { + int current = tokens.get(); + if (current <= 0) return false; + if (tokens.compareAndSet(current, current - 1)) return true; + } + } + + void refill(int amount) { + tokens.getAndUpdate(current -> Math.min(current + amount, capacity)); + } + } +} +``` + +--- + +#### 2. Fixed Window Rate Limiter + +This strategy uses a simple counter within a fixed time window. + +```java +public class FixedWindowRateLimiter implements RateLimiter { + private final int limit; + private final long windowMillis; + private final ConcurrentHashMap counters = new ConcurrentHashMap<>(); + + public FixedWindowRateLimiter(int limit, long windowSeconds) { + this.limit = limit; + this.windowMillis = TimeUnit.SECONDS.toMillis(windowSeconds); + } + + @Override + public synchronized void check(String serviceName, String operationName) throws RateLimitException { + String key = serviceName + ":" + operationName; + WindowCounter counter = counters.computeIfAbsent(key, k -> new WindowCounter()); + + if (!counter.tryIncrement()) { + throw new RateLimitException("Rate limit exceeded for " + key, windowMillis); + } + } + + private class WindowCounter { + private AtomicInteger count = new AtomicInteger(0); + private volatile long windowStart = System.currentTimeMillis(); + + synchronized boolean tryIncrement() { + long now = System.currentTimeMillis(); + if (now - windowStart > windowMillis) { + count.set(0); + windowStart = now; + } + return count.incrementAndGet() <= limit; + } + } +} +``` + +--- + +#### 3. Adaptive Rate Limiter + +This version adjusts the rate based on system health, reducing the rate when throttling occurs and recovering periodically. + +```java +public class AdaptiveRateLimiter implements RateLimiter { + private final int initialLimit; + private final int maxLimit; + private final AtomicInteger currentLimit; + private final ConcurrentHashMap limiters = new ConcurrentHashMap<>(); + private final ScheduledExecutorService healthChecker = Executors.newScheduledThreadPool(1); + + public AdaptiveRateLimiter(int initialLimit, int maxLimit) { + this.initialLimit = initialLimit; + this.maxLimit = maxLimit; + this.currentLimit = new AtomicInteger(initialLimit); + healthChecker.scheduleAtFixedRate(this::adjustLimits, 10, 10, TimeUnit.SECONDS); + } + + @Override + public void check(String serviceName, String operationName) throws RateLimitException { + String key = serviceName + ":" + operationName; + int current = currentLimit.get(); + RateLimiter limiter = limiters.computeIfAbsent(key, k -> new TokenBucketRateLimiter(current, current)); + + try { + limiter.check(serviceName, operationName); + } catch (RateLimitException e) { + currentLimit.updateAndGet(curr -> Math.max(initialLimit, curr / 2)); + throw e; + } + } + + private void adjustLimits() { + currentLimit.updateAndGet(curr -> Math.min(maxLimit, curr + (initialLimit / 2))); + } +} +``` + +--- + +#### 4. Simulated Demo Using All Limiters + +```java +public final class App { + public static void main(String[] args) { + TokenBucketRateLimiter tb = new TokenBucketRateLimiter(2, 1); + FixedWindowRateLimiter fw = new FixedWindowRateLimiter(3, 1); + AdaptiveRateLimiter ar = new AdaptiveRateLimiter(2, 6); + + ExecutorService executor = Executors.newFixedThreadPool(3); + for (int i = 1; i <= 3; i++) { + executor.submit(createClientTask(i, tb, fw, ar)); + } + } + + private static Runnable createClientTask(int clientId, RateLimiter tb, RateLimiter fw, RateLimiter ar) { + return () -> { + String[] services = {"s3", "dynamodb", "lambda"}; + String[] operations = {"GetObject", "PutObject", "Query", "Scan", "PutItem", "Invoke", "ListFunctions"}; + Random random = new Random(); + + while (true) { + String service = services[random.nextInt(services.length)]; + String operation = operations[random.nextInt(operations.length)]; + try { + switch (service) { + case "s3" -> tb.check(service, operation); + case "dynamodb" -> fw.check(service, operation); + case "lambda" -> ar.check(service, operation); + } + System.out.printf("Client %d: %s.%s - ALLOWED%n", clientId, service, operation); + } catch (RateLimitException e) { + System.out.printf("Client %d: %s.%s - THROTTLED%n", clientId, service, operation); + } + + try { + Thread.sleep(30 + random.nextInt(50)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }; + } +} +``` + +--- + +This example highlights how the Rate Limiter pattern supports various throttling techniques and how they respond under simulated traffic pressure, making it invaluable for building scalable, resilient systems. + +## When to Use Rate Limiting + +- APIs receiving unpredictable traffic +- Shared cloud resources (e.g., DB, compute) +- Services requiring fair client usage +- Preventing DoS or abuse + +--- + +## Real-World Applications + +- **AWS API Gateway** +- **Google Cloud Functions** +- **Netflix Zuul API Gateway** +- **Stripe API Throttling** + +--- + +## Benefits and Trade-offs + +### Benefits + +- Protects backend from overload +- Fair distribution of resources +- Better user experience under load + +### Trade-offs + +- May delay valid requests +- Requires tuning of limits +- Could create bottlenecks if misused + +--- + +## Related Java Design Patterns + +- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) +- [Retry](https://java-design-patterns.com/patterns/retry/) +- [Throttling Queue](https://java-design-patterns.com/patterns/throttling/) + +--- + +## References and Credits + +- [Microsoft Cloud Design Patterns](https://learn.microsoft.com/en-us/azure/architecture/patterns/throttling) +- [AWS API Gateway Throttling](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html) +- *Designing Data-Intensive Applications* by Martin Kleppmann +- [Resilience4j](https://resilience4j.readme.io/) +- Java Design Patterns Project: [java-design-patterns](https://github.com/iluwatar/java-design-patterns) diff --git a/rate-limiting-pattern/etc/AdaptiveRateLimiter.png b/rate-limiting-pattern/etc/AdaptiveRateLimiter.png new file mode 100644 index 000000000000..2d849ee8d057 Binary files /dev/null and b/rate-limiting-pattern/etc/AdaptiveRateLimiter.png differ diff --git a/rate-limiting-pattern/etc/FixedWindowRateLimiter.png b/rate-limiting-pattern/etc/FixedWindowRateLimiter.png new file mode 100644 index 000000000000..a81f61d7fa95 Binary files /dev/null and b/rate-limiting-pattern/etc/FixedWindowRateLimiter.png differ diff --git a/rate-limiting-pattern/etc/TokenBucketRateLimiter.png b/rate-limiting-pattern/etc/TokenBucketRateLimiter.png new file mode 100644 index 000000000000..d41701781e27 Binary files /dev/null and b/rate-limiting-pattern/etc/TokenBucketRateLimiter.png differ diff --git a/rate-limiting-pattern/etc/UMLClassDiagram.png b/rate-limiting-pattern/etc/UMLClassDiagram.png new file mode 100644 index 000000000000..9292880244e0 Binary files /dev/null and b/rate-limiting-pattern/etc/UMLClassDiagram.png differ diff --git a/rate-limiting-pattern/pom.xml b/rate-limiting-pattern/pom.xml new file mode 100644 index 000000000000..370b59e7b283 --- /dev/null +++ b/rate-limiting-pattern/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + rate-limiter + + + UTF-8 + 5.11.1 + 1.11.1 + + + + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + + org.mockito + mockito-core + 5.12.0 + test + + + + org.slf4j + slf4j-api + 2.0.18 + + + + ch.qos.logback + logback-classic + 1.5.34 + + + + org.assertj + assertj-core + 3.27.7 + test + + + + + + + com.diffplug.spotless + spotless-maven-plugin + 3.8.0 + + + + check + apply + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + + false + + + + + diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiter.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiter.java new file mode 100644 index 000000000000..4501bb0e9acc --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiter.java @@ -0,0 +1,79 @@ +package com.iluwatar.rate.limiting.pattern; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +/** Adaptive rate limiter that adjusts limits based on system health. */ +public class AdaptiveRateLimiter implements RateLimiter { + private final int initialLimit; + private final int maxLimit; + private final AtomicInteger currentLimit; + private final ConcurrentHashMap limiters = new ConcurrentHashMap<>(); + private final ScheduledExecutorService healthChecker = Executors.newScheduledThreadPool(1); + private final long checkInterval; + private final TimeUnit timeUnit; + + public AdaptiveRateLimiter(int initialLimit, int maxLimit) { + this(initialLimit, maxLimit, 10, TimeUnit.SECONDS); + } + + /** + * Constructor with option to set custom interval. + * + * @param initialLimit initial rate limit + * @param maxLimit maximum rate limit + * @param interval check interval + * @param timeUnit check interval time unit + */ + public AdaptiveRateLimiter(int initialLimit, int maxLimit, long interval, TimeUnit timeUnit) { + this.initialLimit = initialLimit; + this.maxLimit = maxLimit; + this.currentLimit = new AtomicInteger(initialLimit); + this.checkInterval = interval; + this.timeUnit = timeUnit; + healthChecker.scheduleAtFixedRate(this::adjustLimits, interval, interval, timeUnit); + } + + @Override + public void check(String serviceName, String operationName) throws RateLimitException { + String key = serviceName + ":" + operationName; + int current = currentLimit.get(); + + // Reuse or create TokenBucket for this key using currentLimit and checkInterval + RateLimiter limiter = + limiters.computeIfAbsent( + key, k -> new TokenBucketRateLimiter(current, current, checkInterval, timeUnit)); + + try { + limiter.check(serviceName, operationName); + System.out.printf( + "[Adaptive] Allowed %s.%s - CurrentLimit: %d%n", serviceName, operationName, current); + } catch (RateLimitException e) { + // On throttling, reduce system limit to reduce load + currentLimit.updateAndGet(curr -> Math.max(initialLimit, curr / 2)); + System.out.printf( + "[Adaptive] Throttled %s.%s - Decreasing limit to %d%n", + serviceName, operationName, currentLimit.get()); + throw e; + } + } + + // Periodic recovery mechanism to raise limits when the system is under control + private void adjustLimits() { + int updated = currentLimit.updateAndGet(curr -> Math.min(maxLimit, curr + (initialLimit / 2))); + System.out.printf("[Adaptive] Health check passed - Increasing limit to %d%n", updated); + } + + /** Gracefully shut down the health checker executor and child limiters. */ + public void shutdown() { + healthChecker.shutdown(); + limiters + .values() + .forEach( + limiter -> { + if (limiter instanceof TokenBucketRateLimiter) { + ((TokenBucketRateLimiter) limiter).shutdown(); + } + }); + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/App.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/App.java new file mode 100644 index 000000000000..e76ed5254345 --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/App.java @@ -0,0 +1,178 @@ +package com.iluwatar.rate.limiting.pattern; + +import java.security.SecureRandom; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Rate Limiter pattern is a key defensive strategy used to prevent system overload and + * ensure fair usage of shared services. This demo showcases how different rate limiting techniques + * can regulate traffic in distributed systems. + * + *

Specifically, this simulation implements three rate limiter strategies: + * + *

    + *
  • Token Bucket – Allows short bursts followed by steady request rates. + *
  • Fixed Window – Enforces a strict limit per discrete time window (e.g., 3 + * requests/sec). + *
  • Adaptive – Dynamically scales limits based on system health, simulating elastic + * backoff. + *
+ * + *

Each simulated service (e.g., S3, DynamoDB, Lambda) is governed by one of these limiters. + * Multiple concurrent client threads issue randomized requests to these services over a fixed + * duration. Each request is either: + * + *

    + *
  • ALLOWED – Permitted under the current rate limit + *
  • THROTTLED – Rejected due to quota exhaustion + *
  • FAILED – Dropped due to transient service failure + *
+ * + *

Statistics are printed every few seconds, and the simulation exits gracefully after a fixed + * runtime, offering a clear view into how each limiter behaves under pressure. + * + *

Relation to AWS API Gateway:
+ * This implementation mirrors the throttling behavior described in the + * AWS API Gateway Request Throttling documentation, where limits are applied per second and + * over longer durations (burst and rate limits). The TokenBucketRateLimiter mimics + * burst capacity, the FixedWindowRateLimiter models steady rate enforcement, and the + * AdaptiveRateLimiter reflects elasticity in real-world systems like AWS Lambda under + * variable load. + */ +public final class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + private static final int RUN_DURATION_SECONDS = 10; + private static final int SHUTDOWN_TIMEOUT_SECONDS = 5; + + static final AtomicInteger successfulRequests = new AtomicInteger(); + static final AtomicInteger throttledRequests = new AtomicInteger(); + static final AtomicInteger failedRequests = new AtomicInteger(); + static final AtomicBoolean running = new AtomicBoolean(true); + private static final String DIVIDER_LINE = "===================================="; + + public static void main(String[] args) { + LOGGER.info("Starting Rate Limiter Demo"); + LOGGER.info(DIVIDER_LINE); + + ExecutorService executor = Executors.newFixedThreadPool(3); + ScheduledExecutorService statsPrinter = Executors.newSingleThreadScheduledExecutor(); + + try { + TokenBucketRateLimiter tb = new TokenBucketRateLimiter(2, 1); + FixedWindowRateLimiter fw = new FixedWindowRateLimiter(3, 1); + AdaptiveRateLimiter ar = new AdaptiveRateLimiter(2, 6); + + statsPrinter.scheduleAtFixedRate(App::printStats, 2, 2, TimeUnit.SECONDS); + + for (int i = 1; i <= 3; i++) { + executor.submit(createClientTask(i, tb, fw, ar)); + } + + Thread.sleep(RUN_DURATION_SECONDS * 1000L); + LOGGER.info("Shutting down the demo..."); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + running.set(false); + shutdownExecutor(executor, "mainExecutor"); + shutdownExecutor(statsPrinter, "statsPrinter"); + printFinalStats(); + LOGGER.info("Demo completed."); + } + } + + private static void shutdownExecutor(ExecutorService service, String name) { + service.shutdown(); + try { + if (!service.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + service.shutdownNow(); + LOGGER.warn("Forced shutdown of {}", name); + } + } catch (InterruptedException e) { + service.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + static Runnable createClientTask( + int clientId, RateLimiter s3Limiter, RateLimiter dynamoDbLimiter, RateLimiter lambdaLimiter) { + + return () -> { + String[] services = {"s3", "dynamodb", "lambda"}; + String[] operations = { + "GetObject", "PutObject", "Query", "Scan", "PutItem", "Invoke", "ListFunctions" + }; + SecureRandom random = new SecureRandom(); // ✅ Safe & compliant for SonarCloud + + while (running.get() && !Thread.currentThread().isInterrupted()) { + try { + String service = services[random.nextInt(services.length)]; + String operation = operations[random.nextInt(operations.length)]; + + switch (service) { + case "s3" -> makeRequest(clientId, s3Limiter, service, operation); + case "dynamodb" -> makeRequest(clientId, dynamoDbLimiter, service, operation); + case "lambda" -> makeRequest(clientId, lambdaLimiter, service, operation); + default -> LOGGER.warn("Unknown service: {}", service); + } + + Thread.sleep(30L + random.nextInt(50)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }; + } + + static void makeRequest(int clientId, RateLimiter limiter, String service, String operation) { + try { + limiter.check(service, operation); + successfulRequests.incrementAndGet(); + LOGGER.info("Client {}: {}.{} - ALLOWED", clientId, service, operation); + } catch (ThrottlingException e) { + throttledRequests.incrementAndGet(); + LOGGER.warn( + "Client {}: {}.{} - THROTTLED (Retry in {}ms)", + clientId, + service, + operation, + e.getRetryAfterMillis()); + } catch (ServiceUnavailableException e) { + failedRequests.incrementAndGet(); + LOGGER.warn("Client {}: {}.{} - SERVICE UNAVAILABLE", clientId, service, operation); + } catch (Exception e) { + failedRequests.incrementAndGet(); + LOGGER.error("Client {}: {}.{} - ERROR: {}", clientId, service, operation, e.getMessage()); + } + } + + static void printStats() { + if (!running.get()) return; + LOGGER.info("=== Current Statistics ==="); + LOGGER.info("Successful Requests: {}", successfulRequests.get()); + LOGGER.info("Throttled Requests : {}", throttledRequests.get()); + LOGGER.info("Failed Requests : {}", failedRequests.get()); + LOGGER.info(DIVIDER_LINE); + } + + static void printFinalStats() { + LOGGER.info("Final Statistics"); + LOGGER.info(DIVIDER_LINE); + LOGGER.info("Successful Requests: {}", successfulRequests.get()); + LOGGER.info("Throttled Requests : {}", throttledRequests.get()); + LOGGER.info("Failed Requests : {}", failedRequests.get()); + LOGGER.info(DIVIDER_LINE); + } + + static void resetCountersForTesting() { + successfulRequests.set(0); + throttledRequests.set(0); + failedRequests.set(0); + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequest.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequest.java new file mode 100644 index 000000000000..a61fc35f496a --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequest.java @@ -0,0 +1,40 @@ +package com.iluwatar.rate.limiting.pattern; + +/** + * A rate-limited customer lookup operation. This class wraps the rate limiting logic and represents + * an executable business request. + */ +public class FindCustomerRequest implements RateLimitOperation { + private final String customerId; + private final RateLimiter rateLimiter; + + public FindCustomerRequest(String customerId, RateLimiter rateLimiter) { + this.customerId = customerId; + this.rateLimiter = rateLimiter; + } + + @Override + public String getServiceName() { + return "CustomerService"; + } + + @Override + public String getOperationName() { + return "FindCustomer"; + } + + @Override + public String execute() throws RateLimitException { + // Ensure the operation respects the assigned rate limiter + rateLimiter.check(getServiceName(), getOperationName()); + + // Simulate actual operation + try { + Thread.sleep(50); // Simulate processing time + return "Customer-" + customerId; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ServiceUnavailableException(getServiceName(), 1000); + } + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiter.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiter.java new file mode 100644 index 000000000000..3a2b52888ca7 --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiter.java @@ -0,0 +1,53 @@ +package com.iluwatar.rate.limiting.pattern; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Implements a fixed window rate limiter. It allows up to 'limit' number of requests within a time + * window of fixed size. + */ +public class FixedWindowRateLimiter implements RateLimiter { + private final int limit; + private final long windowMillis; + private final ConcurrentHashMap counters = new ConcurrentHashMap<>(); + + public FixedWindowRateLimiter(int limit, long windowSeconds) { + this.limit = limit; + this.windowMillis = TimeUnit.SECONDS.toMillis(windowSeconds); + } + + @Override + public synchronized void check(String serviceName, String operationName) + throws RateLimitException { + String key = serviceName + ":" + operationName; + WindowCounter counter = counters.computeIfAbsent(key, k -> new WindowCounter()); + + if (!counter.tryIncrement()) { + System.out.printf( + "[FixedWindow] Throttled %s.%s - Limit %d reached in window%n", + serviceName, operationName, limit); + throw new RateLimitException("Rate limit exceeded for " + key, windowMillis); + } else { + System.out.printf( + "[FixedWindow] Allowed %s.%s - Count within window%n", serviceName, operationName); + } + } + + /** Tracks the count of requests within the current window. */ + private class WindowCounter { + private AtomicInteger count = new AtomicInteger(0); + private volatile long windowStart = System.currentTimeMillis(); + + synchronized boolean tryIncrement() { + long now = System.currentTimeMillis(); + // Reset window if expired + if (now - windowStart > windowMillis) { + count.set(0); + windowStart = now; + } + // Enforce the request limit within window + return count.incrementAndGet() <= limit; + } + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitException.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitException.java new file mode 100644 index 000000000000..2b3cc1f3006b --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitException.java @@ -0,0 +1,15 @@ +package com.iluwatar.rate.limiting.pattern; + +/** Base exception for rate limiting errors. */ +public class RateLimitException extends Exception { + private final long retryAfterMillis; + + public RateLimitException(String message, long retryAfterMillis) { + super(message); + this.retryAfterMillis = retryAfterMillis; + } + + public long getRetryAfterMillis() { + return retryAfterMillis; + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitOperation.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitOperation.java new file mode 100644 index 000000000000..59191e81fc04 --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimitOperation.java @@ -0,0 +1,10 @@ +package com.iluwatar.rate.limiting.pattern; + +/** Represents a business operation that needs rate limiting. Supports type-safe return values. */ +public interface RateLimitOperation { + String getServiceName(); + + String getOperationName(); + + T execute() throws RateLimitException; +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimiter.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimiter.java new file mode 100644 index 000000000000..19495b401ddb --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/RateLimiter.java @@ -0,0 +1,13 @@ +package com.iluwatar.rate.limiting.pattern; + +/** Base interface for all rate limiter strategies. */ +public interface RateLimiter { + /** + * Checks if a request is allowed under current rate limits + * + * @param serviceName Service being called (e.g., "dynamodb") + * @param operationName Operation being performed (e.g., "Query") + * @throws RateLimitException if request exceeds limits + */ + void check(String serviceName, String operationName) throws RateLimitException; +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ServiceUnavailableException.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ServiceUnavailableException.java new file mode 100644 index 000000000000..f9fc55f15d20 --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ServiceUnavailableException.java @@ -0,0 +1,15 @@ +package com.iluwatar.rate.limiting.pattern; + +/** Exception for when a service is temporarily unavailable. */ +public class ServiceUnavailableException extends RateLimitException { + private final String serviceName; + + public ServiceUnavailableException(String serviceName, long retryAfterMillis) { + super("Service temporarily unavailable: " + serviceName, retryAfterMillis); + this.serviceName = serviceName; + } + + public String getServiceName() { + return serviceName; + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ThrottlingException.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ThrottlingException.java new file mode 100644 index 000000000000..e07087dfee6c --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/ThrottlingException.java @@ -0,0 +1,21 @@ +package com.iluwatar.rate.limiting.pattern; + +/** Exception thrown when AWS-style throttling occurs. */ +public class ThrottlingException extends RateLimitException { + private final String serviceName; + private final String errorCode; + + public ThrottlingException(String serviceName, String operationName, long retryAfterMillis) { + super("AWS throttling error for " + serviceName + "/" + operationName, retryAfterMillis); + this.serviceName = serviceName; + this.errorCode = "ThrottlingException"; + } + + public String getServiceName() { + return serviceName; + } + + public String getErrorCode() { + return errorCode; + } +} diff --git a/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiter.java b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiter.java new file mode 100644 index 000000000000..ded1396f1fff --- /dev/null +++ b/rate-limiting-pattern/src/main/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiter.java @@ -0,0 +1,80 @@ +package com.iluwatar.rate.limiting.pattern; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Token Bucket rate limiter implementation. Allows requests to proceed as long as there are tokens + * available in the bucket. Tokens are added at a fixed interval up to a defined capacity. + */ +public class TokenBucketRateLimiter implements RateLimiter { + private final int capacity; + private final int refillRate; + private final ConcurrentHashMap buckets = new ConcurrentHashMap<>(); + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + public TokenBucketRateLimiter(int capacity, int refillRate) { + this(capacity, refillRate, 1, TimeUnit.SECONDS); + } + + /** + * Constructor with custom refill interval. + * + * @param capacity token bucket capacity + * @param refillRate token refill rate + * @param refillInterval refill interval value + * @param timeUnit refill interval time unit + */ + public TokenBucketRateLimiter( + int capacity, int refillRate, long refillInterval, TimeUnit timeUnit) { + this.capacity = capacity; + this.refillRate = refillRate; + scheduler.scheduleAtFixedRate(this::refillBuckets, refillInterval, refillInterval, timeUnit); + } + + @Override + public void check(String serviceName, String operationName) throws RateLimitException { + String key = serviceName + ":" + operationName; + TokenBucket bucket = buckets.computeIfAbsent(key, k -> new TokenBucket(capacity)); + + if (!bucket.tryConsume()) { + System.out.printf( + "[TokenBucket] Throttled %s.%s - No tokens available%n", serviceName, operationName); + throw new ThrottlingException(serviceName, operationName, 1000); + } else { + System.out.printf( + "[TokenBucket] Allowed %s.%s - Tokens remaining%n", serviceName, operationName); + } + } + + private void refillBuckets() { + buckets.forEach((k, b) -> b.refill(refillRate)); + } + + /** Inner class that represents the bucket holding tokens for each service-operation. */ + private static class TokenBucket { + private final int capacity; + private final AtomicInteger tokens; + + TokenBucket(int capacity) { + this.capacity = capacity; + this.tokens = new AtomicInteger(capacity); + } + + boolean tryConsume() { + while (true) { + int current = tokens.get(); + if (current <= 0) return false; + if (tokens.compareAndSet(current, current - 1)) return true; + } + } + + void refill(int amount) { + tokens.getAndUpdate(current -> Math.min(current + amount, capacity)); + } + } + + public void shutdown() { + scheduler.shutdown(); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiterTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiterTest.java new file mode 100644 index 000000000000..330975353f7c --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AdaptiveRateLimiterTest.java @@ -0,0 +1,67 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class AdaptiveRateLimiterTest { + @Test + void shouldDecreaseLimitWhenThrottled() throws Exception { + AdaptiveRateLimiter limiter = new AdaptiveRateLimiter(10, 20); + try { + // Exceed initial limit + for (int i = 0; i < 11; i++) { + try { + limiter.check("test", "op"); + } catch (RateLimitException e) { + // Expected after 10 requests + } + } + + // Verify limit was reduced + assertThrows( + RateLimitException.class, + () -> { + for (int i = 0; i < 6; i++) { // New limit should be 5 (10/2) + limiter.check("test", "op"); + } + }); + } finally { + limiter.shutdown(); + } + } + + @Test + void shouldGraduallyIncreaseLimitWhenHealthy() throws Exception { + AdaptiveRateLimiter limiter = + new AdaptiveRateLimiter( + 4, + 10, + 100, + java.util.concurrent.TimeUnit + .MILLISECONDS); // Start from 4 → expect 2 → expect increase to 4 + try { + // Force throttling to reduce limit + for (int i = 0; i < 5; i++) { + try { + limiter.check("test", "op"); + } catch (RateLimitException e) { + // Expected to throttle and reduce limit + } + } + + // Wait for health check to increase limit + Thread.sleep(150); // Wait slightly more than 100 milliseconds + + // Allow up to 4 requests again (limit should've increased to 4) + for (int i = 0; i < 4; i++) { + limiter.check("test", "op"); + } + + // 5th should throw exception again + assertThrows(RateLimitException.class, () -> limiter.check("test", "op")); + } finally { + limiter.shutdown(); + } + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTest.java new file mode 100644 index 000000000000..11815a75de84 --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTest.java @@ -0,0 +1,59 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link App}. */ +class AppTest { + + private RateLimiter mockLimiter; + + @BeforeEach + void setUp() { + mockLimiter = mock(RateLimiter.class); + AppTestUtils.resetCounters(); // Ensures counters are clean before every test + } + + @Test + void shouldAllowRequest() { + AppTestUtils.invokeMakeRequest(1, mockLimiter, "s3", "GetObject"); + assertEquals(1, AppTestUtils.getSuccessfulRequests().get(), "Successful count should be 1"); + assertEquals(0, AppTestUtils.getThrottledRequests().get(), "Throttled count should be 0"); + assertEquals(0, AppTestUtils.getFailedRequests().get(), "Failed count should be 0"); + } + + @Test + void shouldHandleThrottlingException() throws Exception { + doThrow(new ThrottlingException("s3", "PutObject", 1000)).when(mockLimiter).check(any(), any()); + AppTestUtils.invokeMakeRequest(2, mockLimiter, "s3", "PutObject"); + assertEquals(0, AppTestUtils.getSuccessfulRequests().get()); + assertEquals(1, AppTestUtils.getThrottledRequests().get()); + assertEquals(0, AppTestUtils.getFailedRequests().get()); + } + + @Test + void shouldHandleServiceUnavailableException() throws Exception { + doThrow(new ServiceUnavailableException("lambda", 500)).when(mockLimiter).check(any(), any()); + AppTestUtils.invokeMakeRequest(3, mockLimiter, "lambda", "Invoke"); + assertEquals(0, AppTestUtils.getSuccessfulRequests().get()); + assertEquals(0, AppTestUtils.getThrottledRequests().get()); + assertEquals(1, AppTestUtils.getFailedRequests().get()); + } + + @Test + void shouldHandleGenericException() throws Exception { + doThrow(new RuntimeException("Unexpected")).when(mockLimiter).check(any(), any()); + AppTestUtils.invokeMakeRequest(4, mockLimiter, "dynamodb", "Query"); + assertEquals(0, AppTestUtils.getSuccessfulRequests().get()); + assertEquals(0, AppTestUtils.getThrottledRequests().get()); + assertEquals(1, AppTestUtils.getFailedRequests().get()); + } + + @Test + void shouldRunMainMethodWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTestUtils.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTestUtils.java new file mode 100644 index 000000000000..9d652ec96c63 --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/AppTestUtils.java @@ -0,0 +1,27 @@ +package com.iluwatar.rate.limiting.pattern; + +import java.util.concurrent.atomic.AtomicInteger; + +public class AppTestUtils { + + public static void invokeMakeRequest( + int clientId, RateLimiter limiter, String service, String operation) { + App.makeRequest(clientId, limiter, service, operation); + } + + public static void resetCounters() { + App.resetCountersForTesting(); + } + + public static AtomicInteger getSuccessfulRequests() { + return App.successfulRequests; + } + + public static AtomicInteger getThrottledRequests() { + return App.throttledRequests; + } + + public static AtomicInteger getFailedRequests() { + return App.failedRequests; + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ConcurrencyTests.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ConcurrencyTests.java new file mode 100644 index 000000000000..cba26d9ab7d0 --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ConcurrencyTests.java @@ -0,0 +1,77 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class ConcurrencyTests { + @Test + void tokenBucketShouldHandleConcurrentRequests() throws Exception { + int threadCount = 10; + int requestLimit = 5; + RateLimiter limiter = new TokenBucketRateLimiter(requestLimit, requestLimit); + ExecutorService executor = Executors.newFixedThreadPool(threadCount); + try { + CountDownLatch latch = new CountDownLatch(threadCount); + + AtomicInteger successCount = new AtomicInteger(); + AtomicInteger failureCount = new AtomicInteger(); + + for (int i = 0; i < threadCount; i++) { + executor.submit( + () -> { + try { + limiter.check("test", "op"); + successCount.incrementAndGet(); + } catch (RateLimitException e) { + failureCount.incrementAndGet(); + } + latch.countDown(); + }); + } + + latch.await(); + assertEquals(requestLimit, successCount.get()); + assertEquals(threadCount - requestLimit, failureCount.get()); + } finally { + executor.shutdown(); + } + } + + @Test + void adaptiveLimiterShouldAdjustUnderLoad() throws Exception { + AdaptiveRateLimiter limiter = new AdaptiveRateLimiter(10, 20, 100, TimeUnit.MILLISECONDS); + ExecutorService executor = Executors.newFixedThreadPool(20); + try { + // Flood with requests to trigger throttling + for (int i = 0; i < 30; i++) { + executor.submit( + () -> { + try { + limiter.check("test", "op"); + } catch (RateLimitException ignored) { + } + }); + } + + Thread.sleep(150); // Wait for adjustment + + // Verify new limit is in effect + int allowed = 0; + for (int i = 0; i < 20; i++) { + try { + limiter.check("test", "op"); + allowed++; + } catch (RateLimitException ignored) { + } + } + + assertTrue(allowed > 5 && allowed < 15); // Should be between initial and max + } finally { + executor.shutdown(); + limiter.shutdown(); + } + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ExceptionTests.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ExceptionTests.java new file mode 100644 index 000000000000..a7b037fbe73f --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/ExceptionTests.java @@ -0,0 +1,28 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class ExceptionTests { + @Test + void rateLimitExceptionShouldContainRetryInfo() { + RateLimitException exception = new RateLimitException("Test", 1000); + assertEquals(1000, exception.getRetryAfterMillis()); + assertEquals("Test", exception.getMessage()); + } + + @Test + void throttlingExceptionShouldContainServiceInfo() { + ThrottlingException exception = new ThrottlingException("dynamodb", "Query", 500); + assertEquals("dynamodb", exception.getServiceName()); + assertEquals("ThrottlingException", exception.getErrorCode()); + } + + @Test + void serviceUnavailableExceptionShouldContainRetryInfo() { + ServiceUnavailableException exception = new ServiceUnavailableException("s3", 2000); + assertEquals("s3", exception.getServiceName()); + assertEquals(2000, exception.getRetryAfterMillis()); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequestTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequestTest.java new file mode 100644 index 000000000000..d0c3197289cd --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FindCustomerRequestTest.java @@ -0,0 +1,62 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class FindCustomerRequestTest implements RateLimitOperationTest { + + @Override + public RateLimitOperation createOperation(RateLimiter limiter) { + return new FindCustomerRequest("123", limiter); + } + + @Test + void shouldExecuteWhenUnderRateLimit() throws Exception { + RateLimiter limiter = new TokenBucketRateLimiter(10, 10); + RateLimitOperation request = createOperation(limiter); + + String result = request.execute(); + assertEquals("Customer-123", result); + } + + @Test + void shouldThrowWhenRateLimitExceeded() { + RateLimiter limiter = new TokenBucketRateLimiter(0, 0); // Always throttled + RateLimitOperation request = createOperation(limiter); + + assertThrows(RateLimitException.class, request::execute); + } + + @Test + void shouldReturnCorrectServiceAndOperationNames() { + RateLimiter limiter = new TokenBucketRateLimiter(10, 10); + FindCustomerRequest request = new FindCustomerRequest("123", limiter); + + assertEquals("CustomerService", request.getServiceName()); + assertEquals("FindCustomer", request.getOperationName()); + } + + // Reuse helper logic from the interface for coverage + @Test + void shouldExecuteUsingDefaultHelper() throws Exception { + RateLimiter limiter = new TokenBucketRateLimiter(5, 5); + shouldExecuteWhenUnderLimit(createOperation(limiter)); + } + + @Test + void shouldThrowServiceUnavailableOnInterruptedException() { + RateLimiter noOpLimiter = (service, operation) -> {}; // no throttling + + FindCustomerRequest request = + new FindCustomerRequest("999", noOpLimiter) { + @Override + public String execute() throws RateLimitException { + Thread.currentThread().interrupt(); // Simulate thread interruption + return super.execute(); // Should throw ServiceUnavailableException + } + }; + + assertThrows(ServiceUnavailableException.class, request::execute); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiterTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiterTest.java new file mode 100644 index 000000000000..656185b7e68e --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/FixedWindowRateLimiterTest.java @@ -0,0 +1,40 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class FixedWindowRateLimiterTest extends RateLimiterTest { + @Override + protected RateLimiter createRateLimiter(int limit, long windowMillis) { + return new FixedWindowRateLimiter(limit, windowMillis / 1000); + } + + @Test + void shouldResetCounterAfterWindow() throws Exception { + FixedWindowRateLimiter limiter = + new FixedWindowRateLimiter(1, 1); // 1 request per 1 second window + + // First request should pass + limiter.check("test", "op"); + + // Second request in same window should be throttled + assertThrows(RateLimitException.class, () -> limiter.check("test", "op")); + + // Wait a bit more than 1 second to ensure window resets + TimeUnit.MILLISECONDS.sleep(1100); + + // After window reset, this should pass again + limiter.check("test", "op"); + } + + @Test + void shouldNotAllowMoreThanLimitInWindow() throws Exception { + FixedWindowRateLimiter limiter = new FixedWindowRateLimiter(3, 1); + for (int i = 0; i < 3; i++) { + limiter.check("test", "op"); + } + assertThrows(RateLimitException.class, () -> limiter.check("test", "op")); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimitOperationTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimitOperationTest.java new file mode 100644 index 000000000000..d4922bdfc073 --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimitOperationTest.java @@ -0,0 +1,22 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +interface RateLimitOperationTest { + + RateLimitOperation createOperation(RateLimiter limiter); + + @Test + default void shouldThrowWhenRateLimited() { + RateLimiter limiter = new TokenBucketRateLimiter(0, 0); // Always throttled + RateLimitOperation operation = createOperation(limiter); + assertThrows(RateLimitException.class, operation::execute); + } + + // ✅ No @Test here, just a helper method + default void shouldExecuteWhenUnderLimit(RateLimitOperation operation) throws Exception { + assertNotNull(operation.execute()); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimiterTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimiterTest.java new file mode 100644 index 000000000000..7f1e6b4a2806 --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/RateLimiterTest.java @@ -0,0 +1,25 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +public abstract class RateLimiterTest { + protected abstract RateLimiter createRateLimiter(int limit, long windowMillis); + + @Test + void shouldAllowRequestsWithinLimit() throws Exception { + RateLimiter limiter = createRateLimiter(5, 1000); + for (int i = 0; i < 5; i++) { + limiter.check("test", "op"); + } + } + + @Test + void shouldThrowWhenLimitExceeded() throws Exception { + RateLimiter limiter = createRateLimiter(2, 1000); + limiter.check("test", "op"); + limiter.check("test", "op"); + assertThrows(RateLimitException.class, () -> limiter.check("test", "op")); + } +} diff --git a/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiterTest.java b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiterTest.java new file mode 100644 index 000000000000..5696299512fb --- /dev/null +++ b/rate-limiting-pattern/src/test/java/com/iluwatar/rate/limiting/pattern/TokenBucketRateLimiterTest.java @@ -0,0 +1,39 @@ +package com.iluwatar.rate.limiting.pattern; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class TokenBucketRateLimiterTest extends RateLimiterTest { + @Override + protected RateLimiter createRateLimiter(int limit, long windowMillis) { + return new TokenBucketRateLimiter(limit, (int) (limit * 1000 / windowMillis)); + } + + @Test + void shouldAllowBurstRequests() throws Exception { + TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(10, 5); + for (int i = 0; i < 10; i++) { + limiter.check("test", "op"); + } + } + + @Test + void shouldRefillTokensAfterTime() throws Exception { + TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(1, 1); + limiter.check("test", "op"); + assertThrows(RateLimitException.class, () -> limiter.check("test", "op")); + + TimeUnit.SECONDS.sleep(1); + limiter.check("test", "op"); + } + + @Test + void shouldHandleMultipleServicesSeparately() throws Exception { + TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(1, 1); + limiter.check("service1", "op"); + limiter.check("service2", "op"); + assertThrows(RateLimitException.class, () -> limiter.check("service1", "op")); + } +} diff --git a/rule-engine/README.md b/rule-engine/README.md new file mode 100644 index 000000000000..53106a71d524 --- /dev/null +++ b/rule-engine/README.md @@ -0,0 +1,199 @@ +--- +title: "Rule Engine Pattern in Java: Replacing Tangled Conditionals with Composable Rules" +shortTitle: Rule Engine +description: "Learn the Rule Engine design pattern in Java. Encapsulate each business rule as an independent object and let an engine evaluate and execute them against a shared context, replacing large nested if/else blocks with small, testable, composable rules." +category: Behavioral +language: en +tag: + - Business + - Decoupling + - Domain + - Encapsulation + - Extensibility +--- + +## Intent of Rule Engine Design Pattern + +Encapsulate each business rule as an independent, self-contained object and let an engine evaluate and execute a collection of those rules against a shared context, so that decision logic can grow and change without rewriting a large nested conditional block. + +## Detailed Explanation of Rule Engine Pattern with Real-World Examples + +Real-world example + +> A bank decides whether to approve a loan by checking several independent criteria: the applicant must be old enough, earn enough, and have a good enough credit score. Instead of hard-coding one enormous condition, the bank keeps each criterion as a separate policy on a checklist. A clerk walks the whole checklist for every application, ticks off the criteria that pass, and writes down the ones that fail. Adding a new criterion means adding a line to the checklist, not rewriting the whole approval procedure. + +In plain words + +> The Rule Engine pattern turns each branch of a giant `if/else` into its own object and hands a collection of them to an engine that runs them all against the same input, collecting which passed and which failed. + +## Programmatic Example of Rule Engine Pattern in Java + +Each rule separates the **decision** (`evaluate`) from the **action** (`execute`). `evaluate` reports whether a rule's condition holds; `execute` performs the side effect associated with a satisfied rule. + +```java +public interface Rule { + + String name(); + + boolean evaluate(T context); + + void execute(T context); +} +``` + +The context is an immutable value object that carries the data the rules inspect. + +```java +public record LoanApplication( + int age, double monthlyIncome, double loanAmount, int creditScore) {} +``` + +Concrete rules encapsulate one criterion each. New criteria are added by writing new classes — the engine never changes. + +```java +public class MinimumAgeRule implements Rule { + + private final int minimumAge; + + public MinimumAgeRule(int minimumAge) { + this.minimumAge = minimumAge; + } + + @Override + public String name() { + return "MinimumAgeRule"; + } + + @Override + public boolean evaluate(LoanApplication context) { + return context.age() >= minimumAge; + } + + @Override + public void execute(LoanApplication context) { + LOGGER.info("Applicant age {} meets the minimum age of {}.", context.age(), minimumAge); + } +} +``` + +The engine holds a defensively copied, immutable list of rules. It evaluates every rule in insertion order, executes the ones that pass, and reports the combined outcome. It never stops at the first failure, so a single run reports *all* the reasons an application was rejected. + +```java +public class RuleEngine { + + private final List> rules; + + public RuleEngine(List> rules) { + this.rules = List.copyOf(rules); + } + + public RuleEngineResult run(T context) { + Objects.requireNonNull(context, "context must not be null"); + List passed = new ArrayList<>(); + List failed = new ArrayList<>(); + for (Rule rule : rules) { + if (rule.evaluate(context)) { + rule.execute(context); + passed.add(rule.name()); + } else { + failed.add(rule.name()); + } + } + return new RuleEngineResult(failed.isEmpty(), passed, failed); + } +} +``` + +The result is an immutable value object describing the run. + +```java +public record RuleEngineResult( + boolean approved, List passedRules, List failedRules) { + + public RuleEngineResult { + passedRules = List.copyOf(passedRules); + failedRules = List.copyOf(failedRules); + } +} +``` + +Putting it together, the `App` builds an engine and runs two applications through it. + +```java +var engine = + new RuleEngine<>( + List.of( + new MinimumAgeRule(18), + new MinimumIncomeRule(2000.0), + new CreditScoreRule(650))); + +engine.run(new LoanApplication(30, 3500.0, 15000.0, 720)); // approved +engine.run(new LoanApplication(17, 1500.0, 15000.0, 720)); // rejected: age and income +``` + +Program output: + +``` +Applicant age 30 meets the minimum age of 18. +Applicant income 3500.0 meets the minimum income of 2000.0. +Applicant credit score 720 meets the minimum score of 650. +Loan approved. Passed rules: [MinimumAgeRule, MinimumIncomeRule, CreditScoreRule] +Applicant credit score 720 meets the minimum score of 650. +Loan rejected. Failed rules: [MinimumAgeRule, MinimumIncomeRule] +``` + +### Behavioral decisions + +The example commits to the following semantics, each covered by tests: + +* `evaluate` returning `true` means the rule **passes** (its condition is satisfied); a passing rule then has its `execute` action run. +* The engine evaluates **every** rule; it does not stop after the first failure, so all rejection reasons are reported. +* Outcomes are reported as an immutable `RuleEngineResult` carrying the overall `approved` flag plus the names of the passed and failed rules. +* Rules execute in **insertion order**. +* A `null` context passed to `run` throws `NullPointerException`; a `null` rule collection or a `null` rule element is rejected on construction. +* An engine with **no rules** approves vacuously (nothing failed). + +## Class diagram + +See [rule-engine.urm.puml](./etc/rule-engine.urm.puml) for the PlantUML class diagram. + +## When to Use the Rule Engine Pattern in Java + +* Decision logic is a growing set of independent conditions that would otherwise become a large, hard-to-read nested `if/else`. +* Rules must be added, removed, or reordered without touching the code that coordinates them. +* You need to report *all* failing conditions, not just the first one. +* Business rules deserve to be unit tested in isolation. + +## Real-World Applications of Rule Engine Pattern in Java + +* Loan, insurance, and credit approval workflows. +* Validation frameworks such as Bean Validation, where each constraint is an independent rule. +* Fraud detection and risk scoring, where many independent checks contribute to one decision. +* Pricing, discount, and promotion eligibility engines. + +## Benefits and Trade-offs of Rule Engine Pattern + +Benefits + +* Encapsulation: each rule owns one criterion. +* Extensibility: new rules are new classes; the engine is closed for modification. +* Testability: rules and the engine can be tested independently. +* Transparency: the result lists every passed and failed rule. + +Trade-offs + +* Debugging a decision means tracing several small objects instead of reading one block. +* Rule ordering and conflicts must be managed deliberately when rules are not independent. +* Over-abstracting trivial logic into a rule engine adds indirection that a simple `if` would not. + +## Related Java Design Patterns + +* [Specification](../specification): combines boolean criteria that an object must satisfy; a Rule Engine orchestrates and executes such criteria. +* [Chain of Responsibility](../chain-of-responsibility): passes a request along handlers; a Rule Engine instead runs every rule against one context. +* [Strategy](../strategy): each rule is effectively a pluggable strategy for one decision. +* [Command](../command): a rule's `execute` action resembles an encapsulated command. + +## References and Credits + +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420) (Martin Fowler) +* [Should I use a Rules Engine? (Martin Fowler)](https://martinfowler.com/bliki/RulesEngine.html) diff --git a/rule-engine/etc/rule-engine.urm.puml b/rule-engine/etc/rule-engine.urm.puml new file mode 100644 index 000000000000..c560f7862485 --- /dev/null +++ b/rule-engine/etc/rule-engine.urm.puml @@ -0,0 +1,61 @@ +@startuml +package com.iluwatar.ruleengine { + interface Rule { + + name() : String {abstract} + + evaluate(context : T) : boolean {abstract} + + execute(context : T) : void {abstract} + } + class RuleEngine { + - rules : List> + + RuleEngine(rules : List>) + + run(context : T) : RuleEngineResult + + rules() : List> + } + class RuleEngineResult { + + RuleEngineResult(approved : boolean, passedRules : List, failedRules : List) + + approved() : boolean + + passedRules() : List + + failedRules() : List + } + class LoanApplication { + + LoanApplication(age : int, monthlyIncome : double, loanAmount : double, creditScore : int) + + age() : int + + monthlyIncome() : double + + loanAmount() : double + + creditScore() : int + } + class MinimumAgeRule { + - minimumAge : int + + MinimumAgeRule(minimumAge : int) + + name() : String + + evaluate(context : LoanApplication) : boolean + + execute(context : LoanApplication) : void + } + class MinimumIncomeRule { + - minimumIncome : double + + MinimumIncomeRule(minimumIncome : double) + + name() : String + + evaluate(context : LoanApplication) : boolean + + execute(context : LoanApplication) : void + } + class CreditScoreRule { + - minimumScore : int + + CreditScoreRule(minimumScore : int) + + name() : String + + evaluate(context : LoanApplication) : boolean + + execute(context : LoanApplication) : void + } + class App { + + App() + + main(args : String[]) : void + } +} +RuleEngine --> "*" Rule +RuleEngine ..> RuleEngineResult +MinimumAgeRule ..|> Rule +MinimumIncomeRule ..|> Rule +CreditScoreRule ..|> Rule +MinimumAgeRule ..> LoanApplication +MinimumIncomeRule ..> LoanApplication +CreditScoreRule ..> LoanApplication +@enduml diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml new file mode 100644 index 000000000000..29738d783a99 --- /dev/null +++ b/rule-engine/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + rule-engine + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.ruleengine.App + + + + + + + + + diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/App.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/App.java new file mode 100644 index 000000000000..78a51f152b84 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/App.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import java.util.List; +import lombok.extern.slf4j.Slf4j; + +/** + * The Rule Engine pattern encapsulates each business rule as an independent object and lets a + * {@link RuleEngine} evaluate a collection of them against a shared context. This replaces large, + * tangled conditional blocks with small, testable rules that can be added or removed without + * touching the orchestration logic. + * + *

This demo builds a loan approval engine from three rules and runs two applications through it: + * one that satisfies every rule and one that fails two of them. Because the engine evaluates every + * rule rather than stopping at the first failure, the result reports all the reasons an application + * was rejected. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var engine = + new RuleEngine<>( + List.of( + new MinimumAgeRule(18), new MinimumIncomeRule(2000.0), new CreditScoreRule(650))); + + var approved = new LoanApplication(30, 3500.0, 15000.0, 720); + var rejected = new LoanApplication(17, 1500.0, 15000.0, 720); + + report(engine.run(approved)); + report(engine.run(rejected)); + } + + private static void report(RuleEngineResult result) { + if (result.approved()) { + LOGGER.info("Loan approved. Passed rules: {}", result.passedRules()); + } else { + LOGGER.info("Loan rejected. Failed rules: {}", result.failedRules()); + } + } +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/CreditScoreRule.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/CreditScoreRule.java new file mode 100644 index 000000000000..28cd59baadbb --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/CreditScoreRule.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import lombok.extern.slf4j.Slf4j; + +/** Passes when the applicant's credit score reaches the required minimum. */ +@Slf4j +public class CreditScoreRule implements Rule { + + private final int minimumScore; + + /** + * Creates the rule. + * + * @param minimumScore the inclusive minimum credit score the applicant must have + */ + public CreditScoreRule(int minimumScore) { + this.minimumScore = minimumScore; + } + + @Override + public String name() { + return "CreditScoreRule"; + } + + @Override + public boolean evaluate(LoanApplication context) { + return context.creditScore() >= minimumScore; + } + + @Override + public void execute(LoanApplication context) { + LOGGER.info( + "Applicant credit score {} meets the minimum score of {}.", + context.creditScore(), + minimumScore); + } +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/LoanApplication.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/LoanApplication.java new file mode 100644 index 000000000000..0eda1f17d3e2 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/LoanApplication.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +/** + * Immutable context that the loan {@link Rule rules} are evaluated against. + * + *

Using a record keeps the domain object immutable and free of behaviour, so the business logic + * lives entirely inside the rules rather than being scattered across the data it operates on. + * + * @param age applicant age in years + * @param monthlyIncome applicant net monthly income + * @param loanAmount requested loan amount + * @param creditScore applicant credit score + */ +public record LoanApplication(int age, double monthlyIncome, double loanAmount, int creditScore) {} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumAgeRule.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumAgeRule.java new file mode 100644 index 000000000000..71532dde4707 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumAgeRule.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import lombok.extern.slf4j.Slf4j; + +/** Passes when the applicant is at least the required minimum age. */ +@Slf4j +public class MinimumAgeRule implements Rule { + + private final int minimumAge; + + /** + * Creates the rule. + * + * @param minimumAge the inclusive minimum age the applicant must reach + */ + public MinimumAgeRule(int minimumAge) { + this.minimumAge = minimumAge; + } + + @Override + public String name() { + return "MinimumAgeRule"; + } + + @Override + public boolean evaluate(LoanApplication context) { + return context.age() >= minimumAge; + } + + @Override + public void execute(LoanApplication context) { + LOGGER.info("Applicant age {} meets the minimum age of {}.", context.age(), minimumAge); + } +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumIncomeRule.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumIncomeRule.java new file mode 100644 index 000000000000..fc6d40964fc9 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/MinimumIncomeRule.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import lombok.extern.slf4j.Slf4j; + +/** Passes when the applicant's monthly income reaches the required minimum. */ +@Slf4j +public class MinimumIncomeRule implements Rule { + + private final double minimumIncome; + + /** + * Creates the rule. + * + * @param minimumIncome the inclusive minimum monthly income the applicant must earn + */ + public MinimumIncomeRule(double minimumIncome) { + this.minimumIncome = minimumIncome; + } + + @Override + public String name() { + return "MinimumIncomeRule"; + } + + @Override + public boolean evaluate(LoanApplication context) { + return context.monthlyIncome() >= minimumIncome; + } + + @Override + public void execute(LoanApplication context) { + LOGGER.info( + "Applicant income {} meets the minimum income of {}.", + context.monthlyIncome(), + minimumIncome); + } +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/Rule.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/Rule.java new file mode 100644 index 000000000000..723b31e73b52 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/Rule.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +/** + * Abstraction for a single, self-contained business rule. + * + *

A rule separates the decision ({@link #evaluate(Object)}) from the action ({@link + * #execute(Object)}). {@code evaluate} inspects the context and reports whether the rule's + * condition is satisfied, while {@code execute} performs the side effect associated with a + * satisfied rule. Keeping the two responsibilities apart lets a {@link RuleEngine} decide which + * rules apply before running any action, and lets new rules be added without touching the engine. + * + * @param type of the context the rule is evaluated against + */ +public interface Rule { + + /** + * Returns a human readable identifier used when reporting rule outcomes. + * + * @return the rule name + */ + String name(); + + /** + * Evaluates the rule against the given context. + * + * @param context the immutable input the rule inspects + * @return {@code true} when the rule's condition is satisfied, {@code false} otherwise + */ + boolean evaluate(T context); + + /** + * Performs the action associated with a satisfied rule. + * + * @param context the immutable input the action operates on + */ + void execute(T context); +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngine.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngine.java new file mode 100644 index 000000000000..85a8db9d74b5 --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngine.java @@ -0,0 +1,91 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Orchestrates a fixed collection of {@link Rule rules} against a context. + * + *

The engine owns the coordination logic that would otherwise live in a large nested {@code + * if}/{@code else} block: it evaluates every rule in insertion order, runs the action of each rule + * whose condition is satisfied, and reports the combined outcome as a {@link RuleEngineResult}. + * Evaluation never stops early, so a single run reports all failing rules rather than only + * the first, which is what makes rejection reasons useful. + * + *

The rule collection is copied defensively on construction, making the engine immutable and + * safe to reuse across many contexts. New behaviour is added by supplying additional {@link Rule} + * implementations; the engine itself never changes. + * + * @param type of the context the rules are evaluated against + */ +public class RuleEngine { + + private final List> rules; + + /** + * Creates an engine for the given rules. + * + * @param rules the rules to evaluate, applied in iteration order; must not be {@code null} or + * contain {@code null} elements + * @throws NullPointerException if {@code rules} is {@code null} or contains a {@code null} rule + */ + public RuleEngine(List> rules) { + this.rules = List.copyOf(rules); + } + + /** + * Evaluates every rule against the context and executes the rules that pass. + * + * @param context the context inspected by the rules; must not be {@code null} + * @return the combined outcome of the run + * @throws NullPointerException if {@code context} is {@code null} + */ + public RuleEngineResult run(T context) { + Objects.requireNonNull(context, "context must not be null"); + List passed = new ArrayList<>(); + List failed = new ArrayList<>(); + for (Rule rule : rules) { + if (rule.evaluate(context)) { + rule.execute(context); + passed.add(rule.name()); + } else { + failed.add(rule.name()); + } + } + return new RuleEngineResult(failed.isEmpty(), passed, failed); + } + + /** + * Returns the rules held by this engine. + * + * @return an immutable view of the configured rules + */ + public List> rules() { + return rules; + } +} diff --git a/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngineResult.java b/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngineResult.java new file mode 100644 index 000000000000..868e3986602f --- /dev/null +++ b/rule-engine/src/main/java/com/iluwatar/ruleengine/RuleEngineResult.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import java.util.List; + +/** + * Immutable outcome produced by {@link RuleEngine#run(Object)}. + * + *

The result reports whether every rule passed and, for transparency, the names of the rules + * that passed and failed in the order they were evaluated. The lists are copied on construction so + * the result cannot be mutated by callers or by later changes to the source collections. + * + * @param approved {@code true} when no rule failed + * @param passedRules names of the rules whose condition was satisfied, in evaluation order + * @param failedRules names of the rules whose condition was not satisfied, in evaluation order + */ +public record RuleEngineResult( + boolean approved, List passedRules, List failedRules) { + + /** Defensive copy keeps the value object immutable. */ + public RuleEngineResult { + passedRules = List.copyOf(passedRules); + failedRules = List.copyOf(failedRules); + } +} diff --git a/rule-engine/src/test/java/com/iluwatar/ruleengine/AppTest.java b/rule-engine/src/test/java/com/iluwatar/ruleengine/AppTest.java new file mode 100644 index 000000000000..a8746fa0c387 --- /dev/null +++ b/rule-engine/src/test/java/com/iluwatar/ruleengine/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldLaunchApp() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/rule-engine/src/test/java/com/iluwatar/ruleengine/LoanRulesTest.java b/rule-engine/src/test/java/com/iluwatar/ruleengine/LoanRulesTest.java new file mode 100644 index 000000000000..80ba160b1ffa --- /dev/null +++ b/rule-engine/src/test/java/com/iluwatar/ruleengine/LoanRulesTest.java @@ -0,0 +1,81 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Verifies each concrete rule independently at, above and below its threshold. */ +class LoanRulesTest { + + private static LoanApplication applicant(int age, double income, int score) { + return new LoanApplication(age, income, 10000.0, score); + } + + @Test + void minimumAgeRulePassesAtOrAboveThreshold() { + var rule = new MinimumAgeRule(18); + assertTrue(rule.evaluate(applicant(18, 3000.0, 700))); + assertTrue(rule.evaluate(applicant(40, 3000.0, 700))); + assertDoesNotThrow(() -> rule.execute(applicant(18, 3000.0, 700))); + } + + @Test + void minimumAgeRuleFailsBelowThreshold() { + var rule = new MinimumAgeRule(18); + assertFalse(rule.evaluate(applicant(17, 3000.0, 700))); + } + + @Test + void minimumIncomeRulePassesAtOrAboveThreshold() { + var rule = new MinimumIncomeRule(2000.0); + assertTrue(rule.evaluate(applicant(30, 2000.0, 700))); + assertTrue(rule.evaluate(applicant(30, 5000.0, 700))); + assertDoesNotThrow(() -> rule.execute(applicant(30, 2000.0, 700))); + } + + @Test + void minimumIncomeRuleFailsBelowThreshold() { + var rule = new MinimumIncomeRule(2000.0); + assertFalse(rule.evaluate(applicant(30, 1999.99, 700))); + } + + @Test + void creditScoreRulePassesAtOrAboveThreshold() { + var rule = new CreditScoreRule(650); + assertTrue(rule.evaluate(applicant(30, 3000.0, 650))); + assertTrue(rule.evaluate(applicant(30, 3000.0, 800))); + assertDoesNotThrow(() -> rule.execute(applicant(30, 3000.0, 650))); + } + + @Test + void creditScoreRuleFailsBelowThreshold() { + var rule = new CreditScoreRule(650); + assertFalse(rule.evaluate(applicant(30, 3000.0, 649))); + } +} diff --git a/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineResultTest.java b/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineResultTest.java new file mode 100644 index 000000000000..0bae5dc12c0d --- /dev/null +++ b/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineResultTest.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class RuleEngineResultTest { + + @Test + void copiesListsDefensivelyOnConstruction() { + var passed = new ArrayList<>(List.of("MinimumAgeRule")); + var failed = new ArrayList<>(List.of("CreditScoreRule")); + var result = new RuleEngineResult(false, passed, failed); + + passed.add("MinimumIncomeRule"); // mutate the sources after construction + failed.clear(); + + assertEquals(List.of("MinimumAgeRule"), result.passedRules()); + assertEquals(List.of("CreditScoreRule"), result.failedRules()); + } + + @Test + void exposedListsAreUnmodifiable() { + var result = new RuleEngineResult(true, List.of("MinimumAgeRule"), List.of()); + assertThrows(UnsupportedOperationException.class, () -> result.passedRules().add("x")); + assertThrows(UnsupportedOperationException.class, () -> result.failedRules().add("x")); + } +} diff --git a/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineTest.java b/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineTest.java new file mode 100644 index 000000000000..fd8f89943ac9 --- /dev/null +++ b/rule-engine/src/test/java/com/iluwatar/ruleengine/RuleEngineTest.java @@ -0,0 +1,122 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.ruleengine; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class RuleEngineTest { + + private static RuleEngine loanEngine() { + return new RuleEngine<>( + List.of(new MinimumAgeRule(18), new MinimumIncomeRule(2000.0), new CreditScoreRule(650))); + } + + @Test + void approvesWhenEveryRulePasses() { + var result = loanEngine().run(new LoanApplication(30, 3000.0, 10000.0, 700)); + assertTrue(result.approved()); + assertEquals( + List.of("MinimumAgeRule", "MinimumIncomeRule", "CreditScoreRule"), result.passedRules()); + assertTrue(result.failedRules().isEmpty()); + } + + @Test + void rejectsWhenASingleRuleFails() { + var result = loanEngine().run(new LoanApplication(30, 3000.0, 10000.0, 600)); + assertFalse(result.approved()); + assertEquals(List.of("CreditScoreRule"), result.failedRules()); + assertEquals(List.of("MinimumAgeRule", "MinimumIncomeRule"), result.passedRules()); + } + + @Test + void reportsEveryFailingRuleWithoutStoppingEarly() { + var result = loanEngine().run(new LoanApplication(16, 500.0, 10000.0, 400)); + assertFalse(result.approved()); + assertEquals( + List.of("MinimumAgeRule", "MinimumIncomeRule", "CreditScoreRule"), result.failedRules()); + assertTrue(result.passedRules().isEmpty()); + } + + @Test + void evaluatesRulesInInsertionOrder() { + var engine = + new RuleEngine<>( + List.of( + new CreditScoreRule(650), new MinimumAgeRule(18), new MinimumIncomeRule(2000.0))); + var result = engine.run(new LoanApplication(16, 500.0, 10000.0, 400)); + assertEquals( + List.of("CreditScoreRule", "MinimumAgeRule", "MinimumIncomeRule"), result.failedRules()); + } + + @Test + void emptyEngineApprovesVacuously() { + var result = + new RuleEngine(List.of()).run(new LoanApplication(1, 1.0, 1.0, 1)); + assertTrue(result.approved()); + assertTrue(result.passedRules().isEmpty()); + assertTrue(result.failedRules().isEmpty()); + } + + @Test + void rejectsNullContext() { + assertThrows(NullPointerException.class, () -> loanEngine().run(null)); + } + + @Test + void rejectsNullRuleCollection() { + assertThrows(NullPointerException.class, () -> new RuleEngine(null)); + } + + @Test + void rejectsNullRuleElement() { + var rules = new ArrayList>(); + rules.add(null); + assertThrows(NullPointerException.class, () -> new RuleEngine<>(rules)); + } + + @Test + void copiesRulesDefensivelyOnConstruction() { + var rules = new ArrayList>(); + rules.add(new MinimumAgeRule(18)); + var engine = new RuleEngine<>(rules); + + rules.add(new CreditScoreRule(650)); // mutate the source after construction + assertEquals(1, engine.rules().size()); + } + + @Test + void exposedRulesAreUnmodifiable() { + var engine = loanEngine(); + assertThrows( + UnsupportedOperationException.class, () -> engine.rules().add(new MinimumAgeRule(21))); + } +} diff --git a/saga/README.md b/saga/README.md index d715f026af67..b559d3daddf3 100644 --- a/saga/README.md +++ b/saga/README.md @@ -193,7 +193,7 @@ Trade-offs: ## Related Java Design Patterns * [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Used to capture state changes as a sequence of events, which can complement the Saga pattern by providing a history of state changes. -* [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/cqrs/): Can be used in conjunction with the Saga pattern to separate command and query responsibilities, improving scalability and fault tolerance. +* [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/): Can be used in conjunction with the Saga pattern to separate command and query responsibilities, improving scalability and fault tolerance. ## References and Credits diff --git a/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java b/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java index f27b71213a09..cb647dcb1ec4 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java @@ -67,7 +67,12 @@ public class SingleTableInheritance implements CommandLineRunner { * @param args program runtime arguments */ public static void main(String[] args) { - SpringApplication.run(SingleTableInheritance.class, args); + var context = SpringApplication.run(SingleTableInheritance.class, args); + if (args.length > 0 && "test".equals(args[0])) { + // Close the context immediately during tests to prevent Tomcat/background threads from + // hanging the JVM + context.close(); + } } /** diff --git a/single-table-inheritance/src/test/java/com/iluwatar/SingleTableInheritanceTest.java b/single-table-inheritance/src/test/java/com/iluwatar/SingleTableInheritanceTest.java new file mode 100644 index 000000000000..8ba4f275a0dd --- /dev/null +++ b/single-table-inheritance/src/test/java/com/iluwatar/SingleTableInheritanceTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that SingleTableInheritance example application runs without errors. */ +class SingleTableInheritanceTest { + + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> SingleTableInheritance.main(new String[] {"test"})); + } +} diff --git a/single-table-inheritance/src/test/java/com/iluwatar/service/VehicleServiceTest.java b/single-table-inheritance/src/test/java/com/iluwatar/service/VehicleServiceTest.java new file mode 100644 index 000000000000..2bff4b354627 --- /dev/null +++ b/single-table-inheritance/src/test/java/com/iluwatar/service/VehicleServiceTest.java @@ -0,0 +1,161 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.entity.Car; +import com.iluwatar.entity.Freighter; +import com.iluwatar.entity.Train; +import com.iluwatar.entity.Truck; +import com.iluwatar.entity.Vehicle; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +/** + * Tests for {@link VehicleService} exercising CRUD operations and verifying that all concrete + * Vehicle subtypes are persisted and retrieved correctly via the single-table inheritance strategy. + */ +@SpringBootTest +class VehicleServiceTest { + + private static final double DELTA = 0.001; + + @Autowired private VehicleService vehicleService; + + private Vehicle savedCar; + private Vehicle savedTruck; + private Vehicle savedTrain; + private Vehicle savedFreighter; + + @BeforeEach + void setUp() { + savedCar = vehicleService.saveVehicle(new Car("Tesla", "Model S", 4, 825)); + savedTruck = vehicleService.saveVehicle(new Truck("Ford", "F-150", 3325, 14000)); + savedTrain = vehicleService.saveVehicle(new Train("Siemens", "Velaro", 600, 8)); + savedFreighter = vehicleService.saveVehicle(new Freighter("Boeing", "747F", 100000, 8130)); + } + + @AfterEach + void tearDown() { + if (savedCar != null) vehicleService.deleteVehicle(savedCar); + if (savedTruck != null) vehicleService.deleteVehicle(savedTruck); + if (savedTrain != null) vehicleService.deleteVehicle(savedTrain); + if (savedFreighter != null) vehicleService.deleteVehicle(savedFreighter); + } + + @Test + void saveVehicle_shouldPersistCarWithCorrectType() { + assertTrue(savedCar.getVehicleId() > 0); + assertInstanceOf(Car.class, savedCar); + assertEquals("Tesla", savedCar.getManufacturer()); + assertEquals("Model S", savedCar.getModel()); + assertEquals(825, ((Car) savedCar).getEngineCapacity()); + } + + @Test + void saveVehicle_shouldPersistTruckWithCorrectType() { + assertTrue(savedTruck.getVehicleId() > 0); + assertInstanceOf(Truck.class, savedTruck); + assertEquals(14000, ((Truck) savedTruck).getTowingCapacity()); + } + + @Test + void saveVehicle_shouldPersistTrainWithCorrectType() { + assertTrue(savedTrain.getVehicleId() > 0); + assertInstanceOf(Train.class, savedTrain); + assertEquals(8, ((Train) savedTrain).getNoOfCarriages()); + } + + @Test + void saveVehicle_shouldPersistFreighterWithCorrectType() { + assertTrue(savedFreighter.getVehicleId() > 0); + assertInstanceOf(Freighter.class, savedFreighter); + assertEquals(8130.0, ((Freighter) savedFreighter).getFlightLength(), DELTA); + } + + @Test + void getVehicle_shouldReturnCorrectVehicleById() { + Vehicle fetched = vehicleService.getVehicle(savedCar.getVehicleId()); + + assertNotNull(fetched); + assertInstanceOf(Car.class, fetched); + assertEquals(savedCar.getVehicleId(), fetched.getVehicleId()); + } + + @Test + void getVehicle_shouldReturnNullForNonexistentId() { + Vehicle result = vehicleService.getVehicle(Integer.MAX_VALUE); + assertNull(result); + } + + @Test + void getAllVehicles_shouldReturnAllSavedVehicles() { + List all = vehicleService.getAllVehicles(); + assertNotNull(all); + // At minimum the 4 vehicles saved in @BeforeEach must be present + assertTrue_containsId(all, savedCar.getVehicleId()); + assertTrue_containsId(all, savedTruck.getVehicleId()); + assertTrue_containsId(all, savedTrain.getVehicleId()); + assertTrue_containsId(all, savedFreighter.getVehicleId()); + } + + @Test + void updateVehicle_shouldPersistChanges() { + Car car = (Car) savedCar; + car.setModel("Model X"); + vehicleService.updateVehicle(car); + + Vehicle updated = vehicleService.getVehicle(car.getVehicleId()); + assertEquals("Model X", updated.getModel()); + } + + @Test + void deleteVehicle_shouldRemoveFromRepository() { + // Save a temporary vehicle and delete it + Vehicle tmp = vehicleService.saveVehicle(new Car("BMW", "M3", 4, 3000)); + int tmpId = tmp.getVehicleId(); + + vehicleService.deleteVehicle(tmp); + + assertNull(vehicleService.getVehicle(tmpId)); + } + + // Helper: assert that a specific vehicle id exists in the list + private void assertTrue_containsId(List vehicles, int id) { + boolean found = vehicles.stream().anyMatch(v -> v.getVehicleId() == id); + if (!found) { + throw new AssertionError("Expected vehicle with id=" + id + " in list but was not found."); + } + } +} diff --git a/subclass-sandbox/pom.xml b/subclass-sandbox/pom.xml index 9d21c7400f09..79aa0b63cbfd 100644 --- a/subclass-sandbox/pom.xml +++ b/subclass-sandbox/pom.xml @@ -34,8 +34,8 @@ 4.0.0 subclass-sandbox - 2.0.17 - 1.5.18 + 2.0.18 + 1.5.35 diff --git a/thread-pool-executor/README.md b/thread-pool-executor/README.md new file mode 100644 index 000000000000..fa1d5a2c8062 --- /dev/null +++ b/thread-pool-executor/README.md @@ -0,0 +1,200 @@ +--- +title: "Thread-Pool Executor Pattern in Java: Efficient Concurrent Task Management" +shortTitle: Thread-Pool Executor +description: "Learn the Thread-Pool Executor pattern in Java with practical examples, class +diagrams, and implementation details. Understand how to manage concurrent tasks efficiently, +improving resource utilization and application performance." +category: Concurrency +language: en +tag: + +- Performance +- Resource Management +- Concurrency +- Multithreading +- Scalability + +--- + +## Intent of Thread-Pool Executor Design Pattern + +The Thread-Pool Executor pattern maintains a pool of worker threads to execute tasks concurrently, +optimizing resource usage by reusing existing threads instead of creating new ones for each task. + +## Detailed Explanation of Thread-Pool Executor Pattern with Real-World Examples + +### Real-world example + +> Imagine a busy airport security checkpoint where instead of opening a new lane for each traveler, +> a fixed number of security lanes (threads) are open to process all passengers. Each security +> officer (thread) processes one passenger (task) at a time, and when finished, immediately calls the +> next passenger in line. During peak travel times, passengers wait in a queue, but the system is much +> more efficient than trying to open a new security lane for each individual traveler. The airport can +> handle fluctuating passenger traffic throughout the day with consistent staffing, optimizing both +> resource utilization and passenger throughput. + +### In plain words + +> Thread-Pool Executor keeps a set of reusable threads that process multiple tasks throughout their +> lifecycle, rather than creating a new thread for each task. + +### Wikipedia says + +> A thread pool is a software design pattern for achieving concurrency of execution in a computer +> program. Often also called a replicated workers or worker-crew model, a thread pool maintains +> multiple threads waiting for tasks to be allocated for concurrent execution by the supervising +> program. + +### Class diagram + +![Thread-pool-executor Class diagram](./etc/thread-pool-executor.urm.png) + +## Programmatic Example of Thread-Pool Executor Pattern in Java + +Imagine a hotel front desk. + +The number of employees (thread pool) is limited, but guests (tasks) keep arriving endlessly. + +The Thread-Pool Executor pattern efficiently handles a large number of requests by reusing a small +set of threads. + +```java +@Slf4j +public class HotelFrontDesk { + public static void main(String[] args) throws InterruptedException, ExecutionException { + // Hire 3 front desk employees (threads) + ExecutorService frontDesk = Executors.newFixedThreadPool(3); + + LOGGER.info("Hotel front desk operation started!"); + + // 7 regular guests checking in (Runnable) + for (int i = 1; i <= 7; i++) { + String guestName = "Guest-" + i; + frontDesk.submit(() -> { + String employeeName = Thread.currentThread().getName(); + LOGGER.info("{} is checking in {}...", employeeName, guestName); + try { + Thread.sleep(2000); // Simulate check-in time + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + LOGGER.info("{} has been successfully checked in!", guestName); + }); + } + + // 3 VIP guests checking in (Callable with result) + Callable vipGuest1 = createVipGuest("VIP-Guest-1"); + Callable vipGuest2 = createVipGuest("VIP-Guest-2"); + Callable vipGuest3 = createVipGuest("VIP-Guest-3"); + + Future vipResult1 = frontDesk.submit(vipGuest1); + Future vipResult2 = frontDesk.submit(vipGuest2); + Future vipResult3 = frontDesk.submit(vipGuest3); + + // Shutdown after submitting all tasks + frontDesk.shutdown(); + + if (frontDesk.awaitTermination(1, TimeUnit.HOURS)) { + // Print VIP guests' check-in results + LOGGER.info("VIP Check-in Results:"); + LOGGER.info(vipResult1.get()); + LOGGER.info(vipResult2.get()); + LOGGER.info(vipResult3.get()); + LOGGER.info("All guests have been successfully checked in. Front desk is now closed."); + } else { + LOGGER.info("Check-in timeout. Forcefully shutting down the front desk."); + } + } + + private static Callable createVipGuest(String vipGuestName) { + return () -> { + String employeeName = Thread.currentThread().getName(); + LOGGER.info("{} is checking in VIP guest {}...", employeeName, vipGuestName); + Thread.sleep(1000); // VIPs are faster to check in + return vipGuestName + " has been successfully checked in!"; + }; + } +} +``` + +Here's the console output: + +```markdown +Hotel front desk operation started! +pool-1-thread-3 is checking in Guest-3... +pool-1-thread-2 is checking in Guest-2... +pool-1-thread-1 is checking in Guest-1... +Guest-2 has been successfully checked in! +Guest-1 has been successfully checked in! +Guest-3 has been successfully checked in! +pool-1-thread-2 is checking in Guest-5... +pool-1-thread-3 is checking in Guest-4... +pool-1-thread-1 is checking in Guest-6... +Guest-5 has been successfully checked in! +pool-1-thread-2 is checking in Guest-7... +Guest-4 has been successfully checked in! +pool-1-thread-3 is checking in VIP guest VIP-Guest-1... +Guest-6 has been successfully checked in! +pool-1-thread-1 is checking in VIP guest VIP-Guest-2... +pool-1-thread-3 is checking in VIP guest VIP-Guest-3... +Guest-7 has been successfully checked in! +VIP Check-in Results: +VIP-Guest-1 has been successfully checked in! +VIP-Guest-2 has been successfully checked in! +VIP-Guest-3 has been successfully checked in! +All guests have been successfully checked in. Front desk is now closed. +``` + +**Note:** Since this example demonstrates asynchronous thread execution, **the actual output may vary between runs**. The order of execution and timing can differ due to thread scheduling, system load, and other factors that affect concurrent processing. The core behavior of the thread pool (limiting concurrent tasks to the number of threads and reusing threads) will remain consistent, but the exact sequence of log messages may change with each execution. + +## When to Use the Thread-Pool Executor Pattern in Java + +* When you need to limit the number of threads running simultaneously to avoid resource exhaustion +* For applications that process a large number of short-lived independent tasks +* To improve performance by reducing thread creation/destruction overhead +* When implementing server applications that handle multiple client requests concurrently +* To execute recurring tasks at fixed rates or with fixed delays + +## Thread-Pool Executor Pattern Java Tutorial + +* [Thread-Pool Executor Pattern Tutorial (Baeldung)](https://www.baeldung.com/thread-pool-java-and-guava) + +## Real-World Applications of Thread-Pool Executor Pattern in Java + +* Application servers like Tomcat and Jetty use thread pools to handle HTTP requests +* Database connection pools in JDBC implementations +* Background job processing frameworks like Spring Batch +* Task scheduling systems like Quartz Scheduler +* Java EE's Managed Executor Service for enterprise applications + +## Benefits and Trade-offs of Thread-Pool Executor Pattern + +### Benefits + +* Improves performance by reusing existing threads instead of creating new ones +* Provides better resource management by limiting the number of active threads +* Simplifies thread lifecycle management and cleanup +* Facilitates easy implementation of task prioritization and scheduling +* Enhances application stability by preventing resource exhaustion + +### Trade-offs + +* May lead to thread starvation if improperly configured (too few threads) +* Potential for resource underutilization if improperly sized (too many threads) +* Requires careful shutdown handling to prevent task loss or resource leaks + +## Related Java Design Patterns + +* [Master-Worker Pattern](https://java-design-patterns.com/patterns/master-worker/): Tasks between a + master and multiple workers. +* [Producer-Consumer Pattern](https://java-design-patterns.com/patterns/producer-consumer/): + Separates task production and task consumption, typically using a blocking queue. +* [Object Pool Pattern](https://java-design-patterns.com/patterns/object-pool/): Reuses a set of + objects (e.g., threads) instead of creating/destroying them repeatedly. + +## References and Credits + +* [Java Documentation for ThreadPoolExecutor](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html) +* [Java Concurrency in Practice](https://jcip.net/) by Brian Goetz +* [Effective Java](https://www.oreilly.com/library/view/effective-java-3rd/9780134686097/) by Joshua + Bloch diff --git a/thread-pool-executor/etc/thread-pool-executor.urm.png b/thread-pool-executor/etc/thread-pool-executor.urm.png new file mode 100644 index 000000000000..d426343f8171 Binary files /dev/null and b/thread-pool-executor/etc/thread-pool-executor.urm.png differ diff --git a/thread-pool-executor/etc/thread-pool-executor.urm.puml b/thread-pool-executor/etc/thread-pool-executor.urm.puml new file mode 100644 index 000000000000..ca83f40c1b40 --- /dev/null +++ b/thread-pool-executor/etc/thread-pool-executor.urm.puml @@ -0,0 +1,66 @@ +@startuml + +interface Runnable { + +run(): void +} + +interface Callable { + +call(): T +} + +interface ExecutorService { + +submit(task: Runnable): Future + +submit(task: Callable): Future + +shutdown(): void + +awaitTermination(timeout: long, unit: TimeUnit): boolean +} + +class ThreadPoolExecutor { + -corePoolSize: int + -maximumPoolSize: int + -keepAliveTime: long + -workQueue: BlockingQueue + +execute(task: Runnable): void + +submit(task: Callable): Future +} + +class ThreadPoolManager { + -executorService: ExecutorService + +ThreadPoolManager(numThreads: int) + +submitTask(task: Runnable): void + +submitCallable(task: Callable): Future + +shutdown(): void + +awaitTermination(timeout: long, unit: TimeUnit): boolean +} + +class Task { + -id: int + -name: String + -processingTime: long + +Task(id: int, name: String, processingTime: long) + +run(): void + +call(): TaskResult +} + +class TaskResult { + -taskId: int + -taskName: String + -executionTime: long + +TaskResult(taskId: int, taskName: String, executionTime: long) +} + +class App { + +main(args: String[]): void + -executeRunnableTasks(poolManager: ThreadPoolManager): void + -executeCallableTasks(poolManager: ThreadPoolManager): void +} + +ExecutorService <|-- ThreadPoolExecutor : implements +Task ..|> Runnable : implements +Task ..|> Callable : implements +Task --> TaskResult : produces +ThreadPoolManager --> ExecutorService : wraps +App --> ThreadPoolManager : uses +App --> Task : creates + +@enduml \ No newline at end of file diff --git a/thread-pool-executor/pom.xml b/thread-pool-executor/pom.xml new file mode 100644 index 000000000000..f77cd92c67aa --- /dev/null +++ b/thread-pool-executor/pom.xml @@ -0,0 +1,83 @@ + + + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + thread-pool-executor + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.threadpoolexecutor.App + + + + + + + + + diff --git a/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/App.java b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/App.java new file mode 100644 index 000000000000..0c1292b89c3a --- /dev/null +++ b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/App.java @@ -0,0 +1,90 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; + +/** + * The Thread-Pool Executor pattern demonstrates how a pool of worker threads can be used to execute + * tasks concurrently. This pattern is particularly useful in scenarios where you need to execute a + * large number of independent tasks and want to limit the number of threads used. + * + *

In this example, a hotel front desk with a fixed number of employees processes guest + * check-ins. Each employee is represented by a thread, and each check-in is a task. + * + *

Key benefits demonstrated: + * + *

    + *
  • Resource management - Limiting the number of concurrent threads + *
  • Efficiency - Reusing threads instead of creating new ones for each task + *
  • Responsiveness - Handling many requests with limited resources + *
+ */ +@Slf4j +public class App { + + /** + * Program main entry point. + * + * @param args program runtime arguments + */ + public static void main(String[] args) throws InterruptedException, ExecutionException { + + FrontDeskService frontDesk = new FrontDeskService(5); + LOGGER.info("Hotel front desk operation started!"); + + LOGGER.info("Processing 30 regular guest check-ins..."); + for (int i = 1; i <= 30; i++) { + frontDesk.submitGuestCheckIn(new GuestCheckInTask("Guest-" + i)); + Thread.sleep(100); + } + + LOGGER.info("Processing 3 VIP guest check-ins..."); + List> vipResults = new ArrayList<>(); + + for (int i = 1; i <= 3; i++) { + Future result = + frontDesk.submitVipGuestCheckIn(new VipGuestCheckInTask("VIP-Guest-" + i)); + vipResults.add(result); + } + + frontDesk.shutdown(); + + if (frontDesk.awaitTermination(1, TimeUnit.HOURS)) { + LOGGER.info("VIP Check-in Results:"); + for (Future result : vipResults) { + LOGGER.info(result.get()); + } + LOGGER.info("All guests have been successfully checked in. Front desk is now closed."); + } else { + LOGGER.warn("Check-in timeout. Forcefully shutting down the front desk."); + } + } +} diff --git a/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/FrontDeskService.java b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/FrontDeskService.java new file mode 100644 index 000000000000..b80236ee5ecf --- /dev/null +++ b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/FrontDeskService.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; + +/** + * FrontDeskService represents the hotel's front desk with a fixed number of employees. This class + * demonstrates the Thread-Pool Executor pattern using Java's ExecutorService. + */ +@Slf4j +public class FrontDeskService { + + private final ExecutorService executorService; + private final int numberOfEmployees; + + /** + * Creates a new front desk with the specified number of employees. + * + * @param numberOfEmployees the number of employees (threads) at the front desk + */ + public FrontDeskService(int numberOfEmployees) { + this.numberOfEmployees = numberOfEmployees; + this.executorService = Executors.newFixedThreadPool(numberOfEmployees); + LOGGER.info("Front desk initialized with {} employees.", numberOfEmployees); + } + + /** + * Submits a regular guest check-in task to an available employee. + * + * @param task the check-in task to submit + * @return a Future representing pending completion of the task + */ + public Future submitGuestCheckIn(Runnable task) { + LOGGER.debug("Submitting regular guest check-in task"); + return executorService.submit(task, null); + } + + /** + * Submits a VIP guest check-in task to an available employee. + * + * @param task the VIP check-in task to submit + * @param the type of the task's result + * @return a Future representing pending completion of the task + */ + public Future submitVipGuestCheckIn(Callable task) { + LOGGER.debug("Submitting VIP guest check-in task"); + return executorService.submit(task); + } + + /** + * Closes the front desk after all currently checked-in guests are processed. No new check-ins + * will be accepted. + */ + public void shutdown() { + LOGGER.info("Front desk is closing - no new guests will be accepted."); + executorService.shutdown(); + } + + /** + * Waits for all check-in processes to complete or until timeout. + * + * @param timeout the maximum time to wait + * @param unit the time unit of the timeout argument + * @return true if all tasks completed, false if timeout elapsed + * @throws InterruptedException if interrupted while waiting + */ + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + LOGGER.info("Waiting for all check-ins to complete (max wait: {} {})", timeout, unit); + return executorService.awaitTermination(timeout, unit); + } + + /** + * Gets the number of employees at the front desk. + * + * @return the number of employees + */ + public int getNumberOfEmployees() { + return numberOfEmployees; + } +} diff --git a/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/GuestCheckInTask.java b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/GuestCheckInTask.java new file mode 100644 index 000000000000..d8a33fdfc8d2 --- /dev/null +++ b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/GuestCheckInTask.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * GuestCheckInTask represents a regular guest check-in process. Implements Runnable because it + * performs an action without returning a result. + */ +@Slf4j +@AllArgsConstructor +public class GuestCheckInTask implements Runnable { + + private final String guestName; + + @Override + public void run() { + String employeeName = Thread.currentThread().getName(); + LOGGER.info("{} is checking in {}...", employeeName, guestName); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Check-in for {} was interrupted", guestName); + } + LOGGER.info("{} has been successfully checked in!", guestName); + } +} diff --git a/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTask.java b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTask.java new file mode 100644 index 000000000000..3948c114f0d6 --- /dev/null +++ b/thread-pool-executor/src/main/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTask.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import java.util.concurrent.Callable; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * VipGuestCheckInTask represents a VIP guest check-in process. Implements Callable because it + * returns a result (check-in confirmation). + */ +@Slf4j +@AllArgsConstructor +public class VipGuestCheckInTask implements Callable { + + private final String vipGuestName; + + @Override + public String call() throws Exception { + String employeeName = Thread.currentThread().getName(); + LOGGER.info("{} is checking in VIP guest {}...", employeeName, vipGuestName); + + Thread.sleep(1000); + + String result = vipGuestName + " has been successfully checked in!"; + LOGGER.info("VIP check-in completed: {}", result); + return result; + } +} diff --git a/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/AppTest.java b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/AppTest.java new file mode 100644 index 000000000000..13e3a5beec3c --- /dev/null +++ b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.threadpoolexecutor; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void appStartsWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/FrontDeskServiceTest.java b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/FrontDeskServiceTest.java new file mode 100644 index 000000000000..8d0396bf0541 --- /dev/null +++ b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/FrontDeskServiceTest.java @@ -0,0 +1,248 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class FrontDeskServiceTest { + + /** + * Tests that the constructor correctly sets the number of employees (threads). This verifies the + * basic initialization of the thread pool. + */ + @Test + void testConstructorSetsCorrectNumberOfEmployees() { + int expectedEmployees = 3; + + FrontDeskService frontDesk = new FrontDeskService(expectedEmployees); + + assertEquals(expectedEmployees, frontDesk.getNumberOfEmployees()); + } + + /** + * Tests that the submitGuestCheckIn method returns a non-null Future object. This verifies the + * basic task submission functionality. + */ + @Test + void testSubmitGuestCheckInReturnsNonNullFuture() { + FrontDeskService frontDesk = new FrontDeskService(1); + + Runnable task = + () -> { + // Task that completes quickly + }; + + Future future = frontDesk.submitGuestCheckIn(task); + + assertNotNull(future); + } + + /** + * Tests that the submitVipGuestCheckIn method returns a non-null Future object. This verifies + * that tasks with return values can be submitted correctly. + */ + @Test + void testSubmitVipGuestCheckInReturnsNonNullFuture() { + FrontDeskService frontDesk = new FrontDeskService(1); + Callable task = () -> "VIP Check-in complete"; + + Future future = frontDesk.submitVipGuestCheckIn(task); + + assertNotNull(future); + } + + /** + * Tests that the shutdown and awaitTermination methods work correctly. This verifies the basic + * shutdown functionality of the thread pool. + */ + @Test + void testShutdownAndAwaitTermination() throws InterruptedException { + FrontDeskService frontDesk = new FrontDeskService(2); + CountDownLatch taskLatch = new CountDownLatch(1); + + Runnable task = taskLatch::countDown; + + frontDesk.submitGuestCheckIn(task); + frontDesk.shutdown(); + boolean terminated = frontDesk.awaitTermination(1, TimeUnit.SECONDS); + + assertTrue(terminated); + assertTrue(taskLatch.await(100, TimeUnit.MILLISECONDS)); + } + + /** + * Tests the thread pool's behavior under load with multiple tasks. This verifies that the thread + * pool limits concurrent execution to the number of threads, all submitted tasks are eventually + * completed, and threads are reused for multiple tasks. + */ + @Test + void testMultipleTasksUnderLoad() throws InterruptedException { + FrontDeskService frontDesk = new FrontDeskService(2); + int taskCount = 10; + CountDownLatch tasksCompletedLatch = new CountDownLatch(taskCount); + AtomicInteger concurrentTasks = new AtomicInteger(0); + AtomicInteger maxConcurrentTasks = new AtomicInteger(0); + + for (int i = 0; i < taskCount; i++) { + frontDesk.submitGuestCheckIn( + () -> { + try { + int current = concurrentTasks.incrementAndGet(); + maxConcurrentTasks.updateAndGet(max -> Math.max(max, current)); + + Thread.sleep(100); + + concurrentTasks.decrementAndGet(); + tasksCompletedLatch.countDown(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } + + boolean allTasksCompleted = tasksCompletedLatch.await(2, TimeUnit.SECONDS); + + frontDesk.shutdown(); + frontDesk.awaitTermination(1, TimeUnit.SECONDS); + + assertTrue(allTasksCompleted); + assertEquals(2, maxConcurrentTasks.get()); + assertEquals(0, concurrentTasks.get()); + } + + /** + * Tests proper shutdown behavior under load. This verifies that after shutdown no new tasks are + * accepted, all previously submitted tasks are completed, and the executor terminates properly + * after all tasks complete. + */ + @Test + void testProperShutdownUnderLoad() throws InterruptedException { + FrontDeskService frontDesk = new FrontDeskService(2); + int taskCount = 5; + CountDownLatch startedTasksLatch = new CountDownLatch(2); + CountDownLatch tasksCompletionLatch = new CountDownLatch(taskCount); + + for (int i = 0; i < taskCount; i++) { + frontDesk.submitGuestCheckIn( + () -> { + try { + startedTasksLatch.countDown(); + Thread.sleep(100); + tasksCompletionLatch.countDown(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } + + assertTrue(startedTasksLatch.await(1, TimeUnit.SECONDS)); + + frontDesk.shutdown(); + + assertThrows( + RejectedExecutionException.class, + () -> { + frontDesk.submitGuestCheckIn(() -> {}); + }); + + boolean allTasksCompleted = tasksCompletionLatch.await(2, TimeUnit.SECONDS); + + boolean terminated = frontDesk.awaitTermination(1, TimeUnit.SECONDS); + + assertTrue(allTasksCompleted); + assertTrue(terminated); + } + + /** + * Tests concurrent execution of different task types (regular and VIP). This verifies that both + * Runnable and Callable tasks can be processed concurrently, all tasks complete successfully, and + * Callable tasks return their results correctly. + */ + @Test + void testConcurrentRegularAndVipTasks() throws Exception { + FrontDeskService frontDesk = new FrontDeskService(3); + int regularTaskCount = 4; + int vipTaskCount = 3; + CountDownLatch allTasksLatch = new CountDownLatch(regularTaskCount + vipTaskCount); + + List> regularResults = new ArrayList<>(); + for (int i = 0; i < regularTaskCount; i++) { + Future result = + frontDesk.submitGuestCheckIn( + () -> { + try { + Thread.sleep(50); + allTasksLatch.countDown(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + regularResults.add(result); + } + + List> vipResults = new ArrayList<>(); + for (int i = 0; i < vipTaskCount; i++) { + final int guestNum = i; + Future result = + frontDesk.submitVipGuestCheckIn( + () -> { + Thread.sleep(25); + allTasksLatch.countDown(); + return "VIP-" + guestNum + " checked in"; + }); + vipResults.add(result); + } + + boolean allCompleted = allTasksLatch.await(2, TimeUnit.SECONDS); + + frontDesk.shutdown(); + frontDesk.awaitTermination(1, TimeUnit.SECONDS); + + assertTrue(allCompleted); + + for (Future result : regularResults) { + assertTrue(result.isDone()); + } + + for (int i = 0; i < vipTaskCount; i++) { + Future result = vipResults.get(i); + assertTrue(result.isDone()); + assertEquals("VIP-" + i + " checked in", result.get()); + } + } +} diff --git a/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/GuestCheckInTaskTest.java b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/GuestCheckInTaskTest.java new file mode 100644 index 000000000000..27bb75efd2db --- /dev/null +++ b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/GuestCheckInTaskTest.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class GuestCheckInTaskTest { + + /** + * Tests that the task executes in the current thread when called directly. This verifies that the + * thread name inside the task matches the calling thread. + */ + @Test + void testThreadNameInTask() { + String guestName = "TestGuest"; + AtomicReference capturedThreadName = new AtomicReference<>(); + + GuestCheckInTask task = + new GuestCheckInTask(guestName) { + @Override + public void run() { + capturedThreadName.set(Thread.currentThread().getName()); + } + }; + + task.run(); + + assertEquals(Thread.currentThread().getName(), capturedThreadName.get()); + } +} diff --git a/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTaskTest.java b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTaskTest.java new file mode 100644 index 000000000000..d76d90625c95 --- /dev/null +++ b/thread-pool-executor/src/test/java/com/iluwatar/threadpoolexecutor/VipGuestCheckInTaskTest.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpoolexecutor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; + +class VipGuestCheckInTaskTest { + + /** + * Tests that the call method returns the expected result string. This verifies that the VIP + * check-in task correctly formats its result message. + */ + @Test + void testCallReturnsExpectedResult() throws Exception { + String vipGuestName = "TestVipGuest"; + VipGuestCheckInTask task = new VipGuestCheckInTask(vipGuestName); + + String result = task.call(); + + assertNotNull(result); + assertEquals("TestVipGuest has been successfully checked in!", result); + } +} diff --git a/thread-specific-storage/README.md b/thread-specific-storage/README.md new file mode 100644 index 000000000000..e3109595fd84 --- /dev/null +++ b/thread-specific-storage/README.md @@ -0,0 +1,227 @@ +--- +title: "Thread-Specific Storage Pattern in Java: Isolated Thread-Local Data Management" +shortTitle: Thread-Specific Storage +description: "Learn the Thread-Specific Storage pattern in Java with practical examples, class +diagrams, and implementation details. Understand how to manage thread-local data efficiently, +improving concurrency and avoiding synchronization issues." +category: Concurrency +language: en +tag: + +- Concurrency +- Multithreading +- Thread Safety +- Data Isolation +- Memory Management + +--- + +## Intent of Thread-Specific Storage Design Pattern + +The Thread-Specific Storage pattern ensures that each thread has its own isolated instance of shared data, +preventing concurrency issues by eliminating the need for synchronization. It achieves this by using +ThreadLocal variables to store data that is specific to each thread. + +## Detailed Explanation of Thread-Specific Storage Pattern with Real-World Examples + +### Real-world example + +> Think of a customer service center where each agent has their own notepad to record information +> about the customer they're currently helping. Even if multiple agents are helping customers +> simultaneously, each agent's notes are completely separate from the others'. When an agent finishes +> with one customer and moves to the next, they start with a fresh notepad. This approach eliminates +> the need for agents to coordinate their note-taking, as each agent's notes are private to their +> current customer interaction. + +### In plain words + +> Thread-Specific Storage provides each thread with its own private copy of data, isolating thread +> interactions and avoiding the need for synchronization mechanisms. + +### Wikipedia says + +> Thread-local storage (TLS) is a computer programming method that uses static or global memory +> local to a thread. TLS is a common technique for avoiding race conditions when multiple threads +> need to access the same data. Each thread has its own copy of the data, so there is no need for +> synchronization. + +### Class diagram + +![Thread-Specific Storage diagram](./etc/ThreadSpecificStorageUML.png) + +## Programmatic Example of Thread-Specific Storage Pattern in Java + +Imagine a web application that needs to track the current user's context across different stages of request processing. + +Each request is handled by a separate thread, and we need to maintain user-specific information without +synchronization overhead. + +The Thread-Specific Storage pattern efficiently handles this by providing each thread with its own copy +of the user context data. + +```java +@Slf4j +public class APP { + public static void main(String[] args) { + // Simulate concurrent requests from multiple users + for (int i = 1; i <= 5; i++) { + // Simulate tokens for different users + String token = "token::" + (i % 3 + 1); // 3 distinct users + + new Thread(() -> { + // Simulate request processing flow + RequestHandler handler = new RequestHandler(token); + handler.process(); + }).start(); + + // Slightly stagger request times + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} +``` + +Here's how the request handler processes each request: + +```java +@Slf4j +public class RequestHandler { + private final String token; + + public RequestHandler(String token) { + this.token = token; + } + + public void process() { + LOGGER.info("Start handling request with token: {}", token); + + try { + // Step 1: Parse token to get userId + Long userId = parseToken(token); + + // Step 2: Save userId in ThreadLocal storage + UserContextProxy.set(new UserContext(userId)); + + // Simulate delay between stages of request handling + Thread.sleep(200); + + // Step 3: Retrieve userId later in the request flow + Long retrievedId = UserContextProxy.get().getUserId(); + Random random = new Random(); + String accountInfo = retrievedId + "'s account: " + random.nextInt(400); + LOGGER.info(accountInfo); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + // Step 4: Clear ThreadLocal to avoid potential memory leaks + UserContextProxy.clear(); + } + } + + // ... parseToken method implementation +} +``` + +The UserContextProxy acts as a thread-safe accessor to the ThreadLocal storage: + +```java +public class UserContextProxy { + // Underlying TSObjectCollection (ThreadLocalMap) managed by JVM. + // This ThreadLocal acts as the Key for the map. + private static final ThreadLocal userContextHolder = new ThreadLocal<>(); + + /** + * Private constructor to prevent instantiation of this utility class. + */ + private UserContextProxy() {} + + /** Set UserContext for the current thread */ + public static void set(UserContext context) { + userContextHolder.set(context); + } + + /** Get UserContext for the current thread */ + public static UserContext get() { + return userContextHolder.get(); + } + + /** Clear UserContext to prevent potential memory leaks */ + public static void clear() { + userContextHolder.remove(); + } +} +``` + +Here's a sample console output: + +``` +Start handling request with token: token::1 +Start handling request with token: token::2 +Start handling request with token: token::3 +Start handling request with token: token::1 +1's account: 234 +Start handling request with token: token::2 +2's account: 157 +3's account: 89 +1's account: 342 +2's account: 76 +``` + +**Note:** Since this example demonstrates concurrent thread execution, **the actual output may vary between runs**. The order of execution and timing can differ due to thread scheduling, system load, and other factors that affect concurrent processing. However, each thread will correctly maintain its own user context without interference from other threads. + +## When to Use the Thread-Specific Storage Pattern in Java + +* When you need to maintain per-thread state without synchronization overhead +* For applications that process requests in multiple stages and need to share data across those stages +* To avoid concurrency issues when working with non-thread-safe objects like SimpleDateFormat +* When implementing logging or security context that needs to be accessible throughout a request processing +* To maintain thread-specific caches or counters without risk of data corruption + +## Thread-Specific Storage Pattern Java Tutorial + +* [Thread-Specific Storage Pattern Tutorial (Baeldung)](https://www.baeldung.com/java-threadlocal) + +## Real-World Applications of Thread-Specific Storage Pattern in Java + +* Servlet containers use ThreadLocal to maintain the current request and response objects +* Spring Framework uses ThreadLocal for managing transaction contexts and security contexts +* Logging frameworks use ThreadLocal to associate log messages with the current thread's context +* Database connection management where each thread needs its own connection or maintains a connection pool per thread +* User session management in web applications where session data is accessed across multiple layers + +## Benefits and Trade-offs of Thread-Specific Storage Pattern + +### Benefits + +* Eliminates the need for synchronization mechanisms, improving performance +* Provides complete isolation of data between threads, preventing concurrency issues +* Simplifies code by removing the need to pass context objects through method parameters +* Enables safe use of non-thread-safe classes in multi-threaded environments +* Reduces object creation overhead by reusing thread-local instances + +### Trade-offs + +* Can lead to increased memory consumption as each thread maintains its own copy of data +* Requires careful cleanup to prevent memory leaks, especially in long-running applications +* May complicate debugging as data is not visible across threads +* Can cause issues in environments with thread pooling where threads are reused (data from previous tasks may persist) + +## Related Java Design Patterns + +* [Context Object Pattern](https://java-design-patterns.com/patterns/context-object/): Encapsulates + request-specific information into a context object that can be passed between components. +* [Thread Pool Pattern](https://java-design-patterns.com/patterns/thread-pool-executor/): + Maintains a pool of worker threads to execute tasks concurrently, optimizing resource usage. +* [Singleton Pattern](https://java-design-patterns.com/patterns/singleton/): Ensures a class has only + one instance and provides global access to it, similar to how ThreadLocal provides per-thread access. + +## References and Credits + +* [Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects](https://www.amazon.com/Pattern-Oriented-Software-Architecture-Concurrent-Networked/dp/0471606952) +* [Java Documentation for ThreadLocal](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ThreadLocal.html) +* [Java Concurrency in Practice](https://jcip.net/) by Brian Goetz \ No newline at end of file diff --git a/thread-specific-storage/etc/ThreadSpecificStorageUML.png b/thread-specific-storage/etc/ThreadSpecificStorageUML.png new file mode 100644 index 000000000000..d4957dd1cc2a Binary files /dev/null and b/thread-specific-storage/etc/ThreadSpecificStorageUML.png differ diff --git a/thread-specific-storage/etc/thread-specific-storage.urm.puml b/thread-specific-storage/etc/thread-specific-storage.urm.puml new file mode 100644 index 000000000000..b38ac8755f72 --- /dev/null +++ b/thread-specific-storage/etc/thread-specific-storage.urm.puml @@ -0,0 +1,41 @@ +@startuml +package thread-specific-storage { + + class APP { + + {static} main(args : String[]) : void + } + + class Thread { + + start() : void + } + + class UserContext { + - userId : Long + + UserContext(userId : Long) + + getUserId() : Long + + setUserId(userId : Long) : void + } + + class UserContextProxy { + - {static} userContextHolder : ThreadLocal + + {static} set(context : UserContext) : void + + {static} get() : UserContext + + {static} clear() : void + } + + class RequestHandler { + - token : String + + RequestHandler(token : String) + + process() : void + - parseToken(token : String) : Long + } + + UserContextProxy --> UserContext : manages + RequestHandler --> UserContextProxy : uses static + RequestHandler --> UserContext : creates + APP --> RequestHandler : creates + APP --> Thread : starts + Thread --> RequestHandler : executes + +} +@enduml \ No newline at end of file diff --git a/thread-specific-storage/pom.xml b/thread-specific-storage/pom.xml new file mode 100644 index 000000000000..1af91514369b --- /dev/null +++ b/thread-specific-storage/pom.xml @@ -0,0 +1,89 @@ + + + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + thread-specific-storage + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + org.awaitility + awaitility + 4.2.1 + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.threadspecificstorage.App + + + + + + + + + diff --git a/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/App.java b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/App.java new file mode 100644 index 000000000000..a84388acfe08 --- /dev/null +++ b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/App.java @@ -0,0 +1,42 @@ +package com.iluwatar.threadspecificstorage; + +import lombok.extern.slf4j.Slf4j; + +/** + * Application entry point demonstrating the Thread-Specific Storage pattern. + * + *

This example simulates concurrent request processing for multiple users. Each request carries + * a user token, and user-specific context is managed transparently using thread-specific storage. + */ +@Slf4j +public class App { + + /** + * Runs the Thread-Specific Storage pattern demonstration. + * + * @param args command-line arguments (not used) + */ + public static void main(String[] args) { + // Simulate concurrent requests from multiple users + for (int i = 1; i <= 5; i++) { + // Simulate tokens for different users + String token = "token::" + (i % 3 + 1); // 3 distinct users + + new Thread( + () -> { + // Simulate request processing flow + RequestHandler handler = new RequestHandler(token); + handler.process(); + }) + .start(); + + // Slightly stagger request times + try { + Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.warn("Sleep interrupted", e); + } + } + } +} diff --git a/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/RequestHandler.java b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/RequestHandler.java new file mode 100644 index 000000000000..d5f2cca2830d --- /dev/null +++ b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/RequestHandler.java @@ -0,0 +1,57 @@ +package com.iluwatar.threadspecificstorage; + +import java.security.SecureRandom; +import lombok.extern.slf4j.Slf4j; + +/** + * Application Thread + * + *

Each instance simulates a request-processing thread that uses the Thread-Specific Object Proxy + * to access Thread-Specific Object. + */ +@Slf4j +public class RequestHandler { + private final String token; + + public RequestHandler(String token) { + this.token = token; + } + + /** + * Simulated business process: 1. Parse userId from token ("Token::userId"). 2. Store userId in + * thread-local storage. 3. Later, retrieve userId and use it for business logic. 4. Finally, + * clear thread-local to prevent memory leak. + */ + public void process() { + LOGGER.info("Start handling request with token: {}", token); + + try { + // Step 1: Parse token to get userId + Long userId = parseToken(token); + + // Step 2: Save userId in ThreadLocal storage + UserContextProxy.set(new UserContext(userId)); + + // Simulate delay between stages of request handling + Thread.sleep(200); + + // Step 3: Retrieve userId later in the request flow + Long retrievedId = UserContextProxy.get().getUserId(); + SecureRandom random = new SecureRandom(); + String accountInfo = retrievedId + "'s account: " + random.nextInt(400); + LOGGER.info(accountInfo); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + // Step 4: Clear ThreadLocal to avoid potential memory leaks + UserContextProxy.clear(); + } + } + + private Long parseToken(String token) { + // token format: "Token::1234" + String[] parts = token.split("::"); + return (parts.length == 2) ? Long.parseLong(parts[1]) : -1L; + } +} diff --git a/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContext.java b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContext.java new file mode 100644 index 000000000000..51399a1a0c72 --- /dev/null +++ b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContext.java @@ -0,0 +1,15 @@ +package com.iluwatar.threadspecificstorage; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Thread-Specific Object + * + *

Provides a service or data that is only accessible via a particular thread. + */ +@Data +@AllArgsConstructor +public class UserContext { + private Long userId; +} diff --git a/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContextProxy.java b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContextProxy.java new file mode 100644 index 000000000000..468e554b0bf6 --- /dev/null +++ b/thread-specific-storage/src/main/java/com/iluwatar/threadspecificstorage/UserContextProxy.java @@ -0,0 +1,33 @@ +package com.iluwatar.threadspecificstorage; + +/** + * Thread-Specific Object Proxy + * + *

The Thread-Specific Object Proxy acts as an intermediary, enabling application thread to + * access and manipulate thread-specific objects simply and securely. + */ +public class UserContextProxy { + /** + * Underlying TSObjectCollection (ThreadLocalMap) managed by JVM.This ThreadLocal acts as the Key + * for the map.So That there is also no key factory. + */ + private static final ThreadLocal userContextHolder = new ThreadLocal<>(); + + /** Private constructor to prevent instantiation of this utility class. */ + private UserContextProxy() {} + + /** Set UserContext for the current thread. */ + public static void set(UserContext context) { + userContextHolder.set(context); + } + + /** Get UserContext for the current thread. */ + public static UserContext get() { + return userContextHolder.get(); + } + + /** Clear UserContext to prevent potential memory leaks. */ + public static void clear() { + userContextHolder.remove(); + } +} diff --git a/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/AppTest.java b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/AppTest.java new file mode 100644 index 000000000000..775ded85b8ea --- /dev/null +++ b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/AppTest.java @@ -0,0 +1,38 @@ +package com.iluwatar.threadspecificstorage; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.Test; + +/** Tests for APP class */ +class AppTest { + @Test + void testMainMethod() { + // Capture system output + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + + // Run the main method + App.main(new String[] {}); + + // Give some time for threads to execute + await() + .atMost(5, SECONDS) + .pollInterval(100, MILLISECONDS) + .until(() -> outContent.toString().contains("Start handling request with token")); + + // Verify output contains expected log messages + String output = outContent.toString(); + assertTrue( + output.contains("Start handling request with token"), + "Should contain request handling start messages"); + + // Restore system output + System.setOut(System.out); + } +} diff --git a/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/RequestHandlerTest.java b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/RequestHandlerTest.java new file mode 100644 index 000000000000..e5f5968e7794 --- /dev/null +++ b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/RequestHandlerTest.java @@ -0,0 +1,32 @@ +package com.iluwatar.threadspecificstorage; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class RequestHandlerTest { + + @Test + void process_shouldStoreAndClearUserContext() { + // Given - a request handler without proxy parameter + RequestHandler handler = new RequestHandler("token::123"); + + // When - process the request + handler.process(); + + // Then - after processing, ThreadLocal should be cleared + assertNull(UserContextProxy.get(), "ThreadLocal should be cleared after process()"); + } + + @Test + void process_withInvalidToken_shouldSetUserIdToMinusOne() { + // Given - a request handler without proxy parameter + RequestHandler handler = new RequestHandler("invalid-token"); + + // When - process the request + handler.process(); + + // Then - after processing, ThreadLocal should be cleared + assertNull(UserContextProxy.get(), "ThreadLocal should be cleared even for invalid token"); + } +} diff --git a/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextProxyTest.java b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextProxyTest.java new file mode 100644 index 000000000000..fd8cfbd6b7aa --- /dev/null +++ b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextProxyTest.java @@ -0,0 +1,70 @@ +package com.iluwatar.threadspecificstorage; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for UserContextProxy class */ +class UserContextProxyTest { + + private UserContext userContext; + + @BeforeEach + void setUp() { + userContext = new UserContext(123L); + } + + @AfterEach + void tearDown() { + UserContextProxy.clear(); + } + + @Test + void testSetAndGetContext() { + UserContextProxy.set(userContext); + UserContext retrievedContext = UserContextProxy.get(); + assertNotNull(retrievedContext, "Retrieved context should not be null"); + assertEquals( + userContext.getUserId(), + retrievedContext.getUserId(), + "Retrieved context should have the same userId"); + } + + @Test + void testGetContextWhenNotSet() { + UserContext retrievedContext = UserContextProxy.get(); + assertNull(retrievedContext, "Context should be null when not set"); + } + + @Test + void testClearContext() { + UserContextProxy.set(userContext); + UserContextProxy.clear(); + UserContext retrievedContext = UserContextProxy.get(); + assertNull(retrievedContext, "Context should be null after clearing"); + } + + @Test + void testThreadIsolation() throws InterruptedException { + UserContext context1 = new UserContext(123L); + UserContext context2 = new UserContext(456L); + UserContextProxy.set(context1); + // Create another thread to set different context + Thread thread = + new Thread( + () -> { + UserContextProxy.set(context2); + UserContext threadContext = UserContextProxy.get(); + assertNotNull(threadContext); + assertEquals(456L, threadContext.getUserId()); + }); + thread.start(); + thread.join(); + // Main thread context should remain unchanged + UserContext mainThreadContext = UserContextProxy.get(); + assertNotNull(mainThreadContext); + assertEquals(123L, mainThreadContext.getUserId()); + } +} diff --git a/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextTest.java b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextTest.java new file mode 100644 index 000000000000..3a7864c9e92e --- /dev/null +++ b/thread-specific-storage/src/test/java/com/iluwatar/threadspecificstorage/UserContextTest.java @@ -0,0 +1,57 @@ +package com.iluwatar.threadspecificstorage; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +/** Tests for UserContext class */ +class UserContextTest { + + @Test + void testConstructorAndGetUserId() { + Long userId = 123L; + UserContext context = new UserContext(userId); + + assertEquals( + userId, context.getUserId(), "UserId should match the one provided in constructor"); + } + + @Test + void testSetUserId() { + UserContext context = new UserContext(123L); + Long newUserId = 456L; + + context.setUserId(newUserId); + + assertEquals(newUserId, context.getUserId(), "UserId should be updated"); + } + + @Test + void testToString() { + Long userId = 123L; + UserContext context = new UserContext(userId); + + String expected = "UserContext(userId=" + userId + ")"; + assertEquals(expected, context.toString(), "toString should return expected format"); + } + + @Test + void testEqualsAndHashCode() { + Long userId = 123L; + UserContext context1 = new UserContext(userId); + UserContext context2 = new UserContext(userId); + UserContext context3 = new UserContext(456L); + + assertEquals(context1, context2, "Objects with same userId should be equal"); + assertEquals( + context1.hashCode(), + context2.hashCode(), + "Objects with same userId should have same hashCode"); + + assertNotEquals(context1, context3, "Objects with different userId should not be equal"); + assertNotEquals( + context1.hashCode(), + context3.hashCode(), + "Objects with different userId should have different hashCode"); + } +} diff --git a/view-helper/README.md b/view-helper/README.md new file mode 100644 index 000000000000..fbc93acba6fd --- /dev/null +++ b/view-helper/README.md @@ -0,0 +1,98 @@ +--- +title: "View Helper Pattern in Java: Simplifying Presentation Logic in MVC Applications" +shortTitle: View Helper +description: "Discover the View Helper Design Pattern in Java, a powerful technique for separating view-related logic from business logic in MVC-based web applications. This pattern enhances maintainability, reusability, and testability by delegating complex UI operations to reusable helper components. Ideal for developers aiming to keep views clean and focused on presentation." +category: Architectural +language: en +tag: + - Architecture + - Presentation + - Decoupling + - Code reuse +--- + +## Intent of View Helper Design Pattern +The View Helper Design Pattern separates presentation logic from the view by delegating complex UI tasks — like formatting or conditional display — to reusable helper components. This keeps views clean, promotes reuse, and aligns with the MVC principle of separating concerns between the view and the business logic. + +## Detailed Explanation with Real‑World Analogy +Real‑world example +> Imagine you're putting together a slideshow for a business presentation. You focus on arranging the slides, choosing the layout, and telling the story. But for tasks like resizing images, formatting charts, or converting data into visual form, you use tools or templates that automate those parts. +> +> In this analogy, you are the view, and the tools/templates are the helpers. They handle the heavy lifting behind the scenes so you can concentrate on the presentation. Similarly, in the View Helper pattern, the view delegates logic-heavy tasks—such as formatting or conditionally displaying data—to helper classes, keeping the view layer clean and presentation-focused. + +### In plain words +> The View Helper pattern is about keeping your UI code clean by moving any logic—like formatting, calculations, or decision-making—into separate helper classes. Instead of stuffing all the logic into the HTML or template files, you delegate it to helpers, so the view just focuses on showing the final result. + +### Sequence diagram +![Sequence diagram for View Helper](etc/view-helper-sequence-diagram.png) + +## Programmatic Example of View Helper Pattern in Java +Raw domain object +```java +public record Product(String name, BigDecimal price, LocalDate releaseDate, boolean discounted) {} +``` + +View model object for display +```java +public record ProductViewModel(String name, String price, String releasedDate) {} +``` + +View Helper formats data for display +```java +class ProductViewHelper implements ViewHelper { + + private static final String DISCOUNT_TAG = " (ON SALE)"; + + public ProductViewModel prepare(Product product) { + var displayName = product.name() + (product.discounted() ? DISCOUNT_TAG : ""); + var priceWithCurrency = NumberFormat.getCurrencyInstance(US).format(product.price()); + var formattedDate = product.releaseDate().format(ISO_DATE); + + return new ProductViewModel(displayName, priceWithCurrency, formattedDate); + } +} +``` + +View renders the formatted data +```java +public class ConsoleProductView implements View { + + @Override + public void render(ProductViewModel productViewModel) { + LOGGER.info(productViewModel.toString()); + } +} +``` +The `App.java` class simulates how the View Helper pattern works in a real application. It starts with a raw `Product` object containing unformatted data. +Then it: +1. Initializes a helper (`ProductViewHelper`) to format the product data for display. +1. Creates a view (`ConsoleProductView`) to render the formatted data. +1. Uses a controller (`ProductController`) to coordinate the flow between raw data, helper logic, and view rendering. + +Finally, it simulates a user request by passing the product to the controller, which prepares the view model using the helper and displays it using the view. This demonstrates a clean separation between data, presentation logic, and rendering. + +## When to Use the View Helper Pattern in Java +Use the View Helper pattern when your view layer starts containing logic such as formatting data, applying conditional styles, or transforming domain objects for display. It's especially useful in MVC architectures where you want to keep views clean and focused on rendering, while delegating non-trivial presentation logic to reusable helper classes. This pattern helps improve maintainability, testability, and separation of concerns in your application's UI layer. + +## Real‑World Uses of View Helper Pattern in Java +The View Helper pattern is widely used in web frameworks that follow the MVC architecture. In Java-based web applications (e.g., JSP, Spring MVC), it's common to use helper classes or utility methods to format dates, currencies, or apply conditional logic before rendering views. Technologies like Thymeleaf or JSF often rely on custom tags or expression helpers to achieve the same effect. + +## Benefits and Trade‑offs +Benefits: +* Separation of concerns: Keeps view templates clean by moving logic into dedicated helpers. +* Reusability: Common formatting and display logic can be reused across multiple views. +* Improved maintainability: Easier to update presentation logic without touching the view. +* Testability: Helpers can be unit tested independently from the UI layer. + +Trade‑offs: +* Added complexity: Introduces extra classes, which may feel unnecessary for very simple views. +* Overuse risk: Excessive use of helpers can spread logic thinly across many files, making it harder to trace behavior. +* Tight coupling risk: If not designed carefully, helpers can become tightly coupled to specific views or data formats. + +## Related Java Design Patterns +* [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): View Helper supports the View layer in MVC by offloading logic from the view to helper classes. +* [Template Method](https://java-design-patterns.com/patterns/template-method/): Can structure the steps of rendering or data transformation, with helpers handling specific formatting tasks. +* [Data Transfer Object (DTO)](https://java-design-patterns.com/patterns/data-transfer-object/): Often used alongside View Helper when transferring raw data that needs formatting before being displayed. + +## References & Credits +* [Core J2EE Patterns: View Helper.](https://www.oracle.com/java/technologies/viewhelper.html) diff --git a/view-helper/etc/view-helper-sequence-diagram.png b/view-helper/etc/view-helper-sequence-diagram.png new file mode 100644 index 000000000000..22e53c6b8afe Binary files /dev/null and b/view-helper/etc/view-helper-sequence-diagram.png differ diff --git a/view-helper/etc/view-helper-sequence-diagram.puml b/view-helper/etc/view-helper-sequence-diagram.puml new file mode 100644 index 000000000000..d5be27e51510 --- /dev/null +++ b/view-helper/etc/view-helper-sequence-diagram.puml @@ -0,0 +1,15 @@ +@startuml +actor Client +participant Controller +participant ViewHelper +participant View +participant Product +participant ProductViewModel + +Client -> Controller : handle(product) +Controller -> ViewHelper : prepare(product) +ViewHelper -> Product : access data +ViewHelper -> ProductViewModel : return formatted view model +Controller -> View : render(viewModel) +View -> Console : display output +@enduml \ No newline at end of file diff --git a/view-helper/etc/view-helper.png b/view-helper/etc/view-helper.png new file mode 100644 index 000000000000..9550b80d7acb Binary files /dev/null and b/view-helper/etc/view-helper.png differ diff --git a/view-helper/etc/view-helper.puml b/view-helper/etc/view-helper.puml new file mode 100644 index 000000000000..cbc4a57d31ff --- /dev/null +++ b/view-helper/etc/view-helper.puml @@ -0,0 +1,45 @@ +@startuml +package com.iluwatar.viewhelper { + interface View { + +render(T model) + } + + interface ViewHelper { + +prepare(S source): T + } + + class Product { + -name: String + -price: BigDecimal + -releaseDate: LocalDate + -discounted: boolean + } + + class ProductViewModel { + -name: String + -price: String + -releasedDate: String + } + + class ProductViewHelper { + +prepare(Product): ProductViewModel + } + + class ConsoleProductView { + +render(ProductViewModel) + } + + class ProductController { + -helper: ViewHelper + -view: View + +handle(Product) + } +} +Product --> ProductViewHelper +ProductViewHelper ..|> ViewHelper +ConsoleProductView ..|> View +ProductViewHelper --> ProductViewModel +ProductController --> ProductViewHelper +ProductController --> ConsoleProductView + +@enduml \ No newline at end of file diff --git a/view-helper/pom.xml b/view-helper/pom.xml new file mode 100644 index 000000000000..e2f3afca3a08 --- /dev/null +++ b/view-helper/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + view-helper + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.value.object.App + + + + + + + + + diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/App.java b/view-helper/src/main/java/com/iluwatar/viewhelper/App.java new file mode 100644 index 000000000000..e427bc8f5e9b --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/App.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.viewhelper; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** The main application class that sets up and runs the View Helper pattern demo. */ +public class App { + /** + * The entry point of the application. + * + * @param args the command line arguments + */ + public static void main(String[] args) { + // Raw Product data (no formatting, no UI tags) + var product = + new Product( + "Design patterns book", new BigDecimal("18.90"), LocalDate.of(2025, 4, 19), true); + + // Create view, viewHelper and viewHelper + var helper = new ProductViewHelper(); + var view = new ConsoleProductView(); + var controller = new ProductController(helper, view); + + // Handle “request” + controller.handle(product); + } +} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/ConsoleProductView.java b/view-helper/src/main/java/com/iluwatar/viewhelper/ConsoleProductView.java new file mode 100644 index 000000000000..7f215a7514f6 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/ConsoleProductView.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +import lombok.extern.slf4j.Slf4j; + +/** Renders {@link ProductViewModel} to the console. */ +@Slf4j +public class ConsoleProductView implements View { + @Override + public void render(ProductViewModel productViewModel) { + LOGGER.info(productViewModel.toString()); + } +} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/Product.java b/view-helper/src/main/java/com/iluwatar/viewhelper/Product.java new file mode 100644 index 000000000000..a0a75cf24188 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/Product.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** Definition of product. */ +public record Product(String name, BigDecimal price, LocalDate releaseDate, boolean discounted) {} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/ProductController.java b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductController.java new file mode 100644 index 000000000000..836f34a33167 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductController.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +/** + * Controller delegates a {@link Product} to {@link ProductViewHelper} and then to {@link + * ConsoleProductView}. + */ +public class ProductController { + + private final ViewHelper viewHelper; + private final View view; + + public ProductController( + ViewHelper viewHelper, View view) { + this.viewHelper = viewHelper; + this.view = view; + } + + /** + * Passes the product to the helper for formatting and then forwards formatted product to the + * view. + */ + public void handle(Product product) { + view.render(viewHelper.prepare(product)); + } +} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewHelper.java b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewHelper.java new file mode 100644 index 000000000000..4c739e9f14a8 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewHelper.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +import static java.time.format.DateTimeFormatter.ISO_DATE; +import static java.util.Locale.US; + +import java.text.NumberFormat; + +/** Formats a {@link Product} into a {@link ProductViewModel}. */ +public class ProductViewHelper implements ViewHelper { + + private static final String DISCOUNT_TAG = " ON SALE"; + + @Override + public ProductViewModel prepare(Product product) { + var displayName = product.name() + (product.discounted() ? DISCOUNT_TAG : ""); + var priceWithCurrency = NumberFormat.getCurrencyInstance(US).format(product.price()); + var formattedDate = product.releaseDate().format(ISO_DATE); + + return new ProductViewModel(displayName, priceWithCurrency, formattedDate); + } +} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewModel.java b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewModel.java new file mode 100644 index 000000000000..b133fc071da1 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/ProductViewModel.java @@ -0,0 +1,28 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +/** Class defining formatted display data of a {@link Product}. */ +public record ProductViewModel(String name, String price, String releasedDate) {} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/View.java b/view-helper/src/main/java/com/iluwatar/viewhelper/View.java new file mode 100644 index 000000000000..7bc822166885 --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/View.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +public interface View { + + void render(V data); +} diff --git a/view-helper/src/main/java/com/iluwatar/viewhelper/ViewHelper.java b/view-helper/src/main/java/com/iluwatar/viewhelper/ViewHelper.java new file mode 100644 index 000000000000..68756f46585d --- /dev/null +++ b/view-helper/src/main/java/com/iluwatar/viewhelper/ViewHelper.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +public interface ViewHelper { + V prepare(M source); +} diff --git a/view-helper/src/test/java/com/iluwatar/viewhelper/AppTest.java b/view-helper/src/test/java/com/iluwatar/viewhelper/AppTest.java new file mode 100644 index 000000000000..bc4a31cc43a8 --- /dev/null +++ b/view-helper/src/test/java/com/iluwatar/viewhelper/AppTest.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.viewhelper; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/view-helper/src/test/java/com/iluwatar/viewhelper/ProductViewHelperTest.java b/view-helper/src/test/java/com/iluwatar/viewhelper/ProductViewHelperTest.java new file mode 100644 index 000000000000..49cc48556f47 --- /dev/null +++ b/view-helper/src/test/java/com/iluwatar/viewhelper/ProductViewHelperTest.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.viewhelper; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.time.LocalDate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ProductViewHelperTest { + + private ProductViewHelper helper; + + @BeforeEach + void setUp() { + helper = new ProductViewHelper(); + } + + @Test + void shouldFormatProductWithoutDiscount() { + var product = new Product("X", new BigDecimal("10.00"), LocalDate.of(2025, 1, 1), false); + ProductViewModel viewModel = helper.prepare(product); + + assertEquals("X", viewModel.name()); + assertEquals("$10.00", viewModel.price()); + assertEquals("2025-01-01", viewModel.releasedDate()); + } + + @Test + void shouldFormatProductWithDiscount() { + var product = new Product("X", new BigDecimal("10.00"), LocalDate.of(2025, 1, 1), true); + ProductViewModel viewModel = helper.prepare(product); + + assertEquals("X ON SALE", viewModel.name()); // locale follows JVM default + } +} diff --git a/write-ahead-log/README.md b/write-ahead-log/README.md new file mode 100644 index 000000000000..45caab13cadf --- /dev/null +++ b/write-ahead-log/README.md @@ -0,0 +1,217 @@ +--- +title: "Write-Ahead Log (WAL) Pattern in Java: Ensuring Data Durability and Crash Recovery" +shortTitle: Write-Ahead Log +description: "Learn about the Write-Ahead Log (WAL) design pattern in Java. Discover how append-only logging guarantees data durability and fast crash recovery in database engines and distributed systems." +category: Data Access +language: en +tag: + - Data access + - Storage + - Fault tolerance + - Transactions + - Performance +--- + +## Also known as + +* Append-Only Log +* Redo Log +* Journaling + +## Intent of Write-Ahead Log Pattern + +The Write-Ahead Log (WAL) design pattern ensures data durability and system recoverability in database engines, distributed consensus protocols, and transactional systems. It enforces a strict order of operations where any state mutation (e.g., insert, update, delete) must be written sequentially to an append-only log file on stable storage (disk) before it is applied to the main database state or in-memory storage structures. + +## Detailed Explanation of Write-Ahead Log Pattern with Real-World Examples + +Real-world example + +> Imagine an accountant managing a company's ledger. Before modifying the main financial summary balance sheets, the accountant immediately records every incoming transaction line-by-line into a sequential physical logbook. If power cuts out mid-day or the summary balance sheets are damaged, the accountant can re-open the physical logbook, replay every recorded entry from the beginning, and perfectly recalculate the final financial state. + +In plain words + +> Write-Ahead Log guarantees that no state mutation is lost during sudden system crashes by writing changes to a fast append-only disk log file before updating the in-memory store. + +Wikipedia says + +> In computer science, write-ahead logging (WAL) is a family of techniques for providing atomicity and durability (two of the ACID properties) in database systems. In a system using WAL, all modifications are written to a log before they are applied. Usually both redo and undo information are stored in the log. + +Class Diagram + +```mermaid +classDiagram + class OperationType { + <> + SET + DELETE + CHECKPOINT + } + + class LogEntry { + -long sequenceNumber + -OperationType type + -String key + -String value + +toLogString() String + +fromLogString(String line)$ LogEntry + } + + class WriteAheadLog { + -File logFile + -AtomicLong sequenceNumberCounter + +append(OperationType type, String key, String value) LogEntry + +readAll() List~LogEntry~ + +clear() void + } + + class DatabaseStore { + -WriteAheadLog wal + -Map~String, String~ memTable + +put(String key, String value) void + +delete(String key) void + +get(String key) String + +checkpoint() void + +simulateCrash() void + +recover() void + } + + DatabaseStore --> WriteAheadLog + WriteAheadLog --> LogEntry + LogEntry --> OperationType +``` + +## Programmatic Example of Write-Ahead Log Pattern in Java + +The `WriteAheadLog` class manages append-only sequential writes to disk: + +```java +public class WriteAheadLog { + private final File logFile; + private final AtomicLong sequenceNumberCounter = new AtomicLong(0); + + public synchronized LogEntry append(OperationType type, String key, String value) throws IOException { + long nextSeq = sequenceNumberCounter.incrementAndGet(); + LogEntry entry = new LogEntry(nextSeq, type, key, value); + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true))) { + writer.write(entry.toLogString()); + writer.newLine(); + writer.flush(); + } + return entry; + } +} +``` + +The `DatabaseStore` class coordinates writing to the log before modifying its in-memory `MemTable`: + +```java +public class DatabaseStore { + private final WriteAheadLog wal; + private final Map memTable = new HashMap<>(); + + public synchronized void put(String key, String value) throws IOException { + wal.append(OperationType.SET, key, value); + memTable.put(key, value); + } + + public synchronized void delete(String key) throws IOException { + wal.append(OperationType.DELETE, key, null); + memTable.remove(key); + } + + public synchronized void recover() { + memTable.clear(); + List entries = wal.readAll(); + for (LogEntry entry : entries) { + if (entry.getType() == OperationType.SET) { + memTable.put(entry.getKey(), entry.getValue()); + } else if (entry.getType() == OperationType.DELETE) { + memTable.remove(entry.getKey()); + } + } + } +} +``` + +The `App` class demonstrates initialization, writes, crash simulation, and WAL recovery: + +```java +@Slf4j +public class App { + public static void main(String[] args) { + try { + File logFile = File.createTempFile("wal_demo", ".log"); + WriteAheadLog wal = new WriteAheadLog(logFile); + DatabaseStore store = new DatabaseStore(wal); + + store.put("user:101", "Alice"); + store.put("user:102", "Bob"); + store.delete("user:103"); + + // Simulating system crash where in-memory state is lost + store.simulateCrash(); + + // System reboot & recovery from WAL log replay + store.recover(); + + LOGGER.info("MemTable post recovery: {}", store.getMemTableSnapshot()); + } catch (IOException e) { + LOGGER.error("Error running WAL demo", e); + } + } +} +``` + +Program output: + +```text +15:45:00.100 [main] INFO com.iluwatar.writeaheadlog.App -- === 1. Initializing Storage Engine with WAL === +15:45:00.105 [main] INFO com.iluwatar.writeaheadlog.WriteAheadLog -- WAL Entry appended & flushed to disk: LogEntry(sequenceNumber=1, type=SET, key=user:101, value=Alice) +15:45:00.106 [main] INFO com.iluwatar.writeaheadlog.DatabaseStore -- Applied SET operation to MemTable: user:101 = Alice +15:45:00.107 [main] INFO com.iluwatar.writeaheadlog.App -- === 3. Simulating Unexpected System Crash === +15:45:00.108 [main] INFO com.iluwatar.writeaheadlog.DatabaseStore -- !!! SIMULATED SYSTEM CRASH: In-memory MemTable has been wiped !!! +15:45:00.109 [main] INFO com.iluwatar.writeaheadlog.App -- === 4. System Restart & Recovery from WAL === +15:45:00.110 [main] INFO com.iluwatar.writeaheadlog.DatabaseStore -- Starting recovery process from WAL... +15:45:00.112 [main] INFO com.iluwatar.writeaheadlog.DatabaseStore -- Recovery completed. Replayed 5 log entries into MemTable. +15:45:00.113 [main] INFO com.iluwatar.writeaheadlog.App -- MemTable snapshot post recovery: {user:101=Alice, user:102=Bob Smith} +``` + +## When to Use the Write-Ahead Log Pattern in Java + +* Building storage engines or key-value data stores requiring ACID durability guarantees. +* Implementing fault-tolerant distributed consensus protocols (e.g., Raft, Paxos). +* System architectures where random disk I/O is expensive, allowing sequential append-only writes for maximum throughput. +* Message brokers or event streams requiring replayability after failure. + +## Real-World Applications of Write-Ahead Log Pattern in Java + +* **PostgreSQL / MySQL (InnoDB):** Uses WAL / Redo Log for crash recovery and replication. +* **SQLite:** Write-Ahead Logging mode for concurrency and atomic commits. +* **Apache Cassandra / RocksDB:** Appends mutations to CommitLog / WAL before MemTable updates. +* **Apache Kafka / Raft:** Log replication across distributed nodes for consensus and state machine replication. + +## Benefits and Trade-offs of Write-Ahead Log Pattern + +Benefits: + +* **High Performance:** Sequential disk writes are significantly faster than random disk updates (e.g., updating B-Trees directly). +* **Durability & Fault Tolerance:** Guarantees no committed transaction is lost during sudden system crashes. +* **Simplicity of Recovery:** Replaying ordered log records deterministically restores the exact last-known state. + +Trade-offs: + +* **Storage Overhead:** Log files grow over time, requiring periodic checkpointing and log truncation. +* **Recovery Time:** Large log files without checkpoints can lead to slow startup/recovery times. + +## Related Java Design Patterns + +* [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Captures state mutations as a sequence of events, similar to log replay. +* [Command](https://java-design-patterns.com/patterns/command/): Encapsulates requests as objects, which can be serialized into WAL entries. +* [Memento](https://java-design-patterns.com/patterns/memento/): Stores state snapshots (checkpoints) to truncate logs. + +## References and Credits + +* [Designing Data-Intensive Applications (Martin Kleppmann)](https://www.oreilly.com/library/view/designing-data-intensive-applications/9781491903063/) +* [PostgreSQL Documentation: Write-Ahead Logging (WAL)](https://www.postgresql.org/docs/current/wal-intro.html) +* [Raft Consensus Algorithm Paper](https://raft.github.io/) diff --git a/write-ahead-log/pom.xml b/write-ahead-log/pom.xml new file mode 100644 index 000000000000..adb766953a47 --- /dev/null +++ b/write-ahead-log/pom.xml @@ -0,0 +1,87 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + write-ahead-log + 1.26.0-SNAPSHOT + write-ahead-log + http://maven.apache.org + + UTF-8 + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.writeaheadlog.App + + + + + + + + + diff --git a/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/App.java b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/App.java new file mode 100644 index 000000000000..e8e9fae2f763 --- /dev/null +++ b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/App.java @@ -0,0 +1,82 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import java.io.File; +import java.io.IOException; +import lombok.extern.slf4j.Slf4j; + +/** + * Main application class demonstrating the Write-Ahead Log (WAL) design pattern. + * + *

The WAL pattern guarantees durability by ensuring every mutation (SET, DELETE) is written to a + * persistent append-only log file on disk BEFORE updating in-memory state. If the system crashes + * unexpectedly, replaying log entries from the WAL file restores state. + */ +@Slf4j +public class App { + + /** + * Application entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + try { + File logFile = File.createTempFile("wal_demo", ".log"); + logFile.deleteOnExit(); + + LOGGER.info( + "=== 1. Initializing Storage Engine with WAL at {} ===", logFile.getAbsolutePath()); + WriteAheadLog wal = new WriteAheadLog(logFile); + DatabaseStore store = new DatabaseStore(wal); + + LOGGER.info("=== 2. Performing Data Operations (Write-Ahead Logging) ==="); + store.put("user:101", "Alice"); + store.put("user:102", "Bob"); + store.put("user:103", "Charlie"); + store.put("user:102", "Bob Smith"); + store.delete("user:103"); + store.checkpoint(); + + LOGGER.info("MemTable snapshot before crash: {}", store.getMemTableSnapshot()); + + LOGGER.info("=== 3. Simulating Unexpected System Crash ==="); + store.simulateCrash(); + LOGGER.info("MemTable snapshot after crash: {}", store.getMemTableSnapshot()); + + LOGGER.info("=== 4. System Restart & Recovery from WAL ==="); + store.recover(); + LOGGER.info("MemTable snapshot post recovery: {}", store.getMemTableSnapshot()); + + if (logFile.exists()) { + logFile.delete(); + } + } catch (IOException e) { + LOGGER.error("An error occurred during WAL demonstration: {}", e.getMessage(), e); + } + } +} diff --git a/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/DatabaseStore.java b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/DatabaseStore.java new file mode 100644 index 000000000000..dd6d94fce7aa --- /dev/null +++ b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/DatabaseStore.java @@ -0,0 +1,131 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** + * Storage engine demonstrating Write-Ahead Log (WAL) pattern. All mutations are logged and flushed + * to persistent WAL storage before modifying the in-memory MemTable. + */ +@Slf4j +public class DatabaseStore { + + @Getter private final WriteAheadLog wal; + private final Map memTable = new HashMap<>(); + + /** + * Constructs DatabaseStore with the specified WriteAheadLog. + * + * @param wal persistent write-ahead log manager + */ + public DatabaseStore(WriteAheadLog wal) { + this.wal = wal; + } + + /** + * Stores a key-value pair. First writes to WAL on disk, then updates the in-memory MemTable. + * + * @param key target entry key + * @param value target entry value + * @throws IOException if writing to WAL fails + */ + public synchronized void put(String key, String value) throws IOException { + wal.append(OperationType.SET, key, value); + memTable.put(key, value); + LOGGER.info("Applied SET operation to MemTable: {} = {}", key, value); + } + + /** + * Removes a key-value pair. First writes DELETE operation to WAL on disk, then updates the + * in-memory MemTable. + * + * @param key target entry key to delete + * @throws IOException if writing to WAL fails + */ + public synchronized void delete(String key) throws IOException { + wal.append(OperationType.DELETE, key, null); + memTable.remove(key); + LOGGER.info("Applied DELETE operation to MemTable: {}", key); + } + + /** + * Retrieves value associated with key from the in-memory MemTable. + * + * @param key key to lookup + * @return value or null if non-existent + */ + public synchronized String get(String key) { + return memTable.get(key); + } + + /** + * Returns an unmodifiable view of current in-memory MemTable state. + * + * @return unmodifiable map of stored data + */ + public synchronized Map getMemTableSnapshot() { + return Collections.unmodifiableMap(new HashMap<>(memTable)); + } + + /** + * Writes a CHECKPOINT log record. + * + * @throws IOException if writing to WAL fails + */ + public synchronized void checkpoint() throws IOException { + wal.append(OperationType.CHECKPOINT, null, null); + LOGGER.info("Checkpoint written to WAL."); + } + + /** Simulates a system crash or power outage where in-memory state is wiped. */ + public synchronized void simulateCrash() { + memTable.clear(); + LOGGER.info("!!! SIMULATED SYSTEM CRASH: In-memory MemTable has been wiped !!!"); + } + + /** Replays log entries from persistent Write-Ahead Log to fully recover in-memory state. */ + public synchronized void recover() { + LOGGER.info("Starting recovery process from WAL..."); + memTable.clear(); + List entries = wal.readAll(); + + for (LogEntry entry : entries) { + if (entry.getType() == OperationType.SET) { + memTable.put(entry.getKey(), entry.getValue()); + } else if (entry.getType() == OperationType.DELETE) { + memTable.remove(entry.getKey()); + } + } + LOGGER.info("Recovery completed. Replayed {} log entries into MemTable.", entries.size()); + } +} diff --git a/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/LogEntry.java b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/LogEntry.java new file mode 100644 index 000000000000..7ae212c8337c --- /dev/null +++ b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/LogEntry.java @@ -0,0 +1,83 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; + +/** Represents a single record entry in the Write-Ahead Log. */ +@Getter +@AllArgsConstructor +@EqualsAndHashCode +@ToString +public class LogEntry { + + private static final String DELIMITER = "|"; + + private final long sequenceNumber; + private final OperationType type; + private final String key; + private final String value; + + /** + * Serializes the LogEntry to a delimited string format suitable for append-only logging. + * + * @return delimited log line representation + */ + public String toLogString() { + return sequenceNumber + + DELIMITER + + type + + DELIMITER + + (key != null ? key : "") + + DELIMITER + + (value != null ? value : ""); + } + + /** + * Deserializes a delimited string line into a LogEntry instance. + * + * @param line serialized log line + * @return parsed LogEntry + * @throws IllegalArgumentException if the log line format is invalid + */ + public static LogEntry fromLogString(String line) { + if (line == null || line.isBlank()) { + throw new IllegalArgumentException("Log line cannot be null or blank"); + } + String[] parts = line.split("\\|", -1); + if (parts.length < 4) { + throw new IllegalArgumentException("Invalid log line format: " + line); + } + long sequenceNumber = Long.parseLong(parts[0]); + OperationType type = OperationType.valueOf(parts[1]); + String key = parts[2].isEmpty() ? null : parts[2]; + String value = parts[3].isEmpty() ? null : parts[3]; + return new LogEntry(sequenceNumber, type, key, value); + } +} diff --git a/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/OperationType.java b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/OperationType.java new file mode 100644 index 000000000000..33e06111bdc4 --- /dev/null +++ b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/OperationType.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +/** Enumeration representing the type of operations logged in the Write-Ahead Log. */ +public enum OperationType { + SET, + DELETE, + CHECKPOINT +} diff --git a/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/WriteAheadLog.java b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/WriteAheadLog.java new file mode 100644 index 000000000000..4ea2044ff2fc --- /dev/null +++ b/write-ahead-log/src/main/java/com/iluwatar/writeaheadlog/WriteAheadLog.java @@ -0,0 +1,134 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** + * Manages sequential append-only logging to persistent disk storage. Ensures state changes are + * flushed to stable storage before in-memory updates. + */ +@Slf4j +public class WriteAheadLog { + + @Getter private final File logFile; + private final AtomicLong sequenceNumberCounter = new AtomicLong(0); + + /** + * Initializes WriteAheadLog with target log file. If log file exists, calculates the initial + * sequence number from existing entries. + * + * @param logFile file to use for append-only log entries + */ + public WriteAheadLog(File logFile) { + this.logFile = logFile; + initSequenceNumber(); + } + + private void initSequenceNumber() { + if (logFile.exists()) { + List existingEntries = readAll(); + if (!existingEntries.isEmpty()) { + long maxSeq = existingEntries.get(existingEntries.size() - 1).getSequenceNumber(); + sequenceNumberCounter.set(maxSeq); + } + } + } + + /** + * Appends an entry to the log file and flushes to ensure persistence. + * + * @param type operation type (SET, DELETE, CHECKPOINT) + * @param key operation target key + * @param value operation target value + * @return recorded LogEntry + * @throws IOException if writing to persistent storage fails + */ + public synchronized LogEntry append(OperationType type, String key, String value) + throws IOException { + long nextSeq = sequenceNumberCounter.incrementAndGet(); + LogEntry entry = new LogEntry(nextSeq, type, key, value); + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true))) { + writer.write(entry.toLogString()); + writer.newLine(); + writer.flush(); + } + LOGGER.info("WAL Entry appended & flushed to disk: {}", entry); + return entry; + } + + /** + * Reads all log entries sequentially from the persistent log file. + * + * @return list of parsed LogEntries in sequential order + */ + public synchronized List readAll() { + List entries = new ArrayList<>(); + if (!logFile.exists()) { + return entries; + } + + try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { + String line; + while ((line = reader.readLine()) != null) { + if (!line.isBlank()) { + entries.add(LogEntry.fromLogString(line)); + } + } + } catch (IOException e) { + LOGGER.error("Failed to read log entries from WAL file: {}", logFile.getAbsolutePath(), e); + } + return entries; + } + + /** + * Clears the log file and resets the sequence number counter. Typically invoked after a + * successful checkpoint. + */ + public synchronized void clear() { + if (logFile.exists()) { + try { + Files.delete(logFile.toPath()); + sequenceNumberCounter.set(0); + LOGGER.info("WAL log cleared successfully."); + } catch (IOException e) { + LOGGER.error("Failed to clear WAL file: {}", logFile.getAbsolutePath(), e); + } + } + } +} diff --git a/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/AppTest.java b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/AppTest.java new file mode 100644 index 000000000000..b3bdbe3360ba --- /dev/null +++ b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void testAppMainExecutesWithoutExceptions() { + assertDoesNotThrow(() -> App.main(new String[0])); + } +} diff --git a/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/DatabaseStoreTest.java b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/DatabaseStoreTest.java new file mode 100644 index 000000000000..08288547348b --- /dev/null +++ b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/DatabaseStoreTest.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class DatabaseStoreTest { + + private File tempFile; + private WriteAheadLog wal; + private DatabaseStore store; + + @BeforeEach + void setUp() throws IOException { + tempFile = File.createTempFile("db_store_test", ".log"); + wal = new WriteAheadLog(tempFile); + store = new DatabaseStore(wal); + } + + @AfterEach + void tearDown() { + if (tempFile != null && tempFile.exists()) { + tempFile.delete(); + } + } + + @Test + void testPutAndGet() throws IOException { + store.put("key1", "val1"); + assertEquals("val1", store.get("key1")); + } + + @Test + void testDelete() throws IOException { + store.put("key1", "val1"); + assertEquals("val1", store.get("key1")); + + store.delete("key1"); + assertNull(store.get("key1")); + } + + @Test + void testSimulateCrashAndRecovery() throws IOException { + store.put("key1", "val1"); + store.put("key2", "val2"); + store.put("key1", "val1_updated"); + store.delete("key2"); + store.checkpoint(); + + Map beforeCrashSnapshot = store.getMemTableSnapshot(); + assertEquals("val1_updated", beforeCrashSnapshot.get("key1")); + assertNull(beforeCrashSnapshot.get("key2")); + + store.simulateCrash(); + assertNull(store.get("key1")); + assertNull(store.get("key2")); + assertTrue(store.getMemTableSnapshot().isEmpty()); + + store.recover(); + Map recoveredSnapshot = store.getMemTableSnapshot(); + assertEquals("val1_updated", recoveredSnapshot.get("key1")); + assertNull(recoveredSnapshot.get("key2")); + } +} diff --git a/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/LogEntryTest.java b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/LogEntryTest.java new file mode 100644 index 000000000000..ea031e04c8a0 --- /dev/null +++ b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/LogEntryTest.java @@ -0,0 +1,80 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class LogEntryTest { + + @Test + void testToLogStringAndFromLogString() { + LogEntry entry = new LogEntry(1, OperationType.SET, "key1", "val1"); + String logString = entry.toLogString(); + assertEquals("1|SET|key1|val1", logString); + + LogEntry parsed = LogEntry.fromLogString(logString); + assertEquals(entry, parsed); + assertEquals(1, parsed.getSequenceNumber()); + assertEquals(OperationType.SET, parsed.getType()); + assertEquals("key1", parsed.getKey()); + assertEquals("val1", parsed.getValue()); + } + + @Test + void testDeleteLogEntrySerialization() { + LogEntry entry = new LogEntry(2, OperationType.DELETE, "key2", null); + String logString = entry.toLogString(); + assertEquals("2|DELETE|key2|", logString); + + LogEntry parsed = LogEntry.fromLogString(logString); + assertEquals(entry, parsed); + assertEquals("key2", parsed.getKey()); + assertNull(parsed.getValue()); + } + + @Test + void testInvalidLogStringThrowsException() { + assertThrows(IllegalArgumentException.class, () -> LogEntry.fromLogString(null)); + assertThrows(IllegalArgumentException.class, () -> LogEntry.fromLogString(" ")); + assertThrows(IllegalArgumentException.class, () -> LogEntry.fromLogString("1|SET|key1")); + } + + @Test + void testEqualsAndHashCode() { + LogEntry entry1 = new LogEntry(1, OperationType.SET, "k", "v"); + LogEntry entry2 = new LogEntry(1, OperationType.SET, "k", "v"); + LogEntry entry3 = new LogEntry(2, OperationType.SET, "k", "v"); + + assertEquals(entry1, entry2); + assertEquals(entry1.hashCode(), entry2.hashCode()); + assertNotEquals(entry1, entry3); + } +} diff --git a/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/WriteAheadLogTest.java b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/WriteAheadLogTest.java new file mode 100644 index 000000000000..8f0410414e3c --- /dev/null +++ b/write-ahead-log/src/test/java/com/iluwatar/writeaheadlog/WriteAheadLogTest.java @@ -0,0 +1,134 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.writeaheadlog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class WriteAheadLogTest { + + private File tempFile; + private WriteAheadLog wal; + + @BeforeEach + void setUp() throws IOException { + tempFile = File.createTempFile("wal_test", ".log"); + wal = new WriteAheadLog(tempFile); + } + + @AfterEach + void tearDown() { + if (tempFile != null && tempFile.exists()) { + if (tempFile.isDirectory()) { + File[] files = tempFile.listFiles(); + if (files != null) { + for (File f : files) { + f.delete(); + } + } + } + tempFile.delete(); + } + } + + @Test + void testAppendAndReadAll() throws IOException { + LogEntry e1 = wal.append(OperationType.SET, "k1", "v1"); + LogEntry e2 = wal.append(OperationType.SET, "k2", "v2"); + LogEntry e3 = wal.append(OperationType.DELETE, "k1", null); + + assertEquals(1, e1.getSequenceNumber()); + assertEquals(2, e2.getSequenceNumber()); + assertEquals(3, e3.getSequenceNumber()); + + List entries = wal.readAll(); + assertEquals(3, entries.size()); + assertEquals(e1, entries.get(0)); + assertEquals(e2, entries.get(1)); + assertEquals(e3, entries.get(2)); + } + + @Test + void testSequenceNumberResumptionOnReopen() throws IOException { + wal.append(OperationType.SET, "k1", "v1"); + wal.append(OperationType.SET, "k2", "v2"); + + WriteAheadLog reopenedWal = new WriteAheadLog(tempFile); + LogEntry newEntry = reopenedWal.append(OperationType.SET, "k3", "v3"); + + assertEquals(3, newEntry.getSequenceNumber()); + } + + @Test + void testClear() throws IOException { + wal.append(OperationType.SET, "k1", "v1"); + assertTrue(tempFile.exists()); + + wal.clear(); + assertFalse(tempFile.exists()); + + List entries = wal.readAll(); + assertNotNull(entries); + assertTrue(entries.isEmpty()); + } + + @Test + void testReadAllIOExceptionHandling() throws IOException { + File dir = Files.createTempDirectory("wal_dir_test").toFile(); + WriteAheadLog dirWal = new WriteAheadLog(dir); + + List entries = dirWal.readAll(); + assertNotNull(entries); + assertTrue(entries.isEmpty()); + + dir.delete(); + } + + @Test + void testClearIOExceptionHandling() throws IOException { + File dir = Files.createTempDirectory("wal_nonempty_dir_test").toFile(); + File child = new File(dir, "child.txt"); + child.createNewFile(); + + WriteAheadLog dirWal = new WriteAheadLog(dir); + dirWal.clear(); + + assertTrue(dir.exists()); + + child.delete(); + dir.delete(); + } +}