diff --git a/.travis.yml b/.travis.yml index a2aaf764b..85f53bcd3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,7 +17,7 @@ install: - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e after_success: -- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarqube.com -Dsonar.login=$SONAR_TOKEN +- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN - bash update-ghpages.sh # use latest java version available instead of travis default @@ -36,4 +36,4 @@ notifications: on_failure: always # options: [always|never|change] default: always on_start: never # options: [always|never|change] default: always -sudo: required \ No newline at end of file +sudo: required diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..097054fe5 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,15 @@ + +Pull request title + +- Clearly and concisely describes what it does +- Refer to the issue that it solves, if available + + +Pull request description + +- Describes the main changes that come with the pull request +- Any relevant additional information is provided + + + +> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute diff --git a/README.md b/README.md index 6eed9561b..03aea2bf6 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ [![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns) [![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) [![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) -[![Quality Gate](https://sonarqube.com/api/badges/gate?key=com.iluwatar%3Ajava-design-patterns)](https://sonarqube.com/dashboard/index/com.iluwatar%3Ajava-design-patterns) +[![Quality Gate](https://sonarcloud.io/api/badges/gate?key=com.iluwatar%3Ajava-design-patterns)](https://sonarcloud.io/dashboard/index/com.iluwatar%3Ajava-design-patterns) +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1503/badge)](https://bestpractices.coreinfrastructure.org/projects/1503) # Introduction diff --git a/_scripts/postPumlsToServer.py b/_scripts/postPumlsToServer.py deleted file mode 100644 index 107ea1988..000000000 --- a/_scripts/postPumlsToServer.py +++ /dev/null @@ -1,67 +0,0 @@ -# -# The MIT License -# Copyright (c) 2014-2016 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. -# - -import requests, glob, re, os - -# taken from here: http://stackoverflow.com/a/13641746 -def replace(file, pattern, subst): - # Read contents from file as a single string - file_handle = open(file, 'r') - file_string = file_handle.read() - file_handle.close() - - # Use RE package to allow for replacement (also allowing for (multiline) REGEX) - file_string = (re.sub(pattern, subst, file_string)) - - # Write contents to file. - # Using mode 'w' truncates the file. - file_handle = open(file, 'w') - file_handle.write(file_string) - file_handle.close() - -# list of all puml files -fileList = glob.glob('*/etc/*.puml') -for puml in fileList: - pathSplit = puml.split("/") - # parent folder - parent = pathSplit[0] - # individual artifact/project name - artifact = pathSplit[2].replace(".urm.puml", "") - print "parent: " + parent + "; artifact: " + artifact - - # do a POST to the official plantuml hosting site with a little trick "!includeurl" and raw github content - data = { - 'text': "!includeurl https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/" + puml - } - r = requests.post('http://plantuml.com/plantuml/uml', data=data) - pumlId = r.url.replace("http://plantuml.com/plantuml/uml/", "") - - # the only thing needed to get a png/svg/ascii from the server back - print "Puml Server ID: " + pumlId - - # add the id so jekyll/liquid can use it - if (parent == artifact): - replace("./" + parent + "/README.md", "categories:", "pumlid: {}\\ncategories:".format(pumlId)) - else: - print "I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file '" + puml + "'\npumlid: {}".format(pumlId) - diff --git a/abstract-document/README.md b/abstract-document/README.md index c8755ce07..2adb3732b 100644 --- a/abstract-document/README.md +++ b/abstract-document/README.md @@ -3,7 +3,6 @@ layout: pattern title: Abstract Document folder: abstract-document permalink: /patterns/abstract-document/ -pumlid: PSjB3eCm34NHhPG599vtDyQn85L-ifzX-p3lxEf8Twj3MXGDQvyJMFubChxpKN767gucSq07iinEjSNDOACVNvoAUZr6MWoe3QVE_WRnxZ0Mf38b-hkIGlurX_MyehS7 categories: Structural tags: - Java @@ -13,8 +12,6 @@ tags: ## Intent Achieve flexibility of untyped languages and keep the type-safety -![alt text](./etc/abstract-document-base.png "Abstract Document Base") - ![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") diff --git a/abstract-document/etc/abstract-document-base.png b/abstract-document/etc/abstract-document-base.png deleted file mode 100644 index 13345dbb8..000000000 Binary files a/abstract-document/etc/abstract-document-base.png and /dev/null differ diff --git a/abstract-document/etc/abstract-document-base.ucls b/abstract-document/etc/abstract-document-base.ucls deleted file mode 100644 index bfe927ed9..000000000 --- a/abstract-document/etc/abstract-document-base.ucls +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/abstract-document/etc/abstract-document.png b/abstract-document/etc/abstract-document.png index 98d186f7e..6bc0b29a4 100644 Binary files a/abstract-document/etc/abstract-document.png and b/abstract-document/etc/abstract-document.png differ diff --git a/abstract-document/etc/abstract-document.ucls b/abstract-document/etc/abstract-document.ucls index ad97457fd..f555394d0 100644 --- a/abstract-document/etc/abstract-document.ucls +++ b/abstract-document/etc/abstract-document.ucls @@ -1,91 +1,137 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + - - - - - - - + + + - - - + + + - + - + + + + + + + + + + + + + + + + + - - - + + + + + + + diff --git a/abstract-document/etc/abstract-document.urm.puml b/abstract-document/etc/abstract-document.urm.puml deleted file mode 100644 index 0c6ffc5ec..000000000 --- a/abstract-document/etc/abstract-document.urm.puml +++ /dev/null @@ -1,59 +0,0 @@ -@startuml -package com.iluwatar.abstractdocument.domain { - class Car { - + Car(properties : Map) - } - interface HasModel { - + PROPERTY : String {static} - + getModel() : Optional - } - interface HasParts { - + PROPERTY : String {static} - + getParts() : Stream - } - interface HasPrice { - + PROPERTY : String {static} - + getPrice() : Optional - } - interface HasType { - + PROPERTY : String {static} - + getType() : Optional - } - class Part { - + Part(properties : Map) - } -} -package com.iluwatar.abstractdocument { - abstract class AbstractDocument { - - properties : Map - # AbstractDocument(properties : Map) - + children(key : String, constructor : Function, T>) : Stream - + get(key : String) : Object - + put(key : String, value : Object) - + toString() : String - } - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - interface Document { - + children(String, Function, T>) : Stream {abstract} - + get(String) : Object {abstract} - + put(String, Object) {abstract} - } -} -AbstractDocument ..|> Document -Car ..|> HasModel -Car ..|> HasPrice -Car ..|> HasParts -Car --|> AbstractDocument -HasModel --|> Document -HasParts --|> Document -HasPrice --|> Document -HasType --|> Document -Part ..|> HasType -Part ..|> HasModel -Part ..|> HasPrice -Part --|> AbstractDocument -@enduml \ No newline at end of file diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index 42d439afd..a249f0d07 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -29,13 +29,18 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT abstract-document - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java index f6686ff8f..63a9974b9 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.abstractdocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; @@ -30,8 +30,8 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * AbstractDocument test class diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java index b91f57b27..0546be523 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.abstractdocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Simple App test diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java index 03d75d5e5..891e5a457 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -28,13 +28,13 @@ import com.iluwatar.abstractdocument.domain.HasParts; import com.iluwatar.abstractdocument.domain.HasPrice; import com.iluwatar.abstractdocument.domain.HasType; import com.iluwatar.abstractdocument.domain.Part; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import static junit.framework.TestCase.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Part and Car diff --git a/abstract-factory/README.md b/abstract-factory/README.md index 25b63f7a2..423988b58 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -3,7 +3,6 @@ layout: pattern title: Abstract Factory folder: abstract-factory permalink: /patterns/abstract-factory/ -pumlid: PSZB3OD034NHLa81Czwd6sCC39gVxEUWT1_ssLmTtQLqgR5fM7sTmFGtaV6TZu8prd0r6HtQaMKqAZLk1XjT_E6qgPUZfyc0MdTgx0-8LuUn8ErFXdr98NypXxKyezKV categories: Creational tags: - Java @@ -120,6 +119,45 @@ king.getDescription(); // Output: This is the Elven king! army.getDescription(); // Output: This is the Elven Army! ``` +Now, we can design a factory for our different kingdom factories. In this example, we created FactoryMaker, responsible for returning an instance of either ElfKingdomFactory or OrcKingdomFactory. +The client can use FactoryMaker to create the desired concrete factory which, in turn, will produce different concrete objects (Army, King, Castle). +In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for. + +``` +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + switch (type) { + case ELF: + return new ElfKingdomFactory(); + case ORC: + return new OrcKingdomFactory(); + default: + throw new IllegalArgumentException("KingdomType not supported."); + } + } +} + +public static void main(String[] args) { + App app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + -- similar use of the orc factory +} +``` + + ## Applicability Use the Abstract Factory pattern when @@ -141,9 +179,15 @@ Use the Abstract Factory pattern when * Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time. + ## Tutorial * [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) +## Presentations + +* [Abstract Factory Pattern](etc/presentation.html) + + ## Real world examples * [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) diff --git a/abstract-factory/etc/diagram1.png b/abstract-factory/etc/diagram1.png new file mode 100644 index 000000000..e9c3c84c2 Binary files /dev/null and b/abstract-factory/etc/diagram1.png differ diff --git a/abstract-factory/etc/diagram2.png b/abstract-factory/etc/diagram2.png new file mode 100644 index 000000000..2ab524535 Binary files /dev/null and b/abstract-factory/etc/diagram2.png differ diff --git a/abstract-factory/etc/presentation.html b/abstract-factory/etc/presentation.html new file mode 100644 index 000000000..9e549faf8 --- /dev/null +++ b/abstract-factory/etc/presentation.html @@ -0,0 +1,190 @@ + + + + + Design Patterns - Abstract Factory Presentation + + + + + + + + + \ No newline at end of file diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index 4c7e51be2..073879acc 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT abstract-factory - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java index d7cb296c0..4d6043abc 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -25,6 +25,8 @@ package com.iluwatar.abstractfactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; + /** * * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme @@ -56,7 +58,7 @@ public class App { setCastle(factory.createCastle()); setArmy(factory.createArmy()); } - + King getKing(final KingdomFactory factory) { return factory.createKing(); } @@ -92,9 +94,36 @@ public class App { private void setArmy(final Army army) { this.army = army; } - + /** - * Program entry point + * The factory of kingdom factories. + */ + public static class FactoryMaker { + + /** + * Enumeration for the different types of Kingdoms. + */ + public enum KingdomType { + ELF, ORC + } + + /** + * The factory method to create KingdomFactory concrete objects. + */ + public static KingdomFactory makeFactory(KingdomType type) { + switch (type) { + case ELF: + return new ElfKingdomFactory(); + case ORC: + return new OrcKingdomFactory(); + default: + throw new IllegalArgumentException("KingdomType not supported."); + } + } + } + + /** + * Program entry point. * * @param args * command line args @@ -104,17 +133,15 @@ public class App { App app = new App(); LOGGER.info("Elf Kingdom"); - app.createKingdom(new ElfKingdomFactory()); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); LOGGER.info(app.getArmy().getDescription()); LOGGER.info(app.getCastle().getDescription()); LOGGER.info(app.getKing().getDescription()); LOGGER.info("Orc Kingdom"); - app.createKingdom(new OrcKingdomFactory()); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); LOGGER.info(app.getArmy().getDescription()); LOGGER.info(app.getCastle().getDescription()); LOGGER.info(app.getKing().getDescription()); - } - -} +} \ No newline at end of file diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java index b6fca8b23..5940da6c1 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -22,11 +22,14 @@ */ package com.iluwatar.abstractfactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Before; -import org.junit.Test; +import com.iluwatar.abstractfactory.App.FactoryMaker; +import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test for abstract factory @@ -37,10 +40,10 @@ public class AbstractFactoryTest { private KingdomFactory elfFactory; private KingdomFactory orcFactory; - @Before + @BeforeEach public void setUp() { - elfFactory = new ElfKingdomFactory(); - orcFactory = new OrcKingdomFactory(); + elfFactory = FactoryMaker.makeFactory(KingdomType.ELF); + orcFactory = FactoryMaker.makeFactory(KingdomType.ORC); } @Test diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java index b9d5f7d90..80c2815dc 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.abstractfactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/adapter/README.md b/adapter/README.md index 6de04a72c..3344490ff 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -3,7 +3,6 @@ layout: pattern title: Adapter folder: adapter permalink: /patterns/adapter/ -pumlid: DSR14S8m30J0Lg20M7-wEMnDOiPMFDA9j0yyUEtUkzMHJTF7xI1NF4GSLzaxZtncgDVJgCPIpobzv0N2vOKtjgRHTziMI7KBcOXl10thfxB-Nz9dMJd71m00 categories: Structural tags: - Java diff --git a/adapter/pom.xml b/adapter/pom.xml index 44259f1c6..95b9a3e99 100644 --- a/adapter/pom.xml +++ b/adapter/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT adapter - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java index 9938f0559..033440b81 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -22,8 +22,8 @@ */ package com.iluwatar.adapter; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -46,7 +46,7 @@ public class AdapterPatternTest { /** * This method runs before the test execution and sets the bean objects in the beans Map. */ - @Before + @BeforeEach public void setup() { beans = new HashMap<>(); diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java index 213035627..ca2c103c3 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.adapter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/aggregator-microservices/README.md b/aggregator-microservices/README.md index 75fe373fd..e65f26d9a 100644 --- a/aggregator-microservices/README.md +++ b/aggregator-microservices/README.md @@ -3,7 +3,6 @@ layout: pattern title: Aggregator Microservices folder: aggregator-microservices permalink: /patterns/aggregator-microservices/ -pumlid: JOov3SCm301NIGQGs7iRXYPa1g8ayB7NjuiKwGvtmBrbKC-Tq_hhY5Y-0HXUjKaS-Kbdepc2HrIQ2jBpma23BvvOTdPfeooCO1iEYlu0O6l63MDQKI6Rp-CKOWSE-ey_NzEqhjH-0m00 categories: Architectural tags: - Java diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml index 078e38d30..d338f47b9 100644 --- a/aggregator-microservices/aggregator-service/pom.xml +++ b/aggregator-microservices/aggregator-service/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -54,8 +54,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java index 2955f6781..bc07ccc21 100644 --- a/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java +++ b/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java @@ -22,15 +22,15 @@ */ package com.iluwatar.aggregator.microservices; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + /** * Test Aggregation of domain objects */ @@ -45,7 +45,7 @@ public class AggregatorTest { @Mock private ProductInventoryClient inventoryClient; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } diff --git a/aggregator-microservices/etc/aggregator-service.urm.puml b/aggregator-microservices/etc/aggregator-service.urm.puml deleted file mode 100644 index ebb782f20..000000000 --- a/aggregator-microservices/etc/aggregator-service.urm.puml +++ /dev/null @@ -1,43 +0,0 @@ -@startuml -package com.iluwatar.aggregator.microservices { - class Aggregator { - - informationClient : ProductInformationClient - - inventoryClient : ProductInventoryClient - + Aggregator() - + getProduct() : Product - } - class App { - + App() - + main(args : String[]) {static} - } - class Product { - - productInventories : int - - title : String - + Product() - + getProductInventories() : int - + getTitle() : String - + setProductInventories(productInventories : int) - + setTitle(title : String) - } - interface ProductInformationClient { - + getProductTitle() : String {abstract} - } - class ProductInformationClientImpl { - - LOGGER : Logger {static} - + ProductInformationClientImpl() - + getProductTitle() : String - } - interface ProductInventoryClient { - + getProductInventories() : int {abstract} - } - class ProductInventoryClientImpl { - - LOGGER : Logger {static} - + ProductInventoryClientImpl() - + getProductInventories() : int - } -} -Aggregator --> "-informationClient" ProductInformationClient -Aggregator --> "-inventoryClient" ProductInventoryClient -ProductInformationClientImpl ..|> ProductInformationClient -ProductInventoryClientImpl ..|> ProductInventoryClient -@enduml \ No newline at end of file diff --git a/aggregator-microservices/etc/information-microservice.urm.puml b/aggregator-microservices/etc/information-microservice.urm.puml deleted file mode 100644 index e0a2ccb24..000000000 --- a/aggregator-microservices/etc/information-microservice.urm.puml +++ /dev/null @@ -1,12 +0,0 @@ -@startuml -package com.iluwatar.information.microservice { - class InformationApplication { - + InformationApplication() - + main(args : String[]) {static} - } - class InformationController { - + InformationController() - + getProductTitle() : String - } -} -@enduml \ No newline at end of file diff --git a/aggregator-microservices/etc/inventory-microservice.urm.puml b/aggregator-microservices/etc/inventory-microservice.urm.puml deleted file mode 100644 index 90f327e07..000000000 --- a/aggregator-microservices/etc/inventory-microservice.urm.puml +++ /dev/null @@ -1,12 +0,0 @@ -@startuml -package com.iluwatar.inventory.microservice { - class InventoryApplication { - + InventoryApplication() - + main(args : String[]) {static} - } - class InventoryController { - + InventoryController() - + getProductInventories() : int - } -} -@enduml \ No newline at end of file diff --git a/aggregator-microservices/information-microservice/pom.xml b/aggregator-microservices/information-microservice/pom.xml index f379afa27..3879681b7 100644 --- a/aggregator-microservices/information-microservice/pom.xml +++ b/aggregator-microservices/information-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -54,8 +54,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java b/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java index 127dd3956..d030cfcb4 100644 --- a/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java +++ b/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java @@ -22,8 +22,9 @@ */ package com.iluwatar.information.microservice; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Information Rest Controller @@ -36,7 +37,7 @@ public class InformationControllerTest { String title = infoController.getProductTitle(); - Assert.assertEquals("The Product Title.", title); + assertEquals("The Product Title.", title); } } diff --git a/aggregator-microservices/inventory-microservice/pom.xml b/aggregator-microservices/inventory-microservice/pom.xml index 8db0814c9..3f212e2e9 100644 --- a/aggregator-microservices/inventory-microservice/pom.xml +++ b/aggregator-microservices/inventory-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -54,8 +54,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java b/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java index b04370fba..78af8582e 100644 --- a/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java +++ b/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java @@ -22,8 +22,9 @@ */ package com.iluwatar.inventory.microservice; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Inventory Rest Controller @@ -35,6 +36,6 @@ public class InventoryControllerTest { int numberOfInventories = inventoryController.getProductInventories(); - Assert.assertEquals(5, numberOfInventories); + assertEquals(5, numberOfInventories); } } diff --git a/aggregator-microservices/pom.xml b/aggregator-microservices/pom.xml index caf600e86..364b02566 100644 --- a/aggregator-microservices/pom.xml +++ b/aggregator-microservices/pom.xml @@ -29,32 +29,11 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 aggregator-microservices pom - - - - - com.github.markusmo3.urm - urm-maven-plugin - ${urm.version} - - ${project.basedir}/../etc - - com.iluwatar - - - - aggregator-microservices - - - - - - information-microservice aggregator-service diff --git a/api-gateway/README.md b/api-gateway/README.md index 93b975e13..23014ae0b 100644 --- a/api-gateway/README.md +++ b/api-gateway/README.md @@ -3,7 +3,6 @@ layout: pattern title: API Gateway folder: api-gateway permalink: /patterns/api-gateway/ -pumlid: JSox3SCm303HLP819FRUXg49cO542_nOyFPncUvUSszHwhbpMdyT4TCt0CDLcyIHdtGsEZLOez8vG7ek33JuueLbPvUcPM84cpeCz2S0fvI6mGjluA1_b-Tt2N5D6tNcw3y0 categories: Architectural tags: - Java diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml index 372c4d0dd..a035f11a2 100644 --- a/api-gateway/api-gateway-service/pom.xml +++ b/api-gateway/api-gateway-service/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 api-gateway-service @@ -53,8 +53,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java index 6a79e5d00..a86d991c8 100644 --- a/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java +++ b/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java @@ -22,15 +22,15 @@ */ package com.iluwatar.api.gateway; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + /** * Test API Gateway Pattern */ @@ -45,7 +45,7 @@ public class ApiGatewayTest { @Mock private PriceClient priceClient; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } diff --git a/api-gateway/etc/api-gateway-service.urm.puml b/api-gateway/etc/api-gateway-service.urm.puml deleted file mode 100644 index 5fabc6a0f..000000000 --- a/api-gateway/etc/api-gateway-service.urm.puml +++ /dev/null @@ -1,48 +0,0 @@ -@startuml -package com.iluwatar.api.gateway { - class ApiGateway { - - imageClient : ImageClient - - priceClient : PriceClient - + ApiGateway() - + getProductDesktop() : DesktopProduct - + getProductMobile() : MobileProduct - } - class App { - + App() - + main(args : String[]) {static} - } - class DesktopProduct { - - imagePath : String - - price : String - + DesktopProduct() - + getImagePath() : String - + getPrice() : String - + setImagePath(imagePath : String) - + setPrice(price : String) - } - interface ImageClient { - + getImagePath() : String {abstract} - } - class ImageClientImpl { - + ImageClientImpl() - + getImagePath() : String - } - class MobileProduct { - - price : String - + MobileProduct() - + getPrice() : String - + setPrice(price : String) - } - interface PriceClient { - + getPrice() : String {abstract} - } - class PriceClientImpl { - + PriceClientImpl() - + getPrice() : String - } -} -ApiGateway --> "-imageClient" ImageClient -ApiGateway --> "-priceClient" PriceClient -ImageClientImpl ..|> ImageClient -PriceClientImpl ..|> PriceClient -@enduml \ No newline at end of file diff --git a/api-gateway/etc/image-microservice.urm.puml b/api-gateway/etc/image-microservice.urm.puml deleted file mode 100644 index 130dac9de..000000000 --- a/api-gateway/etc/image-microservice.urm.puml +++ /dev/null @@ -1,12 +0,0 @@ -@startuml -package com.iluwatar.image.microservice { - class ImageApplication { - + ImageApplication() - + main(args : String[]) {static} - } - class ImageController { - + ImageController() - + getImagePath() : String - } -} -@enduml \ No newline at end of file diff --git a/api-gateway/etc/price-microservice.urm.puml b/api-gateway/etc/price-microservice.urm.puml deleted file mode 100644 index 9893c9c60..000000000 --- a/api-gateway/etc/price-microservice.urm.puml +++ /dev/null @@ -1,12 +0,0 @@ -@startuml -package com.iluwatar.price.microservice { - class PriceApplication { - + PriceApplication() - + main(args : String[]) {static} - } - class PriceController { - + PriceController() - + getPrice() : String - } -} -@enduml \ No newline at end of file diff --git a/api-gateway/image-microservice/pom.xml b/api-gateway/image-microservice/pom.xml index 50fc12886..ad248943d 100644 --- a/api-gateway/image-microservice/pom.xml +++ b/api-gateway/image-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -54,8 +54,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java b/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java index 1b934014a..df9b479ae 100644 --- a/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java +++ b/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java @@ -22,8 +22,9 @@ */ package com.iluwatar.image.microservice; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Image Rest Controller @@ -35,6 +36,6 @@ public class ImageControllerTest { String imagePath = imageController.getImagePath(); - Assert.assertEquals("/product-image.png", imagePath); + assertEquals("/product-image.png", imagePath); } } diff --git a/api-gateway/pom.xml b/api-gateway/pom.xml index f474ba66a..c151d59a1 100644 --- a/api-gateway/pom.xml +++ b/api-gateway/pom.xml @@ -29,32 +29,11 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 api-gateway pom - - - - - com.github.markusmo3.urm - urm-maven-plugin - ${urm.version} - - ${project.basedir}/../etc - - com.iluwatar - - - - api-gateway - - - - - - image-microservice price-microservice diff --git a/api-gateway/price-microservice/pom.xml b/api-gateway/price-microservice/pom.xml index ec6799674..cdd8b4c3c 100644 --- a/api-gateway/price-microservice/pom.xml +++ b/api-gateway/price-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -54,8 +54,13 @@ spring-boot-starter-web - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java b/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java index b1fe66d42..679fb601b 100644 --- a/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java +++ b/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.price.microservice; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Price Rest Controller @@ -36,6 +36,6 @@ public class PriceControllerTest { String price = priceController.getPrice(); - Assert.assertEquals("20", price); + assertEquals("20", price); } } diff --git a/async-method-invocation/README.md b/async-method-invocation/README.md index b96c1d77a..2d99820c5 100644 --- a/async-method-invocation/README.md +++ b/async-method-invocation/README.md @@ -3,7 +3,6 @@ layout: pattern title: Async Method Invocation folder: async-method-invocation permalink: /patterns/async-method-invocation/ -pumlid: TSdB3SCW303GLTe1mFTkunWhk0A3_4dKxTi5UdlIUuhIoCPfuz4Zjhy03EzwIlGyqjbeQR16fJL1HjuOQF362qjZbrFBnWWsTPZeFm3wHwbCZhvQ4RqMOSXIuA1_LzDctJd75m00 categories: Concurrency tags: - Java diff --git a/async-method-invocation/etc/async-method-invocation.urm.puml b/async-method-invocation/etc/async-method-invocation.urm.puml deleted file mode 100644 index 6f5d0b27f..000000000 --- a/async-method-invocation/etc/async-method-invocation.urm.puml +++ /dev/null @@ -1,51 +0,0 @@ -@startuml -package com.iluwatar.async.method.invocation { - class App { - - LOGGER : Logger {static} - + App() - - callback(name : String) : AsyncCallback {static} - - lazyval(value : T, delayMillis : long) : Callable {static} - - log(msg : String) {static} - + main(args : String[]) {static} - } - interface AsyncCallback { - + onComplete(T, Optional) {abstract} - } - interface AsyncExecutor { - + endProcess(AsyncResult) : T {abstract} - + startProcess(Callable) : AsyncResult {abstract} - + startProcess(Callable, AsyncCallback) : AsyncResult {abstract} - } - interface AsyncResult { - + await() {abstract} - + getValue() : T {abstract} - + isCompleted() : boolean {abstract} - } - class ThreadAsyncExecutor { - - idx : AtomicInteger - + ThreadAsyncExecutor() - + endProcess(asyncResult : AsyncResult) : T - + startProcess(task : Callable) : AsyncResult - + startProcess(task : Callable, callback : AsyncCallback) : AsyncResult - } - -class CompletableResult { - ~ COMPLETED : int {static} - ~ FAILED : int {static} - ~ RUNNING : int {static} - ~ callback : Optional> - ~ exception : Exception - ~ lock : Object - ~ state : int - ~ value : T - ~ CompletableResult(callback : AsyncCallback) - + await() - + getValue() : T - + isCompleted() : boolean - ~ setException(exception : Exception) - ~ setValue(value : T) - } -} -CompletableResult ..+ ThreadAsyncExecutor -ThreadAsyncExecutor ..|> AsyncExecutor -CompletableResult ..|> AsyncResult -@enduml \ No newline at end of file diff --git a/async-method-invocation/pom.xml b/async-method-invocation/pom.xml index af169c14f..a686e3e68 100644 --- a/async-method-invocation/pom.xml +++ b/async-method-invocation/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT async-method-invocation - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java index ef2649f8a..a2744306e 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.async.method.invocation; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java index d0e730344..b5c4fff67 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.async.method.invocation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; @@ -30,8 +30,21 @@ import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static java.time.Duration.ofMillis; +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; /** @@ -44,205 +57,217 @@ public class ThreadAsyncExecutorTest { /** * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} */ - @Test(timeout = 3000) + @Test public void testSuccessfulTaskWithoutCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenReturn(result); + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - // Our task should only execute once ... - verify(task, times(1)).call(); + // Our task should only execute once ... + verify(task, times(1)).call(); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} */ - @Test(timeout = 3000) + @Test public void testSuccessfulTaskWithCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenReturn(result); + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - // Our task should only execute once ... - verify(task, times(1)).call(); + // Our task should only execute once ... + verify(task, times(1)).call(); - // ... same for the callback, we expect our object - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); + // ... same for the callback, we expect our object + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertFalse(optionalException.isPresent()); + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while * to execute */ - @Test(timeout = 5000) + @Test public void testLongRunningTaskWithoutCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); }); - - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); - - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); } /** * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task * takes a while to execute */ - @Test(timeout = 5000) + @Test public void testLongRunningTaskWithCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + verifyZeroInteractions(callback); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task, callback); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); }); - - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - verifyZeroInteractions(callback); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); - - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); - - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertFalse(optionalException.isPresent()); - - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task, callback); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); } /** * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} */ - @Test(timeout = 5000) + @Test public void testEndProcess() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + assertSame(result, executor.endProcess(asyncResult)); + verify(task, times(1)).call(); + assertTrue(asyncResult.isCompleted()); + + // Calling end process a second time while already finished should give the same result + assertSame(result, executor.endProcess(asyncResult)); + verifyNoMoreInteractions(task); }); - - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - assertSame(result, executor.endProcess(asyncResult)); - verify(task, times(1)).call(); - assertTrue(asyncResult.isCompleted()); - - // Calling end process a second time while already finished should give the same result - assertSame(result, executor.endProcess(asyncResult)); - verifyNoMoreInteractions(task); } /** * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' */ - @Test(timeout = 3000) + @Test public void testNullTask() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncResult asyncResult = executor.startProcess(null); + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null); - assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } @@ -250,36 +275,38 @@ public class ThreadAsyncExecutorTest { * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the * callable is 'null', but the asynchronous callback is provided */ - @Test(timeout = 3000) + @Test public void testNullTaskWithCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(null, callback); + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(null, callback); - assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertTrue(optionalException.isPresent()); + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertTrue(optionalException.isPresent()); - final Exception exception = optionalException.get(); - assertNotNull(exception); - assertEquals(NullPointerException.class, exception.getClass()); + final Exception exception = optionalException.get(); + assertNotNull(exception); + assertEquals(NullPointerException.class, exception.getClass()); - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } @@ -287,24 +314,29 @@ public class ThreadAsyncExecutorTest { * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both * the callable and the asynchronous callback are 'null' */ - @Test(timeout = 3000) + @Test public void testNullTaskWithNullCallback() throws Exception { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncResult asyncResult = executor.startProcess(null, null); + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null, null); - assertNotNull("The AsyncResult should not be 'null', even though the task and callback were 'null'.", asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task and callback were 'null'." + ); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } diff --git a/balking/README.md b/balking/README.md index f720c0d02..fb5c83d5b 100644 --- a/balking/README.md +++ b/balking/README.md @@ -18,10 +18,10 @@ incomplete or inappropriate state ## Applicability Use the Balking pattern when -*you want to invoke an action on an object only when it is in a particular state -*objects are generally only in a state that is prone to balking temporarily +* you want to invoke an action on an object only when it is in a particular state +* objects are generally only in a state that is prone to balking temporarily but for an unknown amount of time ## Related patterns * Guarded Suspension Pattern -* Double Checked Locking Pattern \ No newline at end of file +* Double Checked Locking Pattern diff --git a/balking/etc/balking.urm.puml b/balking/etc/balking.urm.puml deleted file mode 100644 index b0296b925..000000000 --- a/balking/etc/balking.urm.puml +++ /dev/null @@ -1,24 +0,0 @@ -@startuml -package com.iluwatar.balking { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class WashingMachine { - - LOGGER : Logger {static} - - washingMachineState : WashingMachineState - + WashingMachine() - + endOfWashing() - + getWashingMachineState() : WashingMachineState - + wash() - } - enum WashingMachineState { - + ENABLED {static} - + WASHING {static} - + valueOf(name : String) : WashingMachineState {static} - + values() : WashingMachineState[] {static} - } -} -WashingMachine --> "-washingMachineState" WashingMachineState -@enduml \ No newline at end of file diff --git a/balking/pom.xml b/balking/pom.xml index a924eae43..276dc397d 100644 --- a/balking/pom.xml +++ b/balking/pom.xml @@ -29,15 +29,20 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 balking - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/balking/src/test/java/com/iluwatar/balking/AppTest.java b/balking/src/test/java/com/iluwatar/balking/AppTest.java index df104b901..87941dc27 100644 --- a/balking/src/test/java/com/iluwatar/balking/AppTest.java +++ b/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -23,7 +23,7 @@ package com.iluwatar.balking; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application test diff --git a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java index ecf81f409..47957835d 100644 --- a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java +++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.balking; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link WashingMachine} diff --git a/bridge/README.md b/bridge/README.md index a53e6143f..bce723971 100644 --- a/bridge/README.md +++ b/bridge/README.md @@ -3,7 +3,6 @@ layout: pattern title: Bridge folder: bridge permalink: /patterns/bridge/ -pumlid: BSR14SCm20J0Lf82BFxf1akCJ4R26ZZYzkE7zxLljJgoIVfu7S2A3v7pLRhYo3r3l9u6CPHwJjAH5uETllpZhKbejsqn86v1a-CExQwj2mdgqv8-oyev_W00 categories: Structural tags: - Java diff --git a/bridge/pom.xml b/bridge/pom.xml index 5a807bbdd..0cef80258 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT bridge - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java index fcf7e44ce..233f1d481 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.bridge; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java index a650bae04..4cb3bd69e 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -22,11 +22,10 @@ */ package com.iluwatar.bridge; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; /** * Tests for hammer diff --git a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java index 7ffd0e492..e1cccb39a 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -22,11 +22,10 @@ */ package com.iluwatar.bridge; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; /** * Tests for sword diff --git a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java index daec1014a..e8518eb50 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -22,10 +22,11 @@ */ package com.iluwatar.bridge; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Disabled; + +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.internal.verification.VerificationModeFactory.times; /** * Base class for weapon tests @@ -44,15 +45,15 @@ public abstract class WeaponTest { assertNotNull(weapon.getEnchantment()); weapon.swing(); - verify(enchantment, times(1)).apply(); + verify(enchantment).apply(); verifyNoMoreInteractions(enchantment); weapon.wield(); - verify(enchantment, times(1)).onActivate(); + verify(enchantment).onActivate(); verifyNoMoreInteractions(enchantment); weapon.unwield(); - verify(enchantment, times(1)).onDeactivate(); + verify(enchantment).onDeactivate(); verifyNoMoreInteractions(enchantment); } diff --git a/builder/README.md b/builder/README.md index d255ec2f6..51495619b 100644 --- a/builder/README.md +++ b/builder/README.md @@ -3,7 +3,6 @@ layout: pattern title: Builder folder: builder permalink: /patterns/builder/ -pumlid: DSR94O0m2030LhG0mzzkC64KXs26GzlNZw_TcRLADagJwOWOlW8OFcNdE79B9wkN1ccKUdLWoGS33KwySMdalEioC89C7Jhw5zYIfNrIrFybhPUHNLu0 categories: Creational tags: - Java diff --git a/builder/pom.xml b/builder/pom.xml index 0c4d44bdc..a7d5c9d70 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT builder - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/builder/src/test/java/com/iluwatar/builder/AppTest.java b/builder/src/test/java/com/iluwatar/builder/AppTest.java index b30c50cda..abaaa034f 100644 --- a/builder/src/test/java/com/iluwatar/builder/AppTest.java +++ b/builder/src/test/java/com/iluwatar/builder/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.builder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/builder/src/test/java/com/iluwatar/builder/HeroTest.java index c111fb853..aa2e1490f 100644 --- a/builder/src/test/java/com/iluwatar/builder/HeroTest.java +++ b/builder/src/test/java/com/iluwatar/builder/HeroTest.java @@ -22,10 +22,11 @@ */ package com.iluwatar.builder; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Date: 12/6/15 - 11:01 PM @@ -37,17 +38,17 @@ public class HeroTest { /** * Test if we get the expected exception when trying to create a hero without a profession */ - @Test(expected = IllegalArgumentException.class) + @Test public void testMissingProfession() throws Exception { - new Hero.Builder(null, "Sir without a job"); + assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job")); } /** * Test if we get the expected exception when trying to create a hero without a name */ - @Test(expected = IllegalArgumentException.class) + @Test public void testMissingName() throws Exception { - new Hero.Builder(Profession.THIEF, null); + assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null)); } /** diff --git a/business-delegate/README.md b/business-delegate/README.md index 8e6e3456c..e6e249122 100644 --- a/business-delegate/README.md +++ b/business-delegate/README.md @@ -3,7 +3,6 @@ layout: pattern title: Business Delegate folder: business-delegate permalink: /patterns/business-delegate/ -pumlid: POl13SCm3CHMQGU8zUysgYCuBcJ5a4x9-l6_Fu84tzsgvYxf-Zg06HyYvxkqZYE_6UBrD8YXr7DGrxmPxFJZYxTTeZVR9WFY5ZGu5j2wkad4wYgD8IIe_xQaZp9pw0C0 categories: Business Tier tags: - Java diff --git a/business-delegate/etc/business-delegate.urm.puml b/business-delegate/etc/business-delegate.urm.puml deleted file mode 100644 index 40aa2d6f0..000000000 --- a/business-delegate/etc/business-delegate.urm.puml +++ /dev/null @@ -1,57 +0,0 @@ -@startuml -package com.iluwatar.business.delegate { - class App { - + App() - + main(args : String[]) {static} - } - class BusinessDelegate { - - businessService : BusinessService - - lookupService : BusinessLookup - - serviceType : ServiceType - + BusinessDelegate() - + doTask() - + setLookupService(businessLookup : BusinessLookup) - + setServiceType(serviceType : ServiceType) - } - class BusinessLookup { - - ejbService : EjbService - - jmsService : JmsService - + BusinessLookup() - + getBusinessService(serviceType : ServiceType) : BusinessService - + setEjbService(ejbService : EjbService) - + setJmsService(jmsService : JmsService) - } - interface BusinessService { - + doProcessing() {abstract} - } - class Client { - - businessDelegate : BusinessDelegate - + Client(businessDelegate : BusinessDelegate) - + doTask() - } - class EjbService { - - LOGGER : Logger {static} - + EjbService() - + doProcessing() - } - class JmsService { - - LOGGER : Logger {static} - + JmsService() - + doProcessing() - } - enum ServiceType { - + EJB {static} - + JMS {static} - + valueOf(name : String) : ServiceType {static} - + values() : ServiceType[] {static} - } -} -BusinessLookup --> "-ejbService" EjbService -BusinessDelegate --> "-serviceType" ServiceType -Client --> "-businessDelegate" BusinessDelegate -BusinessDelegate --> "-businessService" BusinessService -BusinessDelegate --> "-lookupService" BusinessLookup -BusinessLookup --> "-jmsService" JmsService -EjbService ..|> BusinessService -JmsService ..|> BusinessService -@enduml \ No newline at end of file diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index db04484a4..0bc02827b 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -30,13 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT business-delegate - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java index d02109d37..415f855d1 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.business.delegate; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java index 48d576319..ccdaaae4e 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.business.delegate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import org.junit.Before; -import org.junit.Test; - /** * The Business Delegate pattern adds an abstraction layer between the presentation and business * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate @@ -53,7 +53,7 @@ public class BusinessDelegateTest { * This method sets up the instance variables of this test class. It is executed before the * execution of every test. */ - @Before + @BeforeEach public void setup() { ejbService = spy(new EjbService()); jmsService = spy(new JmsService()); diff --git a/caching/README.md b/caching/README.md index b48d060f0..7184d51d4 100644 --- a/caching/README.md +++ b/caching/README.md @@ -3,7 +3,6 @@ layout: pattern title: Caching folder: caching permalink: /patterns/caching/ -pumlid: DSRB4OKm2030LhG0m_rrWyWaE0bc-6ZxpujxsbMKUXwSrfSMCVq7OFYKAj5oJsUZIuCr2bq3fEU3WGOdthWTx59rcnZ1fWu3_GqGKXEjm47VIzeeCqV_0m00 categories: Other tags: - Java diff --git a/caching/etc/caching.urm.puml b/caching/etc/caching.urm.puml deleted file mode 100644 index 6ac3fd4cc..000000000 --- a/caching/etc/caching.urm.puml +++ /dev/null @@ -1,110 +0,0 @@ -@startuml -package com.iluwatar.caching { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - + useCacheAsideStategy() - + useReadAndWriteThroughStrategy() - + useReadThroughAndWriteAroundStrategy() - + useReadThroughAndWriteBehindStrategy() - } - class AppManager { - - cachingPolicy : CachingPolicy {static} - - AppManager() - + find(userId : String) : UserAccount {static} - - findAside(userId : String) : UserAccount {static} - + initCacheCapacity(capacity : int) {static} - + initCachingPolicy(policy : CachingPolicy) {static} - + initDb(useMongoDb : boolean) {static} - + printCacheContent() : String {static} - + save(userAccount : UserAccount) {static} - - saveAside(userAccount : UserAccount) {static} - } - class CacheStore { - - LOGGER : Logger {static} - ~ cache : LruCache {static} - - CacheStore() - + clearCache() {static} - + flushCache() {static} - + get(userId : String) : UserAccount {static} - + initCapacity(capacity : int) {static} - + invalidate(userId : String) {static} - + print() : String {static} - + readThrough(userId : String) : UserAccount {static} - + readThroughWithWriteBackPolicy(userId : String) : UserAccount {static} - + set(userId : String, userAccount : UserAccount) {static} - + writeAround(userAccount : UserAccount) {static} - + writeBehind(userAccount : UserAccount) {static} - + writeThrough(userAccount : UserAccount) {static} - } - enum CachingPolicy { - + AROUND {static} - + ASIDE {static} - + BEHIND {static} - + THROUGH {static} - - policy : String - + getPolicy() : String - + valueOf(name : String) : CachingPolicy {static} - + values() : CachingPolicy[] {static} - } - class DbManager { - - db : MongoDatabase {static} - - mongoClient : MongoClient {static} - - useMongoDB : boolean {static} - - virtualDB : Map {static} - - DbManager() - + connect() {static} - + createVirtualDb() {static} - + readFromDb(userId : String) : UserAccount {static} - + updateDb(userAccount : UserAccount) {static} - + upsertDb(userAccount : UserAccount) {static} - + writeToDb(userAccount : UserAccount) {static} - } - class LruCache { - - LOGGER : Logger {static} - ~ cache : Map - ~ capacity : int - ~ end : Node - ~ head : Node - + LruCache(capacity : int) - + clear() - + contains(userId : String) : boolean - + get(userId : String) : UserAccount - + getCacheDataInListForm() : List - + getLruData() : UserAccount - + invalidate(userId : String) - + isFull() : boolean - + remove(node : Node) - + set(userId : String, userAccount : UserAccount) - + setCapacity(newCapacity : int) - + setHead(node : Node) - } - ~class Node { - ~ next : Node - ~ previous : Node - ~ userAccount : UserAccount - ~ userId : String - + Node(this$0 : String, userId : UserAccount) - } - class UserAccount { - - additionalInfo : String - - userId : String - - userName : String - + UserAccount(userId : String, userName : String, additionalInfo : String) - + getAdditionalInfo() : String - + getUserId() : String - + getUserName() : String - + setAdditionalInfo(additionalInfo : String) - + setUserId(userId : String) - + setUserName(userName : String) - + toString() : String - } -} -LruCache --> "-head" Node -Node --+ LruCache -Node --> "-previous" Node -AppManager --> "-cachingPolicy" CachingPolicy -Node --> "-userAccount" UserAccount -CacheStore --> "-cache" LruCache -@enduml \ No newline at end of file diff --git a/caching/pom.xml b/caching/pom.xml index 1da9a33d3..f76778840 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT caching - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/caching/src/test/java/com/iluwatar/caching/AppTest.java b/caching/src/test/java/com/iluwatar/caching/AppTest.java index 3ac513033..32935bf24 100644 --- a/caching/src/test/java/com/iluwatar/caching/AppTest.java +++ b/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.caching; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/caching/src/test/java/com/iluwatar/caching/CachingTest.java index 4d8dea7a4..0a7e8aed3 100644 --- a/caching/src/test/java/com/iluwatar/caching/CachingTest.java +++ b/caching/src/test/java/com/iluwatar/caching/CachingTest.java @@ -22,8 +22,8 @@ */ package com.iluwatar.caching; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @@ -36,7 +36,7 @@ public class CachingTest { /** * Setup of application test includes: initializing DB connection and cache size/capacity. */ - @Before + @BeforeEach public void setUp() { AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests // to avoid Maven compilation errors. Set flag to true to run the diff --git a/callback/README.md b/callback/README.md index 278aa9b0a..a408fd5e0 100644 --- a/callback/README.md +++ b/callback/README.md @@ -3,7 +3,6 @@ layout: pattern title: Callback folder: callback permalink: /patterns/callback/ -pumlid: FSVB4S8m30N0Lg20M7UwUL4qYOciUFGXxSE9s-wp6sjjKgwF8tF6YyXnjxtdKMk5E5-MOjdu6jIrRYIStlXWsIJwRij4fhW53SGFn51TmIT9yZ-jVBHPGxy0 categories: Other tags: - Java diff --git a/callback/etc/callback.urm.puml b/callback/etc/callback.urm.puml deleted file mode 100644 index 02545e80f..000000000 --- a/callback/etc/callback.urm.puml +++ /dev/null @@ -1,28 +0,0 @@ -@startuml -package com.iluwatar.callback { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - interface Callback { - + call() {abstract} - } - class LambdasApp { - - LOGGER : Logger {static} - + LambdasApp() - + main(args : String[]) {static} - } - class SimpleTask { - - LOGGER : Logger {static} - + SimpleTask() - + execute() - } - abstract class Task { - + Task() - + execute() {abstract} - + executeWith(callback : Callback) - } -} -SimpleTask --|> Task -@enduml \ No newline at end of file diff --git a/callback/pom.xml b/callback/pom.xml index b4ece4579..aa1039789 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT callback - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/callback/src/test/java/com/iluwatar/callback/AppTest.java b/callback/src/test/java/com/iluwatar/callback/AppTest.java index 9e3355f47..bb9b698d4 100644 --- a/callback/src/test/java/com/iluwatar/callback/AppTest.java +++ b/callback/src/test/java/com/iluwatar/callback/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.callback; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java index d6f804f45..7a14b0a4a 100644 --- a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java +++ b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.callback; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Add a field as a counter. Every time the callback method is called increment this field. Unit @@ -47,15 +47,15 @@ public class CallbackTest { Task task = new SimpleTask(); - assertEquals("Initial calling count of 0", new Integer(0), callingCount); + assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); task.executeWith(callback); - assertEquals("Callback called once", new Integer(1), callingCount); + assertEquals(new Integer(1), callingCount, "Callback called once"); task.executeWith(callback); - assertEquals("Callback called twice", new Integer(2), callingCount); + assertEquals(new Integer(2), callingCount, "Callback called twice"); } @@ -65,15 +65,15 @@ public class CallbackTest { Task task = new SimpleTask(); - assertEquals("Initial calling count of 0", new Integer(0), callingCount); + assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); task.executeWith(callback); - assertEquals("Callback called once", new Integer(1), callingCount); + assertEquals(new Integer(1), callingCount, "Callback called once"); task.executeWith(callback); - assertEquals("Callback called twice", new Integer(2), callingCount); + assertEquals(new Integer(2), callingCount, "Callback called twice"); } } diff --git a/chain/README.md b/chain/README.md index 1d7eb5b73..6bca81610 100644 --- a/chain/README.md +++ b/chain/README.md @@ -3,7 +3,6 @@ layout: pattern title: Chain of responsibility folder: chain permalink: /patterns/chain/ -pumlid: 9SR13SCm20NGLTe1OkxTXX0KKzd4Wa-pVYlrdTxJN4OTMZ4U7LZv8Wg-ssdejLTgoELGHvDhaesw6HpqvWzlXwQTlYq6D3nfSlv2qjcS5F9VgvXjrHnV categories: Behavioral tags: - Java diff --git a/chain/pom.xml b/chain/pom.xml index f35faf468..51c83f1ae 100644 --- a/chain/pom.xml +++ b/chain/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT chain - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/chain/src/test/java/com/iluwatar/chain/AppTest.java b/chain/src/test/java/com/iluwatar/chain/AppTest.java index 2a3b6b197..577221bac 100644 --- a/chain/src/test/java/com/iluwatar/chain/AppTest.java +++ b/chain/src/test/java/com/iluwatar/chain/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.chain; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java b/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java index 208e6ecb6..c7cfb687c 100644 --- a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java +++ b/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.chain; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/6/15 - 9:29 PM @@ -49,8 +49,8 @@ public class OrcKingTest { for (final Request request : REQUESTS) { king.makeRequest(request); assertTrue( - "Expected all requests from King to be handled, but [" + request + "] was not!", - request.isHandled() + request.isHandled(), + "Expected all requests from King to be handled, but [" + request + "] was not!" ); } diff --git a/checkstyle.xml b/checkstyle.xml index 37db7e711..e5c12ac3a 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -85,9 +85,7 @@ value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/> - - - + @@ -181,7 +179,7 @@ - + diff --git a/command/README.md b/command/README.md index 3996d2842..614654f5b 100644 --- a/command/README.md +++ b/command/README.md @@ -3,7 +3,6 @@ layout: pattern title: Command folder: command permalink: /patterns/command/ -pumlid: DSgn4OCm30NGLM00h3xR25i7vYpXaxx2-g59zugtTgiZcwIFvGHcV8YSdt9qdBbdYDVR88PIRwK-yc6mqyLVtff4FsoR38XRa7Aye3SgMoD1_RkaQvcfumS0 categories: Behavioral tags: - Java @@ -37,6 +36,10 @@ Use the Command pattern when you want to * implement callback functionality * implement the undo functionality +## Presentations + +* [Command Pattern](etc/presentation.html) + ## Real world examples * [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) diff --git a/command/etc/command.urm.puml b/command/etc/command.urm.puml deleted file mode 100644 index 9bdbce64d..000000000 --- a/command/etc/command.urm.puml +++ /dev/null @@ -1,86 +0,0 @@ -@startuml -package com.iluwatar.command { - class App { - + App() - + main(args : String[]) {static} - } - abstract class Command { - + Command() - + execute(Target) {abstract} - + redo() {abstract} - + toString() : String {abstract} - + undo() {abstract} - } - class Goblin { - + Goblin() - + toString() : String - } - class InvisibilitySpell { - - target : Target - + InvisibilitySpell() - + execute(target : Target) - + redo() - + toString() : String - + undo() - } - class ShrinkSpell { - - oldSize : Size - - target : Target - + ShrinkSpell() - + execute(target : Target) - + redo() - + toString() : String - + undo() - } - enum Size { - + LARGE {static} - + NORMAL {static} - + SMALL {static} - + UNDEFINED {static} - - title : String - + toString() : String - + valueOf(name : String) : Size {static} - + values() : Size[] {static} - } - abstract class Target { - - LOGGER : Logger {static} - - size : Size - - visibility : Visibility - + Target() - + getSize() : Size - + getVisibility() : Visibility - + printStatus() - + setSize(size : Size) - + setVisibility(visibility : Visibility) - + toString() : String {abstract} - } - enum Visibility { - + INVISIBLE {static} - + UNDEFINED {static} - + VISIBLE {static} - - title : String - + toString() : String - + valueOf(name : String) : Visibility {static} - + values() : Visibility[] {static} - } - class Wizard { - - LOGGER : Logger {static} - - redoStack : Deque - - undoStack : Deque - + Wizard() - + castSpell(command : Command, target : Target) - + redoLastSpell() - + toString() : String - + undoLastSpell() - } -} -Target --> "-size" Size -Wizard --> "-undoStack" Command -ShrinkSpell --> "-oldSize" Size -InvisibilitySpell --> "-target" Target -ShrinkSpell --> "-target" Target -Target --> "-visibility" Visibility -Goblin --|> Target -InvisibilitySpell --|> Command -ShrinkSpell --|> Command -@enduml \ No newline at end of file diff --git a/command/etc/diagram.png b/command/etc/diagram.png new file mode 100644 index 000000000..1d3494292 Binary files /dev/null and b/command/etc/diagram.png differ diff --git a/command/etc/presentation.html b/command/etc/presentation.html new file mode 100644 index 000000000..88a3f0c66 --- /dev/null +++ b/command/etc/presentation.html @@ -0,0 +1,243 @@ + + + + + Design Patterns - Command Presentation + + + + + + + + + \ No newline at end of file diff --git a/command/pom.xml b/command/pom.xml index 3612dd8aa..9a819bb6c 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT command - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/command/src/main/java/com/iluwatar/command/Size.java index 1e72474cc..25f94a101 100644 --- a/command/src/main/java/com/iluwatar/command/Size.java +++ b/command/src/main/java/com/iluwatar/command/Size.java @@ -29,7 +29,7 @@ package com.iluwatar.command; */ public enum Size { - SMALL("small"), NORMAL("normal"), LARGE("large"), UNDEFINED(""); + SMALL("small"), NORMAL("normal"); private String title; diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java index 802927b9d..8c360d534 100644 --- a/command/src/main/java/com/iluwatar/command/Visibility.java +++ b/command/src/main/java/com/iluwatar/command/Visibility.java @@ -29,7 +29,7 @@ package com.iluwatar.command; */ public enum Visibility { - VISIBLE("visible"), INVISIBLE("invisible"), UNDEFINED(""); + VISIBLE("visible"), INVISIBLE("invisible"); private String title; diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index 501676984..866ea0e0f 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -40,7 +40,9 @@ public class Wizard { private Deque undoStack = new LinkedList<>(); private Deque redoStack = new LinkedList<>(); - public Wizard() {} + public Wizard() { + // comment to ignore sonar issue: LEVEL critical + } /** * Cast spell diff --git a/command/src/test/java/com/iluwatar/command/AppTest.java b/command/src/test/java/com/iluwatar/command/AppTest.java index 5b4b742d8..eb0cf0f8a 100644 --- a/command/src/test/java/com/iluwatar/command/AppTest.java +++ b/command/src/test/java/com/iluwatar/command/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.command; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/command/src/test/java/com/iluwatar/command/CommandTest.java b/command/src/test/java/com/iluwatar/command/CommandTest.java index 5c3fa6fe1..b3a3f48d0 100644 --- a/command/src/test/java/com/iluwatar/command/CommandTest.java +++ b/command/src/test/java/com/iluwatar/command/CommandTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.command; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all @@ -81,13 +81,13 @@ public class CommandTest { * @param goblin a goblin object whose state is to be verified against other parameters * @param expectedName expectedName of the goblin * @param expectedSize expected size of the goblin - * @param expectedVisibilty exepcted visibility of the goblin + * @param expectedVisibility expected visibility of the goblin */ private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, - Visibility expectedVisibilty) { - assertEquals("Goblin's name must be same as expectedName", expectedName, goblin.toString()); - assertEquals("Goblin's size must be same as expectedSize", expectedSize, goblin.getSize()); - assertEquals("Goblin's visibility must be same as expectedVisibility", expectedVisibilty, - goblin.getVisibility()); + Visibility expectedVisibility) { + assertEquals(expectedName, goblin.toString(), "Goblin's name must be same as expectedName"); + assertEquals(expectedSize, goblin.getSize(), "Goblin's size must be same as expectedSize"); + assertEquals(expectedVisibility, goblin.getVisibility(), + "Goblin's visibility must be same as expectedVisibility"); } } diff --git a/composite/README.md b/composite/README.md index fbb21ecb3..e4f45ddd0 100644 --- a/composite/README.md +++ b/composite/README.md @@ -3,7 +3,6 @@ layout: pattern title: Composite folder: composite permalink: /patterns/composite/ -pumlid: HSf13eCm30NHgy01YFUzZGaM62LEP7-NwvTTT_EaMTLgoqFIst81Cpv4payv5LVk6U9r6CHGwkYaBHy6EztyvUsGqDEsoO2u1NMED-WTvmY5aA3-LT9xcTdR3m00 categories: Structural tags: - Java diff --git a/composite/pom.xml b/composite/pom.xml index 62f07c8d5..eb3b5d7b4 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT composite - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/composite/src/test/java/com/iluwatar/composite/AppTest.java b/composite/src/test/java/com/iluwatar/composite/AppTest.java index 0862d5c20..76e0220c9 100644 --- a/composite/src/test/java/com/iluwatar/composite/AppTest.java +++ b/composite/src/test/java/com/iluwatar/composite/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.composite; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java index 3746b236a..3911382be 100644 --- a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java +++ b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java @@ -22,15 +22,15 @@ */ package com.iluwatar.composite; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/11/15 - 8:12 PM @@ -52,7 +52,7 @@ public class MessengerTest { /** * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test */ - @Before + @BeforeEach public void setUp() { this.stdOutBuffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOutBuffer)); @@ -61,7 +61,7 @@ public class MessengerTest { /** * Removed the mocked std-out {@link PrintStream} again from the {@link System} class */ - @After + @AfterEach public void tearDown() { System.setOut(realStdOut); } diff --git a/converter/README.md b/converter/README.md index 190ae8bfc..79b539422 100644 --- a/converter/README.md +++ b/converter/README.md @@ -3,7 +3,7 @@ layout: pattern title: Converter folder: converter permalink: /patterns/converter/ -categories: +categories: Business Tier tags: - Java - Difficulty-Beginner diff --git a/converter/etc/converter.urm.puml b/converter/etc/converter.urm.puml deleted file mode 100644 index 5e0acf191..000000000 --- a/converter/etc/converter.urm.puml +++ /dev/null @@ -1,49 +0,0 @@ -@startuml -package com.iluwatar.converter { - class App { - + App() - + main(args : String[]) {static} - } - class Converter { - - fromDto : Function - - fromEntity : Function - + Converter(fromDto : Function, fromEntity : Function) - + convertFromDto(userDto : T) : U - + convertFromEntity(user : U) : T - + createFromDtos(dtoUsers : Collection) : List - + createFromEntities(users : Collection) : List - } - class User { - - firstName : String - - isActive : boolean - - lastName : String - - userId : String - + User(firstName : String, lastName : String, isActive : boolean, userId : String) - + equals(o : Object) : boolean - + getFirstName() : String - + getLastName() : String - + getUserId() : String - + hashCode() : int - + isActive() : boolean - + toString() : String - } - class UserConverter { - + UserConverter() - } - class UserDto { - - email : String - - firstName : String - - isActive : boolean - - lastName : String - + UserDto(firstName : String, lastName : String, isActive : boolean, email : String) - + equals(o : Object) : boolean - + getEmail() : String - + getFirstName() : String - + getLastName() : String - + hashCode() : int - + isActive() : boolean - + toString() : String - } -} -UserConverter --|> Converter -@enduml \ No newline at end of file diff --git a/converter/pom.xml b/converter/pom.xml index 6bd1c5c16..69005d7d6 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -29,13 +29,18 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java index fbae0309d..6e436706d 100644 --- a/converter/src/main/java/com/iluwatar/converter/App.java +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -41,10 +41,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - Converter userConverter = new Converter<>( - userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), - userDto.getEmail()), - user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId())); + Converter userConverter = new UserConverter(); UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); User user = userConverter.convertFromDto(dtoUser); diff --git a/converter/src/main/java/com/iluwatar/converter/Converter.java b/converter/src/main/java/com/iluwatar/converter/Converter.java index eeabc4102..918d2d503 100644 --- a/converter/src/main/java/com/iluwatar/converter/Converter.java +++ b/converter/src/main/java/com/iluwatar/converter/Converter.java @@ -68,7 +68,7 @@ public class Converter { /** * @param dtoUsers collection of DTO entities * @return List of domain representation of provided entities retrieved by - * mapping each of them with the convertion function + * mapping each of them with the conversion function */ public final List createFromDtos(final Collection dtoUsers) { return dtoUsers.stream().map(this::convertFromDto).collect(Collectors.toList()); @@ -77,7 +77,7 @@ public class Converter { /** * @param users collection of domain entities * @return List of domain representation of provided entities retrieved by - * mapping each of them with the convertion function + * mapping each of them with the conversion function */ public final List createFromEntities(final Collection users) { return users.stream().map(this::convertFromEntity).collect(Collectors.toList()); diff --git a/converter/src/test/java/com/iluwatar/converter/AppTest.java b/converter/src/test/java/com/iluwatar/converter/AppTest.java index 091fbe2ca..1617beeb4 100644 --- a/converter/src/test/java/com/iluwatar/converter/AppTest.java +++ b/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.converter; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * App running test diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java index 9fc2e2a0c..f5c41256d 100644 --- a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java +++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -23,13 +23,13 @@ package com.iluwatar.converter; import com.google.common.collect.Lists; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; -import static junit.framework.TestCase.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link Converter} @@ -41,7 +41,8 @@ public class ConverterTest { /** * Tests whether a converter created of opposite functions holds equality as a bijection. */ - @Test public void testConversionsStartingFromDomain() { + @Test + public void testConversionsStartingFromDomain() { User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); assertEquals(u1, u2); @@ -50,7 +51,8 @@ public class ConverterTest { /** * Tests whether a converter created of opposite functions holds equality as a bijection. */ - @Test public void testConversionsStartingFromDto() { + @Test + public void testConversionsStartingFromDto() { UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); assertEquals(u1, u2); @@ -60,7 +62,8 @@ public class ConverterTest { * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and * cleanly instantiated allowing various different conversion strategies to be implemented. */ - @Test public void testCustomConverter() { + @Test + public void testCustomConverter() { Converter converter = new Converter<>( userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), String.valueOf(new Random().nextInt())), @@ -75,7 +78,8 @@ public class ConverterTest { * Test whether converting a collection of Users to DTO Users and then converting them back to domain * users returns an equal collection. */ - @Test public void testCollectionConversion() { + @Test + public void testCollectionConversion() { ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); List fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); diff --git a/cqrs/README.md b/cqrs/README.md index 3cdd429a1..111c1ccd4 100644 --- a/cqrs/README.md +++ b/cqrs/README.md @@ -3,7 +3,6 @@ layout: pattern title: CQRS folder: cqrs permalink: /patterns/cqrs/ -pumlid: 7SPR4a0m3030gt00pR_RH6I8QQFouFgC_TfHb6gkd5Q7FQBx363ub4rYpoMTZKuDrYXqDX37HIuuyCPfPPTDfuuHREhGqBy0NUR0GNzAMYizMtq1 categories: Architectural tags: - Java diff --git a/cqrs/etc/cqrs.urm.puml b/cqrs/etc/cqrs.urm.puml deleted file mode 100644 index 6dd65dd3a..000000000 --- a/cqrs/etc/cqrs.urm.puml +++ /dev/null @@ -1,124 +0,0 @@ -@startuml -package com.iluwatar.cqrs.util { - class HibernateUtil { - - LOGGER : Logger {static} - - SESSIONFACTORY : SessionFactory {static} - + HibernateUtil() - - buildSessionFactory() : SessionFactory {static} - + getSessionFactory() : SessionFactory {static} - } -} -package com.iluwatar.cqrs.app { - class App { - + App() - + main(args : String[]) {static} - } -} -package com.iluwatar.cqrs.dto { - class Author { - - email : String - - name : String - - username : String - + Author() - + Author(name : String, email : String, username : String) - + equals(obj : Object) : boolean - + getEmail() : String - + getName() : String - + getUsername() : String - + hashCode() : int - + toString() : String - } - class Book { - - price : double - - title : String - + Book() - + Book(title : String, price : double) - + equals(obj : Object) : boolean - + getPrice() : double - + getTitle() : String - + hashCode() : int - + toString() : String - } -} -package com.iluwatar.cqrs.commandes { - class CommandServiceImpl { - - sessionFactory : SessionFactory - + CommandServiceImpl() - + authorCreated(username : String, name : String, email : String) - + authorEmailUpdated(username : String, email : String) - + authorNameUpdated(username : String, name : String) - + authorUsernameUpdated(oldUsername : String, newUsername : String) - + bookAddedToAuthor(title : String, price : double, username : String) - + bookPriceUpdated(title : String, price : double) - + bookTitleUpdated(oldTitle : String, newTitle : String) - - getAuthorByUsername(username : String) : Author - - getBookByTitle(title : String) : Book - } - interface ICommandService { - + authorCreated(String, String, String) {abstract} - + authorEmailUpdated(String, String) {abstract} - + authorNameUpdated(String, String) {abstract} - + authorUsernameUpdated(String, String) {abstract} - + bookAddedToAuthor(String, double, String) {abstract} - + bookPriceUpdated(String, double) {abstract} - + bookTitleUpdated(String, String) {abstract} - } -} -package com.iluwatar.cqrs.queries { - interface IQueryService { - + getAuthorBooks(String) : List {abstract} - + getAuthorBooksCount(String) : BigInteger {abstract} - + getAuthorByUsername(String) : Author {abstract} - + getAuthorsCount() : BigInteger {abstract} - + getBook(String) : Book {abstract} - } - class QueryServiceImpl { - - sessionFactory : SessionFactory - + QueryServiceImpl() - + getAuthorBooks(username : String) : List - + getAuthorBooksCount(username : String) : BigInteger - + getAuthorByUsername(username : String) : Author - + getAuthorsCount() : BigInteger - + getBook(title : String) : Book - } -} -package com.iluwatar.cqrs.domain.model { - class Author { - - email : String - - id : long - - name : String - - username : String - # Author() - + Author(username : String, name : String, email : String) - + getEmail() : String - + getId() : long - + getName() : String - + getUsername() : String - + setEmail(email : String) - + setId(id : long) - + setName(name : String) - + setUsername(username : String) - + toString() : String - } - class Book { - - author : Author - - id : long - - price : double - - title : String - # Book() - + Book(title : String, price : double, author : Author) - + getAuthor() : Author - + getId() : long - + getPrice() : double - + getTitle() : String - + setAuthor(author : Author) - + setId(id : long) - + setPrice(price : double) - + setTitle(title : String) - + toString() : String - } -} -Book --> "-author" Author -CommandServiceImpl ..|> ICommandService -QueryServiceImpl ..|> IQueryService -@enduml \ No newline at end of file diff --git a/cqrs/pom.xml b/cqrs/pom.xml index 6c036a933..2ed0809f6 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -21,13 +21,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT cqrs - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java index 1d110cb59..9825de9f7 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java @@ -50,14 +50,12 @@ public class Author { * email of the author */ public Author(String username, String name, String email) { - super(); this.username = username; this.name = name; this.email = email; } protected Author() { - super(); } public long getId() { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java index 8d9ba0ca3..8a11fcdd4 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java @@ -43,7 +43,7 @@ public class Book { private Author author; /** - * + * * @param title * title of the book * @param price @@ -52,14 +52,12 @@ public class Book { * author of the book */ public Book(String title, double price, Author author) { - super(); this.title = title; this.price = price; this.author = author; } protected Book() { - super(); } public long getId() { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java index 34d082e86..c5473354d 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java @@ -45,14 +45,12 @@ public class Author { * username of the author */ public Author(String name, String email, String username) { - super(); this.name = name; this.email = email; this.username = username; } public Author() { - super(); } public String getName() { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java index ff4d258af..f121a2ca7 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java @@ -42,13 +42,11 @@ public class Book { * price of the book */ public Book(String title, double price) { - super(); this.title = title; this.price = price; } public Book() { - super(); } public String getTitle() { diff --git a/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java index dd10f658d..536418cbe 100644 --- a/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java +++ b/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java @@ -22,21 +22,20 @@ */ package com.iluwatar.cqrs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.math.BigInteger; import java.util.List; -import org.junit.BeforeClass; -import org.junit.Test; - import com.iluwatar.cqrs.commandes.CommandServiceImpl; import com.iluwatar.cqrs.commandes.ICommandService; import com.iluwatar.cqrs.dto.Author; import com.iluwatar.cqrs.dto.Book; import com.iluwatar.cqrs.queries.IQueryService; import com.iluwatar.cqrs.queries.QueryServiceImpl; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Integration test of IQueryService and ICommandService with h2 data @@ -47,14 +46,11 @@ public class IntegrationTest { private static IQueryService queryService; private static ICommandService commandService; - @BeforeClass - public static void initialize() { + @BeforeAll + public static void initializeAndPopulateDatabase() { commandService = new CommandServiceImpl(); queryService = new QueryServiceImpl(); - } - @BeforeClass - public static void populateDatabase() { // create first author1 commandService.authorCreated("username1", "name1", "email1"); @@ -94,7 +90,7 @@ public class IntegrationTest { public void testGetBook() { Book book = queryService.getBook("title1"); assertEquals("title1", book.getTitle()); - assertEquals(10, book.getPrice(), 0); + assertEquals(10, book.getPrice(), 0.01); } @Test diff --git a/dao/README.md b/dao/README.md index b1b655edf..785a1c362 100644 --- a/dao/README.md +++ b/dao/README.md @@ -3,7 +3,6 @@ layout: pattern title: Data Access Object folder: dao permalink: /patterns/dao/ -pumlid: 5SR14OKW30N0LhG0oVrt4o6ZE12Ov4NR_thQNQlc5aN2sd82qtz4naywAixOmyNoK8WYvT6fjdWOR7JnpLiHhuTkam4nTUhiRwZm847-J64zpUZj3m00 categories: Persistence Tier tags: - Java diff --git a/dao/etc/dao.urm.puml b/dao/etc/dao.urm.puml deleted file mode 100644 index b0a5b2c54..000000000 --- a/dao/etc/dao.urm.puml +++ /dev/null @@ -1,66 +0,0 @@ -@startuml -package com.iluwatar.dao { - class App { - - DB_URL : String {static} - - log : Logger {static} - + App() - - addCustomers(customerDao : CustomerDao) {static} - - createDataSource() : DataSource {static} - - createSchema(dataSource : DataSource) {static} - - deleteSchema(dataSource : DataSource) {static} - + generateSampleCustomers() : List {static} - + main(args : String[]) {static} - - performOperationsUsing(customerDao : CustomerDao) {static} - } - class Customer { - - firstName : String - - id : int - - lastName : String - + Customer(id : int, firstName : String, lastName : String) - + equals(that : Object) : boolean - + getFirstName() : String - + getId() : int - + getLastName() : String - + hashCode() : int - + setFirstName(firstName : String) - + setId(id : int) - + setLastName(lastName : String) - + toString() : String - } - interface CustomerDao { - + add(Customer) : boolean {abstract} - + delete(Customer) : boolean {abstract} - + getAll() : Stream {abstract} - + getById(int) : Optional {abstract} - + update(Customer) : boolean {abstract} - } - class CustomerSchemaSql { - + CREATE_SCHEMA_SQL : String {static} - + DELETE_SCHEMA_SQL : String {static} - - CustomerSchemaSql() - } - class DbCustomerDao { - - dataSource : DataSource - + DbCustomerDao(dataSource : DataSource) - + add(customer : Customer) : boolean - - createCustomer(resultSet : ResultSet) : Customer - + delete(customer : Customer) : boolean - + getAll() : Stream - + getById(id : int) : Optional - - getConnection() : Connection - - mutedClose(connection : Connection) - + update(customer : Customer) : boolean - } - class InMemoryCustomerDao { - - idToCustomer : Map - + InMemoryCustomerDao() - + add(customer : Customer) : boolean - + delete(customer : Customer) : boolean - + getAll() : Stream - + getById(id : int) : Optional - + update(customer : Customer) : boolean - } -} -DbCustomerDao ..|> CustomerDao -InMemoryCustomerDao ..|> CustomerDao -@enduml \ No newline at end of file diff --git a/dao/pom.xml b/dao/pom.xml index e61eaba3c..621af6baf 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -30,14 +30,19 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT dao - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test @@ -48,10 +53,6 @@ com.h2database h2 - - de.bechte.junit - junit-hierarchicalcontextrunner - org.mockito mockito-core diff --git a/dao/src/test/java/com/iluwatar/dao/AppTest.java b/dao/src/test/java/com/iluwatar/dao/AppTest.java index 73534eb02..75ef59f18 100644 --- a/dao/src/test/java/com/iluwatar/dao/AppTest.java +++ b/dao/src/test/java/com/iluwatar/dao/AppTest.java @@ -23,7 +23,7 @@ package com.iluwatar.dao; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that DAO example runs without errors. diff --git a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java index 8122c369f..1a55e3beb 100644 --- a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java +++ b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -23,11 +23,11 @@ package com.iluwatar.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests {@link Customer}. @@ -39,7 +39,7 @@ public class CustomerTest { private static final String FIRSTNAME = "Winston"; private static final String LASTNAME = "Churchill"; - @Before + @BeforeEach public void setUp() { customer = new Customer(ID, FIRSTNAME, LASTNAME); } diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java index 213aef206..80920aa37 100644 --- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java +++ b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -22,38 +22,32 @@ */ package com.iluwatar.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; +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; +import javax.sql.DataSource; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.stream.Stream; -import javax.sql.DataSource; - -import org.h2.jdbcx.JdbcDataSource; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; - -import de.bechte.junit.runners.context.HierarchicalContextRunner; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; /** * Tests {@link DbCustomerDao}. */ -@RunWith(HierarchicalContextRunner.class) public class DbCustomerDaoTest { private static final String DB_URL = "jdbc:h2:~/dao"; @@ -64,7 +58,7 @@ public class DbCustomerDaoTest { * Creates customers schema. * @throws SQLException if there is any error while creating schema. */ - @Before + @BeforeEach public void createSchema() throws SQLException { try (Connection connection = DriverManager.getConnection(DB_URL); Statement statement = connection.createStatement()) { @@ -75,13 +69,14 @@ public class DbCustomerDaoTest { /** * Represents the scenario where DB connectivity is present. */ + @Nested public class ConnectionSuccess { /** * Setup for connection success scenario. * @throws Exception if any error occurs. */ - @Before + @BeforeEach public void setUp() throws Exception { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); @@ -93,6 +88,7 @@ public class DbCustomerDaoTest { /** * Represents the scenario when DAO operations are being performed on a non existing customer. */ + @Nested public class NonExistingCustomer { @Test @@ -141,6 +137,7 @@ public class DbCustomerDaoTest { * customer. * */ + @Nested public class ExistingCustomer { @Test @@ -184,20 +181,18 @@ public class DbCustomerDaoTest { * DB service unavailable. * */ + @Nested public class ConnectivityIssue { private static final String EXCEPTION_CAUSE = "Connection not available"; - @Rule public ExpectedException exception = ExpectedException.none(); - + /** * setup a connection failure scenario. * @throws SQLException if any error occurs. */ - @Before + @BeforeEach public void setUp() throws SQLException { dao = new DbCustomerDao(mockedDatasource()); - exception.expect(Exception.class); - exception.expectMessage(EXCEPTION_CAUSE); } private DataSource mockedDatasource() throws SQLException { @@ -210,31 +205,40 @@ public class DbCustomerDaoTest { } @Test - public void addingACustomerFailsWithExceptionAsFeedbackToClient() throws Exception { - dao.add(new Customer(2, "Bernard", "Montgomery")); + public void addingACustomerFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.add(new Customer(2, "Bernard", "Montgomery")); + }); } @Test - public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() throws Exception { - dao.delete(existingCustomer); + public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { + assertThrows(Exception.class, () -> { + dao.delete(existingCustomer); + }); } @Test - public void updatingACustomerFailsWithFeedbackToTheClient() throws Exception { + public void updatingACustomerFailsWithFeedbackToTheClient() { final String newFirstname = "Bernard"; final String newLastname = "Montgomery"; - - dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); + assertThrows(Exception.class, () -> { + dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); + }); } @Test - public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() throws Exception { - dao.getById(existingCustomer.getId()); + public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.getById(existingCustomer.getId()); + }); } @Test - public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() throws Exception { - dao.getAll(); + public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.getAll(); + }); } } @@ -243,7 +247,7 @@ public class DbCustomerDaoTest { * Delete customer schema for fresh setup per test. * @throws SQLException if any error occurs. */ - @After + @AfterEach public void deleteSchema() throws SQLException { try (Connection connection = DriverManager.getConnection(DB_URL); Statement statement = connection.createStatement()) { diff --git a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java index 2532b2fad..7cb14b0b1 100644 --- a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java +++ b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -23,31 +23,27 @@ package com.iluwatar.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import java.util.Optional; import java.util.stream.Stream; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import de.bechte.junit.runners.context.HierarchicalContextRunner; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Tests {@link InMemoryCustomerDao}. */ -@RunWith(HierarchicalContextRunner.class) public class InMemoryCustomerDaoTest { private InMemoryCustomerDao dao; private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); - @Before + @BeforeEach public void setUp() { dao = new InMemoryCustomerDao(); assertTrue(dao.add(CUSTOMER)); @@ -57,6 +53,7 @@ public class InMemoryCustomerDaoTest { * Represents the scenario when the DAO operations are being performed on a non existent * customer. */ + @Nested public class NonExistingCustomer { @Test @@ -104,6 +101,7 @@ public class InMemoryCustomerDaoTest { * Represents the scenario when the DAO operations are being performed on an already existing * customer. */ + @Nested public class ExistingCustomer { @Test diff --git a/data-bus/etc/data-bus.urm.puml b/data-bus/etc/data-bus.urm.puml deleted file mode 100644 index 9ca0ab602..000000000 --- a/data-bus/etc/data-bus.urm.puml +++ /dev/null @@ -1,77 +0,0 @@ -@startuml -package com.iluwatar.databus { - class AbstractDataType { - - dataBus : DataBus - + AbstractDataType() - + getDataBus() : DataBus - + setDataBus(dataBus : DataBus) - } - ~class App { - - log : Logger {static} - ~ App() - + main(args : String[]) {static} - } - class DataBus { - - INSTANCE : DataBus {static} - - listeners : Set - + DataBus() - + getInstance() : DataBus {static} - + publish(event : DataType) - + subscribe(member : Member) - + unsubscribe(member : Member) - } - interface DataType { - + getDataBus() : DataBus {abstract} - + setDataBus(DataBus) {abstract} - } - interface Member { - + accept(DataType) {abstract} - } -} -package com.iluwatar.databus.data { - class MessageData { - - message : String - + MessageData(message : String) - + getMessage() : String - + of(message : String) : DataType {static} - } - class StartingData { - - when : LocalDateTime - + StartingData(when : LocalDateTime) - + getWhen() : LocalDateTime - + of(when : LocalDateTime) : DataType {static} - } - class StoppingData { - - when : LocalDateTime - + StoppingData(when : LocalDateTime) - + getWhen() : LocalDateTime - + of(when : LocalDateTime) : DataType {static} - } -} -package com.iluwatar.databus.members { - class CounterMember { - - log : Logger {static} - - name : String - + CounterMember(name : String) - + accept(data : DataType) - - handleEvent(data : MessageData) - } - class StatusMember { - - id : int - - log : Logger {static} - + StatusMember(id : int) - + accept(data : DataType) - - handleEvent(data : StartingData) - - handleEvent(data : StoppingData) - } -} -AbstractDataType --> "-dataBus" DataBus -DataBus --> "-INSTANCE" DataBus -DataBus --> "-listeners" Member -AbstractDataType ..|> DataType -MessageData --|> AbstractDataType -StartingData --|> AbstractDataType -StoppingData --|> AbstractDataType -CounterMember ..|> Member -StatusMember ..|> Member -@enduml \ No newline at end of file diff --git a/data-bus/pom.xml b/data-bus/pom.xml index a77b59106..11d945268 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -33,13 +33,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT data-bus - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java index f986e1681..83d5386ac 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -22,8 +22,8 @@ */ package com.iluwatar.databus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -43,7 +43,7 @@ public class DataBusTest { @Mock private DataType event; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); } diff --git a/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java index 35deeb5fb..be705d6e7 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -24,11 +24,13 @@ package com.iluwatar.databus.members; import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.LocalDateTime; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests for {@link MessageCollectorMember}. * @@ -45,7 +47,7 @@ public class MessageCollectorMemberTest { //when collector.accept(messageData); //then - Assert.assertTrue(collector.getMessages().contains(message)); + assertTrue(collector.getMessages().contains(message)); } @Test @@ -56,7 +58,7 @@ public class MessageCollectorMemberTest { //when collector.accept(startingData); //then - Assert.assertEquals(0, collector.getMessages().size()); + assertEquals(0, collector.getMessages().size()); } } diff --git a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java index d5afbd132..41c0fccca 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -26,12 +26,14 @@ import com.iluwatar.databus.DataBus; import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; import com.iluwatar.databus.data.StoppingData; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.Month; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * Tests for {@link StatusMember}. * @@ -48,7 +50,7 @@ public class StatusMemberTest { //when statusMember.accept(startingData); //then - Assert.assertEquals(startTime, statusMember.getStarted()); + assertEquals(startTime, statusMember.getStarted()); } @Test @@ -61,7 +63,7 @@ public class StatusMemberTest { //when statusMember.accept(stoppingData); //then - Assert.assertEquals(stop, statusMember.getStopped()); + assertEquals(stop, statusMember.getStopped()); } @Test @@ -72,8 +74,8 @@ public class StatusMemberTest { //when statusMember.accept(messageData); //then - Assert.assertNull(statusMember.getStarted()); - Assert.assertNull(statusMember.getStopped()); + assertNull(statusMember.getStarted()); + assertNull(statusMember.getStopped()); } } diff --git a/data-mapper/README.md b/data-mapper/README.md index 362f19c51..075e8eece 100644 --- a/data-mapper/README.md +++ b/data-mapper/README.md @@ -3,7 +3,6 @@ layout: pattern title: Data Mapper folder: data-mapper permalink: /patterns/data-mapper/ -pumlid: JShB3OGm303HLg20nFVjnYGM1CN6ycTfVtFSsnjfzY5jPgUqkLqHwXy0mxUU8wuyqidQ8q4IjJqCO-QBWGOtVh5qyd5AKOmW4mT6Nu2-ZiAekapH_hkcSTNa-GC0 categories: Persistence Tier tags: - Java diff --git a/data-mapper/etc/data-mapper.urm.puml b/data-mapper/etc/data-mapper.urm.puml deleted file mode 100644 index 041cbb07b..000000000 --- a/data-mapper/etc/data-mapper.urm.puml +++ /dev/null @@ -1,42 +0,0 @@ -@startuml -package com.iluwatar.datamapper { - class App { - - log : Logger {static} - - App() - + main(args : String[]) {static} - } - class Student { - - grade : char - - name : String - - serialVersionUID : long {static} - - studentId : int - + Student(studentId : int, name : String, grade : char) - + equals(inputObject : Object) : boolean - + getGrade() : char - + getName() : String - + getStudentId() : int - + hashCode() : int - + setGrade(grade : char) - + setName(name : String) - + setStudentId(studentId : int) - + toString() : String - } - interface StudentDataMapper { - + delete(Student) {abstract} - + find(int) : Optional {abstract} - + insert(Student) {abstract} - + update(Student) {abstract} - } - class StudentDataMapperImpl { - - students : List - + StudentDataMapperImpl() - + delete(studentToBeDeleted : Student) - + find(studentId : int) : Optional - + getStudents() : List - + insert(studentToBeInserted : Student) - + update(studentToBeUpdated : Student) - } -} -StudentDataMapperImpl --> "-students" Student -StudentDataMapperImpl ..|> StudentDataMapper -@enduml \ No newline at end of file diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index 2d39ed042..ac0d78c33 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -28,13 +28,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT data-mapper - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java index d709833aa..d9c3d389f 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java @@ -41,8 +41,6 @@ public final class Student implements Serializable { * @param grade as respective grade of student */ public Student(final int studentId, final String name, final char grade) { - super(); - this.studentId = studentId; this.name = name; this.grade = grade; diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java index f2858100e..5c665a4e4 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java @@ -18,8 +18,7 @@ */ package com.iluwatar.datamapper; -import com.iluwatar.datamapper.App; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that Data-Mapper example runs without errors. diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java index 17f4d3922..5f63cf045 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java @@ -18,13 +18,9 @@ */ package com.iluwatar.datamapper; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import com.iluwatar.datamapper.Student; -import com.iluwatar.datamapper.StudentDataMapper; -import com.iluwatar.datamapper.StudentDataMapperImpl; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java index ec35b21de..523a6509a 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -18,10 +18,10 @@ */ package com.iluwatar.datamapper; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests {@link Student}. diff --git a/data-transfer-object/README.md b/data-transfer-object/README.md index 7fe2d9cdc..ad9b9f4e2 100644 --- a/data-transfer-object/README.md +++ b/data-transfer-object/README.md @@ -3,7 +3,6 @@ layout: pattern title: Data Transfer Object folder: data-transfer-object permalink: /patterns/data-transfer-object/ -pumlid: RSh14SCW30NHLk82GFTq8uDYum71I5zn-t41kUtCswrfwL4bhBzEOFcRoFZEHyCPUxXOcGfHv387jHutWuqk_dAguktGj1WGKwV1_WJLvqWmLl-8fRbVKa22yXTosCWhHly1 categories: Architectural tags: - Java diff --git a/data-transfer-object/etc/data-transfer-object.urm.puml b/data-transfer-object/etc/data-transfer-object.urm.puml deleted file mode 100644 index 2c21dd21c..000000000 --- a/data-transfer-object/etc/data-transfer-object.urm.puml +++ /dev/null @@ -1,26 +0,0 @@ -@startuml -package com.iluwatar.datatransfer { - class CustomerClientApp { - + CustomerClientApp() - + main(args : String[]) {static} - - printCustomerDetails(allCustomers : List) {static} - } - class CustomerDto { - - firstName : String - - id : String - - lastName : String - + CustomerDto(id : String, firstName : String, lastName : String) - + getFirstName() : String - + getId() : String - + getLastName() : String - } - class CustomerResource { - - customers : List - + CustomerResource(customers : List) - + delete(customerId : String) - + getAllCustomers() : List - + save(customer : CustomerDto) - } -} -CustomerResource --> "-customers" CustomerDto -@enduml \ No newline at end of file diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml index 2f4871cb6..8a484e919 100644 --- a/data-transfer-object/pom.xml +++ b/data-transfer-object/pom.xml @@ -28,13 +28,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT data-transfer-object - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java index adfe66b7d..db669b785 100644 --- a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java @@ -24,12 +24,12 @@ package com.iluwatar.datatransfer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * tests {@link CustomerResource}. diff --git a/decorator/README.md b/decorator/README.md index 1b9d8a511..dcf49dbf5 100644 --- a/decorator/README.md +++ b/decorator/README.md @@ -3,7 +3,6 @@ layout: pattern title: Decorator folder: decorator permalink: /patterns/decorator/ -pumlid: HSV14SCm20J0Lk82BFxf1YF6LaP26ZZizfDVVhjRC-bPDRs_Bc35cyZvAMV3bKU6kao36ehCGQtdms2d3z-yLursshuOKBUWmV43LPNfZEcaaFzA-YWhH_y2 categories: Structural tags: - Java @@ -35,7 +34,7 @@ Wikipedia says **Programmatic Example** -Lets take the troll example. First of all we have a simple troll implementing the troll interface +Let's take the troll example. First of all we have a simple troll implementing the troll interface ``` public interface Troll { diff --git a/decorator/pom.xml b/decorator/pom.xml index 99a7b14c0..687de3ad8 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT decorator - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java index 466fa1552..35cc76dbd 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.decorator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java index fb86615c6..5221eb2da 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -22,10 +22,12 @@ */ package com.iluwatar.decorator; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.internal.verification.VerificationModeFactory.times; /** diff --git a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java index 5c6b2bbe7..14d944b2e 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java @@ -25,15 +25,15 @@ package com.iluwatar.decorator; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link SimpleTroll} @@ -42,12 +42,12 @@ public class SimpleTrollTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(SimpleTroll.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/delegation/README.md b/delegation/README.md index b294607ec..e5c0c6376 100644 --- a/delegation/README.md +++ b/delegation/README.md @@ -3,7 +3,6 @@ layout: pattern title: Delegation folder: delegation permalink: /patterns/delegation/ -pumlid: JSV14GCX20NGLf82LkxfXbN69OFeu2VRVdBCxRsdUhLiac6F2rZxHHHybwwuyimjKQT37ANEGMfvCpZepHy-ccpjVYm697pJuFq3DJ7f39rEWlhNaZ7Aoc5V categories: Behavioral tags: - Java diff --git a/delegation/etc/delegation.urm.puml b/delegation/etc/delegation.urm.puml deleted file mode 100644 index 419cf350b..000000000 --- a/delegation/etc/delegation.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package com.iluwatar.delegation.simple.printers { - class CanonPrinter { - - LOGGER : Logger {static} - + CanonPrinter() - + print(message : String) - } - class EpsonPrinter { - - LOGGER : Logger {static} - + EpsonPrinter() - + print(message : String) - } - class HpPrinter { - - LOGGER : Logger {static} - + HpPrinter() - + print(message : String) - } -} -package com.iluwatar.delegation.simple { - class App { - + MESSAGE_TO_PRINT : String {static} - + App() - + main(args : String[]) {static} - } - interface Printer { - + print(String) {abstract} - } - class PrinterController { - - printer : Printer - + PrinterController(printer : Printer) - + print(message : String) - } -} -PrinterController --> "-printer" Printer -PrinterController ..|> Printer -CanonPrinter ..|> Printer -EpsonPrinter ..|> Printer -HpPrinter ..|> Printer -@enduml \ No newline at end of file diff --git a/delegation/pom.xml b/delegation/pom.xml index 67b1e599f..118f9f75b 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -38,13 +38,13 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api test - com.github.stefanbirkner - system-rules + org.junit.jupiter + junit-jupiter-engine test diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java index 434d94baa..ffdc96b80 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -22,7 +22,8 @@ */ package com.iluwatar.delegation.simple; -import org.junit.Test; +import org.junit.jupiter.api.Test; + /** * Application Test Entry */ diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java index fd99a30dd..422da5685 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -22,20 +22,21 @@ */ package com.iluwatar.delegation.simple; -import static org.junit.Assert.assertEquals; - import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import com.iluwatar.delegation.simple.printers.CanonPrinter; import com.iluwatar.delegation.simple.printers.EpsonPrinter; import com.iluwatar.delegation.simple.printers.HpPrinter; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + import java.util.LinkedList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Delegation Pattern @@ -44,12 +45,12 @@ public class DelegateTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/dependency-injection/README.md b/dependency-injection/README.md index b4ec12e6b..735f589b1 100644 --- a/dependency-injection/README.md +++ b/dependency-injection/README.md @@ -3,7 +3,6 @@ layout: pattern title: Dependency Injection folder: dependency-injection permalink: /patterns/dependency-injection/ -pumlid: RSdB3SCW303GLPe1mFTkunWhSGG6-PEesxS3zFQajubIpyPf_NL6B7y363xra3XpJsUZgS4QbUO0wVbWeC65DvR6BeUMXH5iwZ3GVu36YxMnqgU8NamXKu63_aPD6tNbw5y0 categories: Behavioral tags: - Java diff --git a/dependency-injection/etc/dependency-injection.urm.puml b/dependency-injection/etc/dependency-injection.urm.puml deleted file mode 100644 index 80f15fce3..000000000 --- a/dependency-injection/etc/dependency-injection.urm.puml +++ /dev/null @@ -1,49 +0,0 @@ -@startuml -package com.iluwatar.dependency.injection { - class AdvancedWizard { - - tobacco : Tobacco - + AdvancedWizard(tobacco : Tobacco) - + smoke() - } - class App { - + App() - + main(args : String[]) {static} - } - class GuiceWizard { - - tobacco : Tobacco - + GuiceWizard(tobacco : Tobacco) - + smoke() - } - class OldTobyTobacco { - + OldTobyTobacco() - } - class RivendellTobacco { - + RivendellTobacco() - } - class SecondBreakfastTobacco { - + SecondBreakfastTobacco() - } - class SimpleWizard { - - tobacco : OldTobyTobacco - + SimpleWizard() - + smoke() - } - abstract class Tobacco { - - LOGGER : Logger {static} - + Tobacco() - + smoke(wizard : Wizard) - } - interface Wizard { - + smoke() {abstract} - } -} -SimpleWizard --> "-tobacco" OldTobyTobacco -AdvancedWizard --> "-tobacco" Tobacco -GuiceWizard --> "-tobacco" Tobacco -AdvancedWizard ..|> Wizard -GuiceWizard ..|> Wizard -OldTobyTobacco --|> Tobacco -RivendellTobacco --|> Tobacco -SecondBreakfastTobacco --|> Tobacco -SimpleWizard ..|> Wizard -@enduml \ No newline at end of file diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index e4e7765a3..127a9b2b8 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT dependency-injection - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java index b2a701d0b..da15b7c52 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java @@ -23,11 +23,12 @@ package com.iluwatar.dependency.injection; import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; /** * Date: 28/04/17 - 7:40 AM @@ -39,12 +40,12 @@ public class AdvancedSorceressTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Tobacco.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java index 2d6857912..46e38cc33 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java @@ -23,11 +23,12 @@ package com.iluwatar.dependency.injection; import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; /** * Date: 12/10/15 - 8:40 PM @@ -38,12 +39,12 @@ public class AdvancedWizardTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Tobacco.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java index 41f04c9b3..fc8775942 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.dependency.injection; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java index e58a9f3b5..042a41855 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java @@ -26,11 +26,11 @@ import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/10/15 - 8:57 PM @@ -41,12 +41,12 @@ public class GuiceWizardTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Tobacco.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java index 4ce69e095..4600a2598 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java @@ -23,11 +23,11 @@ package com.iluwatar.dependency.injection; import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/10/15 - 8:26 PM @@ -38,12 +38,12 @@ public class SimpleWizardTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Tobacco.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/double-checked-locking/README.md b/double-checked-locking/README.md index 582e4aac6..da1fdd1a2 100644 --- a/double-checked-locking/README.md +++ b/double-checked-locking/README.md @@ -3,7 +3,6 @@ layout: pattern title: Double Checked Locking folder: double-checked-locking permalink: /patterns/double-checked-locking/ -pumlid: TSdH4SCW203GLTe1bFzkGv1J6qGFeLc_MI1_x-wzkv94uJ1vDVUrFm26LwxTMnonsMYgitgcEQ1BNEXeyCKVfiAxLqqBtTbqmy1z0ygCGpXHOpgv99bqTgt0JW-LmqPUCUGF categories: Concurrency tags: - Java diff --git a/double-checked-locking/etc/double-checked-locking.urm.puml b/double-checked-locking/etc/double-checked-locking.urm.puml deleted file mode 100644 index 242519fce..000000000 --- a/double-checked-locking/etc/double-checked-locking.urm.puml +++ /dev/null @@ -1,22 +0,0 @@ -@startuml -package com.iluwatar.doublechecked.locking { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Inventory { - - LOGGER : Logger {static} - - inventorySize : int - - items : List - - lock : Lock - + Inventory(inventorySize : int) - + addItem(item : Item) : boolean - + getItems() : List - } - class Item { - + Item() - } -} -Inventory --> "-items" Item -@enduml \ No newline at end of file diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index e82dcd559..d7e8414c0 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -27,13 +27,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT double-checked-locking - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java index 672d83f0a..649afa58f 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.doublechecked.locking; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java index 0b1487e11..2929afc5e 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java @@ -25,9 +25,9 @@ package com.iluwatar.doublechecked.locking; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; @@ -36,9 +36,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static junit.framework.TestCase.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/10/15 - 9:34 PM @@ -49,12 +51,12 @@ public class InventoryTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Inventory.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } @@ -76,32 +78,34 @@ public class InventoryTest { * of order, it means that the locking is not ok, increasing the risk of going over the inventory * item limit. */ - @Test(timeout = 10000) + @Test public void testAddItem() throws Exception { - // Create a new inventory with a limit of 1000 items and put some load on the add method - final Inventory inventory = new Inventory(INVENTORY_SIZE); - final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); - for (int i = 0; i < THREAD_COUNT; i++) { - executorService.execute(() -> { - while (inventory.addItem(new Item())) {}; - }); - } + assertTimeout(ofMillis(10000), () -> { + // Create a new inventory with a limit of 1000 items and put some load on the add method + final Inventory inventory = new Inventory(INVENTORY_SIZE); + final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); + for (int i = 0; i < THREAD_COUNT; i++) { + executorService.execute(() -> { + while (inventory.addItem(new Item())) {}; + }); + } - // Wait until all threads have finished - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.SECONDS); + // Wait until all threads have finished + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); - // Check the number of items in the inventory. It should not have exceeded the allowed maximum - final List items = inventory.getItems(); - assertNotNull(items); - assertEquals(INVENTORY_SIZE, items.size()); + // Check the number of items in the inventory. It should not have exceeded the allowed maximum + final List items = inventory.getItems(); + assertNotNull(items); + assertEquals(INVENTORY_SIZE, items.size()); - assertEquals(INVENTORY_SIZE, appender.getLogSize()); + assertEquals(INVENTORY_SIZE, appender.getLogSize()); - // ... and check if the inventory size is increasing continuously - for (int i = 0; i < items.size(); i++) { - assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); - } + // ... and check if the inventory size is increasing continuously + for (int i = 0; i < items.size(); i++) { + assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); + } + }); } diff --git a/double-dispatch/README.md b/double-dispatch/README.md index b0f2185f9..ae87208a2 100644 --- a/double-dispatch/README.md +++ b/double-dispatch/README.md @@ -3,7 +3,6 @@ layout: pattern title: Double Dispatch folder: double-dispatch permalink: /patterns/double-dispatch/ -pumlid: NSbB3iCW303HgpG70Ezx6yTOWSeOv4zp_MRTtUZDCPGa6wV9gqTiVmCOtlKQqVDCPwEbmHgLreGXUMEWmGU_M1hxkBHiZ61JXud-1BILft1fmvz37JZetshQh3kd_000 categories: Other tags: - Java diff --git a/double-dispatch/etc/double-dispatch.urm.puml b/double-dispatch/etc/double-dispatch.urm.puml deleted file mode 100644 index 447cf3081..000000000 --- a/double-dispatch/etc/double-dispatch.urm.puml +++ /dev/null @@ -1,68 +0,0 @@ -@startuml -package com.iluwatar.doubledispatch { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class FlamingAsteroid { - + FlamingAsteroid(left : int, top : int, right : int, bottom : int) - + collision(gameObject : GameObject) - } - abstract class GameObject { - - damaged : boolean - - onFire : boolean - + GameObject(left : int, top : int, right : int, bottom : int) - + collision(GameObject) {abstract} - + collisionResolve(FlamingAsteroid) {abstract} - + collisionResolve(Meteoroid) {abstract} - + collisionResolve(SpaceStationIss) {abstract} - + collisionResolve(SpaceStationMir) {abstract} - + isDamaged() : boolean - + isOnFire() : boolean - + setDamaged(damaged : boolean) - + setOnFire(onFire : boolean) - + toString() : String - } - class Meteoroid { - - LOGGER : Logger {static} - + Meteoroid(left : int, top : int, right : int, bottom : int) - + collision(gameObject : GameObject) - + collisionResolve(asteroid : FlamingAsteroid) - + collisionResolve(iss : SpaceStationIss) - + collisionResolve(meteoroid : Meteoroid) - + collisionResolve(mir : SpaceStationMir) - } - class Rectangle { - - bottom : int - - left : int - - right : int - - top : int - + Rectangle(left : int, top : int, right : int, bottom : int) - + getBottom() : int - + getLeft() : int - + getRight() : int - + getTop() : int - ~ intersectsWith(r : Rectangle) : boolean - + toString() : String - } - class SpaceStationIss { - + SpaceStationIss(left : int, top : int, right : int, bottom : int) - + collision(gameObject : GameObject) - } - class SpaceStationMir { - - LOGGER : Logger {static} - + SpaceStationMir(left : int, top : int, right : int, bottom : int) - + collision(gameObject : GameObject) - + collisionResolve(asteroid : FlamingAsteroid) - + collisionResolve(iss : SpaceStationIss) - + collisionResolve(meteoroid : Meteoroid) - + collisionResolve(mir : SpaceStationMir) - } -} -FlamingAsteroid --|> Meteoroid -GameObject --|> Rectangle -Meteoroid --|> GameObject -SpaceStationIss --|> SpaceStationMir -SpaceStationMir --|> GameObject -@enduml \ No newline at end of file diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index 90ea0a66d..85a85d831 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT double-dispatch - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java index dce6afd86..ce39b2cce 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java index 3dc32905a..683fcd5b0 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.doubledispatch; -import static org.junit.Assert.assertEquals; - import java.util.Objects; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Date: 12/10/15 - 8:37 PM * Test for Collision @@ -86,7 +86,7 @@ public abstract class CollisionTest { ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; - assertEquals(errorMessage, expectTargetOnFire, target.isOnFire()); + assertEquals(expectTargetOnFire, target.isOnFire(), errorMessage); } /** @@ -105,7 +105,7 @@ public abstract class CollisionTest { ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; - assertEquals(errorMessage, expectedDamage, target.isDamaged()); + assertEquals(expectedDamage, target.isDamaged(), errorMessage); } } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java index 120c9a883..7c5edb5c9 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java @@ -22,11 +22,11 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/10/15 - 11:31 PM diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java index 8eed497c0..40ba0f60d 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Date: 12/10/15 - 11:31 PM diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java index 1f4e476de..8f547c11f 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java @@ -22,11 +22,11 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static junit.framework.TestCase.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit test for Rectangle diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java index 8cde65d11..f99f6bdf5 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Date: 12/10/15 - 11:31 PM diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java index 3dbab58ba..f0cbd3668 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.doubledispatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Date: 12/10/15 - 11:31 PM diff --git a/eip-aggregator/README.md b/eip-aggregator/README.md new file mode 100644 index 000000000..a1dc18ea8 --- /dev/null +++ b/eip-aggregator/README.md @@ -0,0 +1,33 @@ +--- +layout: pattern +title: EIP Aggregator +folder: eip-aggregator +permalink: /patterns/eip-aggregator/ +categories: Integration +tags: + - Java + - Difficulty-Intermittent + - EIP +--- + +## Intent +Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example +you may need to gather offers and after defined number of offers has been received you would like to choose the one with +the best parameters. + +Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages, +applies aggregation strategy and upon fulfilling given criteria, releasing merged messages. + +![alt text](./etc/aggregator.gif "Splitter") + +## Applicability +Use the Aggregator pattern when + +* You need to combine multiple incoming messages +* You want to process grouped data + +## Credits + +* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Aggregator.html) +* [Apache Camel - Documentation](http://camel.apache.org/aggregator2.html) + diff --git a/eip-aggregator/etc/aggregator.gif b/eip-aggregator/etc/aggregator.gif new file mode 100644 index 000000000..b06cdfb0c Binary files /dev/null and b/eip-aggregator/etc/aggregator.gif differ diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml new file mode 100644 index 000000000..8a51b8218 --- /dev/null +++ b/eip-aggregator/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + eip-aggregator + + com.iluwatar + java-design-patterns + 1.19.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.camel + camel-core + ${camel.version} + + + + org.apache.camel + camel-spring-boot + ${camel.version} + + + + + com.github.sbrannen + spring-test-junit5 + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.springframework.boot + spring-boot-starter-test + + + + org.apache.camel + camel-test-spring + ${camel.version} + + + + \ No newline at end of file diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java new file mode 100644 index 000000000..d55f24e3d --- /dev/null +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java @@ -0,0 +1,73 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example + * you may need to gather offers and after defined number of offers has been received you would like to choose the one + * with the best parameters. + * + *

+ * Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages, + * applies aggregation strategy and upon fulfilling given criteria, releasing merged messages. + *

+ * + */ +@SpringBootApplication +public class App { + + /** + * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * + * @param args command line args + */ + public static void main(String[] args) throws Exception { + // Run Spring Boot application and obtain ApplicationContext + ConfigurableApplicationContext context = SpringApplication.run(App.class, args); + + // Get CamelContext from ApplicationContext + CamelContext camelContext = (CamelContext) context.getBean("camelContext"); + + // Add a new routes that will handle endpoints form SplitterRoute class. + camelContext.addRoutes(new RouteBuilder() { + + @Override + public void configure() throws Exception { + from("{{endpoint}}").log("ENDPOINT: ${body}"); + } + + }); + + // Add producer that will send test message to an entry point in WireTapRoute + String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"}; + camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray); + + SpringApplication.exit(context); + } +} diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java new file mode 100644 index 000000000..536565339 --- /dev/null +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator.routes; + +import org.apache.camel.builder.RouteBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Sample aggregator route definition. + * + *

+ * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. + * Route accepts messages containing String as a body, it aggregates the messages based on the settings and forwards + * them as CSV to the output chanel. + * + * Settings for the aggregation are: aggregate until 3 messages are bundled or wait 2000ms before sending bundled + * messages further. + *

+ * + * In this example input/output endpoints names are stored in application.properties file. + */ +@Component +public class AggregatorRoute extends RouteBuilder { + + @Autowired + private MessageAggregationStrategy aggregator; + + /** + * Configures the route + * @throws Exception in case of exception during configuration + */ + @Override + public void configure() throws Exception { + // Main route + from("{{entry}}").aggregate(constant(true), aggregator) + .completionSize(3).completionInterval(2000) + .to("{{endpoint}}"); + } +} diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java new file mode 100644 index 000000000..4b5e4cb2f --- /dev/null +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java @@ -0,0 +1,49 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator.routes; + +import org.apache.camel.Exchange; +import org.apache.camel.processor.aggregate.AggregationStrategy; +import org.springframework.stereotype.Component; + +/** + * Aggregation strategy joining bodies of messages. If message is first one oldMessage is null. All changes are + * made on IN messages. + */ +@Component +public class MessageAggregationStrategy implements AggregationStrategy { + + @Override + public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { + if (oldExchange == null) { + return newExchange; + } + + String in1 = (String) oldExchange.getIn().getBody(); + String in2 = (String) newExchange.getIn().getBody(); + + oldExchange.getIn().setBody(in1 + ";" + in2); + + return oldExchange; + } +} diff --git a/eip-aggregator/src/main/resources/application.properties b/eip-aggregator/src/main/resources/application.properties new file mode 100644 index 000000000..044833fc1 --- /dev/null +++ b/eip-aggregator/src/main/resources/application.properties @@ -0,0 +1,25 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=direct:endpoint diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java new file mode 100644 index 000000000..40a336786 --- /dev/null +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java new file mode 100644 index 000000000..2c7d207d6 --- /dev/null +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test class for AggregatorRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class AggregatorRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody("TEST1"); + entry.sendBody("TEST2"); + entry.sendBody("TEST3"); + entry.sendBody("TEST4"); + entry.sendBody("TEST5"); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(2); + endpoint.assertIsSatisfied(); + + String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody(); + assertEquals(3, body.split(";").length); + + String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody(); + assertEquals(2, body2.split(";").length); + } +} diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java new file mode 100644 index 000000000..7a7a15154 --- /dev/null +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.aggregator.routes; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests MessageAggregationStrategy + */ +public class MessageAggregationStrategyTest { + + @Test + public void testAggregate() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + Exchange oldExchange = new DefaultExchange((CamelContext) null); + oldExchange.getIn().setBody("TEST1"); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(oldExchange, newExchange); + String outputBody = (String) output.getIn().getBody(); + assertEquals("TEST1;TEST2", outputBody); + } + + @Test + public void testAggregateOldNull() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(null, newExchange); + String outputBody = (String) output.getIn().getBody(); + + assertEquals(newExchange, output); + assertEquals("TEST2", outputBody); + } +} diff --git a/eip-aggregator/src/test/resources/application-test.properties b/eip-aggregator/src/test/resources/application-test.properties new file mode 100644 index 000000000..8d6ecbbd3 --- /dev/null +++ b/eip-aggregator/src/test/resources/application-test.properties @@ -0,0 +1,25 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=mock:endpoint diff --git a/eip-splitter/README.md b/eip-splitter/README.md new file mode 100644 index 000000000..51a917bad --- /dev/null +++ b/eip-splitter/README.md @@ -0,0 +1,32 @@ +--- +layout: pattern +title: EIP Splitter +folder: eip-splitter +permalink: /patterns/eip-splitter/ +categories: Integration +tags: + - Java + - Difficulty-Intermittent + - EIP +--- + +## Intent +It is very common in integration systems that incoming messages consists of many items bundled together. For example +an invoice document contains multiple invoice lines describing transaction (quantity, name of provided +service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter +pattern comes in handy. It will take the whole document, split it based on given criteria and send individual +items to the endpoint. + +![alt text](./etc/sequencer.gif "Splitter") + +## Applicability +Use the Splitter pattern when + +* You need to split received data into smaller pieces to process them individually +* You need to control the size of data batches you are able to process + +## Credits + +* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html) +* [Apache Camel - Documentation](http://camel.apache.org/splitter.html) + diff --git a/eip-splitter/etc/sequencer.gif b/eip-splitter/etc/sequencer.gif new file mode 100644 index 000000000..a925fa209 Binary files /dev/null and b/eip-splitter/etc/sequencer.gif differ diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml new file mode 100644 index 000000000..54661f946 --- /dev/null +++ b/eip-splitter/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + eip-splitter + + com.iluwatar + java-design-patterns + 1.19.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.camel + camel-core + ${camel.version} + + + + org.apache.camel + camel-spring-boot + ${camel.version} + + + + + com.github.sbrannen + spring-test-junit5 + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.springframework.boot + spring-boot-starter-test + + + + org.apache.camel + camel-test-spring + ${camel.version} + + + + \ No newline at end of file diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java new file mode 100644 index 000000000..ceadb5f8d --- /dev/null +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java @@ -0,0 +1,75 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.splitter; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * It is very common in integration systems that incoming messages consists of many items bundled together. For example + * an invoice document contains multiple invoice lines describing transaction (quantity, name of provided + * service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter + * pattern comes in handy. It will take the whole document, split it based on given criteria and send individual + * items to the endpoint. + * + *

+ * Splitter allows you to split messages based on defined criteria. It takes original message, process it and send + * multiple parts to the output channel. It is not defined if it should keep the order of items though. + *

+ * + */ +@SpringBootApplication +public class App { + + /** + * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * + * @param args command line args + */ + public static void main(String[] args) throws Exception { + // Run Spring Boot application and obtain ApplicationContext + ConfigurableApplicationContext context = SpringApplication.run(App.class, args); + + // Get CamelContext from ApplicationContext + CamelContext camelContext = (CamelContext) context.getBean("camelContext"); + + // Add a new routes that will handle endpoints form SplitterRoute class. + camelContext.addRoutes(new RouteBuilder() { + + @Override + public void configure() throws Exception { + from("{{endpoint}}").log("ENDPOINT: ${body}"); + } + + }); + + // Add producer that will send test message to an entry point in WireTapRoute + String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"}; + camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray); + + SpringApplication.exit(context); + } +} diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java new file mode 100644 index 000000000..f7eb28dea --- /dev/null +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.splitter.routes; + +import org.apache.camel.builder.RouteBuilder; +import org.springframework.stereotype.Component; + +/** + * Sample splitter route definition. + * + *

+ * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. + * Route accepts messages having body of array or collection of objects. Splitter component split message body and + * forwards single objects to the endpoint. + *

+ * + * In this example input/output endpoints names are stored in application.properties file. + */ +@Component +public class SplitterRoute extends RouteBuilder { + + /** + * Configures the route + * @throws Exception in case of exception during configuration + */ + @Override + public void configure() throws Exception { + // Main route + from("{{entry}}").split().body().to("{{endpoint}}"); + } +} diff --git a/eip-splitter/src/main/resources/application.properties b/eip-splitter/src/main/resources/application.properties new file mode 100644 index 000000000..044833fc1 --- /dev/null +++ b/eip-splitter/src/main/resources/application.properties @@ -0,0 +1,25 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=direct:endpoint diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java new file mode 100644 index 000000000..fe3eca01e --- /dev/null +++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.splitter; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java new file mode 100644 index 000000000..9257a4410 --- /dev/null +++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java @@ -0,0 +1,72 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.splitter.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +/** + * Test class for SplitterRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = SplitterRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class SplitterRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"}); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(3); + endpoint.assertIsSatisfied(); + } +} diff --git a/eip-splitter/src/test/resources/application-test.properties b/eip-splitter/src/test/resources/application-test.properties new file mode 100644 index 000000000..8d6ecbbd3 --- /dev/null +++ b/eip-splitter/src/test/resources/application-test.properties @@ -0,0 +1,25 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=mock:endpoint diff --git a/eip-wire-tap/README.md b/eip-wire-tap/README.md new file mode 100644 index 000000000..31cbd9123 --- /dev/null +++ b/eip-wire-tap/README.md @@ -0,0 +1,29 @@ +--- +layout: pattern +title: EIP Wire Tap +folder: eip-wire-tap +permalink: /patterns/eip-wire-tap/ +categories: Integration +tags: + - Java + - Difficulty-Intermittent + - EIP +--- + +## Intent +In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved +by intercepting the message and redirecting it to a different location like console, filesystem or the database. +It is important that such functionality should not modify the original message and influence the processing path. + +![alt text](./etc/wiretap.gif "Wire Tap") + +## Applicability +Use the Wire Tap pattern when + +* You need to monitor messages flowing through the system +* You need to redirect the same, unchanged message to two different endpoints/paths + +## Credits + +* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/WireTap.html) +* [Apache Camel - Documentation](http://camel.apache.org/wire-tap.html) diff --git a/eip-wire-tap/etc/wiretap.gif b/eip-wire-tap/etc/wiretap.gif new file mode 100644 index 000000000..414173716 Binary files /dev/null and b/eip-wire-tap/etc/wiretap.gif differ diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml new file mode 100644 index 000000000..688f4ad6d --- /dev/null +++ b/eip-wire-tap/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + eip-wire-tap + + com.iluwatar + java-design-patterns + 1.19.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.camel + camel-core + ${camel.version} + + + + org.apache.camel + camel-spring-boot + ${camel.version} + + + + + com.github.sbrannen + spring-test-junit5 + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.springframework.boot + spring-boot-starter-test + + + + org.apache.camel + camel-test-spring + ${camel.version} + + + + \ No newline at end of file diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java new file mode 100644 index 000000000..ca605cb78 --- /dev/null +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java @@ -0,0 +1,73 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.wiretap; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved + * by intercepting the message and redirecting it to a different location like console, filesystem or the database. + * It is important that such functionality should not modify the original message and influence the processing path. + * + *

+ * Wire Tap allows you to route messages to a separate location while they are being forwarded to the ultimate + * destination. It basically consumes messages of the input channel and publishes the unmodified message to both + * output channels. + *

+ */ +@SpringBootApplication +public class App { + + /** + * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * + * @param args command line args + */ + public static void main(String[] args) throws Exception { + // Run Spring Boot application and obtain ApplicationContext + ConfigurableApplicationContext context = SpringApplication.run(App.class, args); + + // Get CamelContext from ApplicationContext + CamelContext camelContext = (CamelContext) context.getBean("camelContext"); + + // Add a new routes that will handle endpoints form WireTapRoute class. + camelContext.addRoutes(new RouteBuilder() { + + @Override + public void configure() throws Exception { + from("{{endpoint}}").log("ENDPOINT: ${body}"); + from("{{wireTapEndpoint}}").log("WIRETAPPED ENDPOINT: ${body}"); + } + + }); + + // Add producer that will send test message to an entry point in WireTapRoute + camelContext.createProducerTemplate().sendBody("{{entry}}", "Test message"); + + SpringApplication.exit(context); + } +} diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java new file mode 100644 index 000000000..994ceacdb --- /dev/null +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.wiretap.routes; + +import org.apache.camel.builder.RouteBuilder; +import org.springframework.stereotype.Component; + +/** + * Sample wire tap route definition. + * + *

+ * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. + * Wire Tap intercepts the message and sends it to direct:wireTap, which in turn forwards it to + * direct:wireTapEndpoint. + *

+ * + * In this example input/output endpoints names are stored in application.properties file. + */ +@Component +public class WireTapRoute extends RouteBuilder { + + /** + * Configures the route + * @throws Exception in case of exception during configuration + */ + @Override + public void configure() throws Exception { + // Main route + from("{{entry}}").wireTap("direct:wireTap").to("{{endpoint}}"); + + // Wire tap route + from("direct:wireTap").log("Message: ${body}").to("{{wireTapEndpoint}}"); + } +} diff --git a/eip-wire-tap/src/main/resources/application.properties b/eip-wire-tap/src/main/resources/application.properties new file mode 100644 index 000000000..90a152425 --- /dev/null +++ b/eip-wire-tap/src/main/resources/application.properties @@ -0,0 +1,26 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=direct:endpoint +wireTapEndpoint=direct:wireTapEndpoint \ No newline at end of file diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java new file mode 100644 index 000000000..673803df7 --- /dev/null +++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.wiretap; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java new file mode 100644 index 000000000..449f86208 --- /dev/null +++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 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.eip.wiretap.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test class for WireTapRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = WireTapRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class WireTapRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + @EndpointInject(uri = "{{wireTapEndpoint}}") + private MockEndpoint wireTapEndpoint; + + /** + * Test if both endpoints receive exactly one message containing the same, unchanged body. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testWireTap() throws Exception { + entry.sendBody("TEST"); + + endpoint.expectedMessageCount(1); + wireTapEndpoint.expectedMessageCount(1); + + endpoint.assertIsSatisfied(); + wireTapEndpoint.assertIsSatisfied(); + + Message endpointIn = endpoint.getExchanges().get(0).getIn(); + Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn(); + + assertEquals("TEST", endpointIn.getBody()); + assertEquals("TEST", wireTapEndpointIn.getBody()); + } +} diff --git a/eip-wire-tap/src/test/resources/application-test.properties b/eip-wire-tap/src/test/resources/application-test.properties new file mode 100644 index 000000000..e76faa1fc --- /dev/null +++ b/eip-wire-tap/src/test/resources/application-test.properties @@ -0,0 +1,26 @@ +# +# The MIT License +# Copyright (c) 2014 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. +# + +entry=direct:entry +endpoint=mock:endpoint +wireTapEndpoint=mock:wireTapEndpoint \ No newline at end of file diff --git a/event-aggregator/README.md b/event-aggregator/README.md index ce7f358de..ac07869e7 100644 --- a/event-aggregator/README.md +++ b/event-aggregator/README.md @@ -3,7 +3,6 @@ layout: pattern title: Event Aggregator folder: event-aggregator permalink: /patterns/event-aggregator/ -pumlid: PSf13iCW30NHgxG70Ezx6uTOX0eCih-JwvTzTwEdUJSjFKu9wwyBMFuXCdvoRRZY21ShKo6ANEQWrkDXiD6NRqwdUAkQ5WDYwZJOTv3SUqzSgqbbp0qeVvZ3Hbun-Wy0 categories: Structural tags: - Java diff --git a/event-aggregator/etc/event-aggregator.urm.puml b/event-aggregator/etc/event-aggregator.urm.puml deleted file mode 100644 index 341d7d65e..000000000 --- a/event-aggregator/etc/event-aggregator.urm.puml +++ /dev/null @@ -1,74 +0,0 @@ -@startuml -package com.iluwatar.event.aggregator { - class App { - + App() - + main(args : String[]) {static} - } - enum Event { - + STARK_SIGHTED {static} - + TRAITOR_DETECTED {static} - + WARSHIPS_APPROACHING {static} - - description : String - + toString() : String - + valueOf(name : String) : Event {static} - + values() : Event[] {static} - } - abstract class EventEmitter { - - observers : List - + EventEmitter() - + EventEmitter(obs : EventObserver) - # notifyObservers(e : Event) - + registerObserver(obs : EventObserver) - + timePasses(Weekday) {abstract} - } - interface EventObserver { - + onEvent(Event) {abstract} - } - class KingJoffrey { - - LOGGER : Logger {static} - + KingJoffrey() - + onEvent(e : Event) - } - class KingsHand { - + KingsHand() - + KingsHand(obs : EventObserver) - + onEvent(e : Event) - + timePasses(day : Weekday) - } - class LordBaelish { - + LordBaelish() - + LordBaelish(obs : EventObserver) - + timePasses(day : Weekday) - } - class LordVarys { - + LordVarys() - + LordVarys(obs : EventObserver) - + timePasses(day : Weekday) - } - class Scout { - + Scout() - + Scout(obs : EventObserver) - + timePasses(day : Weekday) - } - enum Weekday { - + FRIDAY {static} - + MONDAY {static} - + SATURDAY {static} - + SUNDAY {static} - + THURSDAY {static} - + TUESDAY {static} - + WEDNESDAY {static} - - description : String - + toString() : String - + valueOf(name : String) : Weekday {static} - + values() : Weekday[] {static} - } -} -EventEmitter --> "-observers" EventObserver -KingJoffrey ..|> EventObserver -KingsHand ..|> EventObserver -KingsHand --|> EventEmitter -LordBaelish --|> EventEmitter -LordVarys --|> EventEmitter -Scout --|> EventEmitter -@enduml \ No newline at end of file diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index 19e76af84..c28fded6f 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -28,13 +28,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT event-aggregator - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java index 2de7021b3..0d4f6af2d 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java @@ -30,7 +30,6 @@ package com.iluwatar.event.aggregator; public class KingsHand extends EventEmitter implements EventObserver { public KingsHand() { - super(); } public KingsHand(EventObserver obs) { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java index 9204aa572..50b7d501a 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java @@ -30,7 +30,6 @@ package com.iluwatar.event.aggregator; public class LordBaelish extends EventEmitter { public LordBaelish() { - super(); } public LordBaelish(EventObserver obs) { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java index dc6009b8c..6248c4446 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java @@ -30,7 +30,6 @@ package com.iluwatar.event.aggregator; public class LordVarys extends EventEmitter { public LordVarys() { - super(); } public LordVarys(EventObserver obs) { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java index c8dcf5ba3..a1095640a 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java @@ -30,7 +30,6 @@ package com.iluwatar.event.aggregator; public class Scout extends EventEmitter { public Scout() { - super(); } public Scout(EventObserver obs) { diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java index 6cd678704..09548e384 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.event.aggregator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java index a67272789..c2f457e28 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -22,6 +22,8 @@ */ package com.iluwatar.event.aggregator; +import org.junit.jupiter.api.Test; + import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -32,7 +34,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; -import org.junit.Test; /** * Date: 12/12/15 - 10:58 PM diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java index 54c511f8c..28062c613 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.event.aggregator; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/12/15 - 2:52 PM diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java index 1743c3211..3f3296c57 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java @@ -25,15 +25,15 @@ package com.iluwatar.event.aggregator; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/12/15 - 3:04 PM @@ -44,12 +44,12 @@ public class KingJoffreyTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(KingJoffrey.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java index ba1327182..3a5ae8f68 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.event.aggregator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java index ab25d7ccc..df2d8ac79 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.event.aggregator; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/12/15 - 2:12 PM diff --git a/event-asynchronous/etc/event-asynchronous.png b/event-asynchronous/etc/event-asynchronous.png index a46ffe1c5..76cb1b626 100644 Binary files a/event-asynchronous/etc/event-asynchronous.png and b/event-asynchronous/etc/event-asynchronous.png differ diff --git a/event-asynchronous/etc/event-asynchronous.ucls b/event-asynchronous/etc/event-asynchronous.ucls index df09fc28d..1327b7104 100644 --- a/event-asynchronous/etc/event-asynchronous.ucls +++ b/event-asynchronous/etc/event-asynchronous.ucls @@ -1,63 +1,62 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + - - + + - - + + + + + + + + + + + + + + + + + + + + + + + @@ -65,49 +64,36 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - + + + + + + + + + + + + + + + + + + + - - + + diff --git a/event-asynchronous/etc/event-asynchronous.urm.puml b/event-asynchronous/etc/event-asynchronous.urm.puml deleted file mode 100644 index 0d683d27d..000000000 --- a/event-asynchronous/etc/event-asynchronous.urm.puml +++ /dev/null @@ -1,66 +0,0 @@ -@startuml -package com.iluwatar.event.asynchronous { - class App { - - LOGGER : Logger {static} - + PROP_FILE_NAME : String {static} - ~ interactiveMode : boolean - + App() - + main(args : String[]) {static} - + quickRun() - + run() - + runInteractiveMode() - + setUp() - } - class Event { - - LOGGER : Logger {static} - - eventId : int - - eventListener : ThreadCompleteListener - - eventTime : int - - isComplete : boolean - - isSynchronous : boolean - - thread : Thread - + Event(eventId : int, eventTime : int, isSynchronous : boolean) - + addListener(listener : ThreadCompleteListener) - - completed() - + isSynchronous() : boolean - + removeListener(listener : ThreadCompleteListener) - + run() - + start() - + status() - + stop() - } - class EventManager { - + MAX_EVENT_TIME : int {static} - + MAX_ID : int {static} - + MAX_RUNNING_EVENTS : int {static} - + MIN_ID : int {static} - - currentlyRunningSyncEvent : int - - eventPool : Map - - rand : Random - + EventManager() - + cancel(eventId : int) - + completedEventHandler(eventId : int) - + create(eventTime : int) : int - + createAsync(eventTime : int) : int - - createEvent(eventTime : int, isSynchronous : boolean) : int - - generateId() : int - + getEventPool() : Map - + numOfCurrentlyRunningSyncEvent() : int - + shutdown() - + start(eventId : int) - + status(eventId : int) - + statusOfAllEvents() - } - interface IEvent { - + start() {abstract} - + status() {abstract} - + stop() {abstract} - } - interface ThreadCompleteListener { - + completedEventHandler(int) {abstract} - } -} -Event --> "-eventListener" ThreadCompleteListener -Event ..|> IEvent -EventManager ..|> ThreadCompleteListener -@enduml \ No newline at end of file diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml index 5a2d65bfe..3c07f47bc 100644 --- a/event-asynchronous/pom.xml +++ b/event-asynchronous/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT event-asynchronous - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java index 2056dcf18..372bc2f58 100644 --- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java +++ b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java @@ -16,9 +16,9 @@ */ package com.iluwatar.event.asynchronous; -import java.io.IOException; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.IOException; /** * Tests that EventAsynchronous example runs without errors. diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java index 8e0860286..aa2c644cb 100644 --- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java +++ b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -16,12 +16,13 @@ */ package com.iluwatar.event.asynchronous; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -33,7 +34,7 @@ public class EventAsynchronousTest { private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); - @Before + @BeforeEach public void setUp() { app = new App(); } @@ -71,17 +72,19 @@ public class EventAsynchronousTest { } } - @Test(expected = InvalidOperationException.class) + @Test public void testUnsuccessfulSynchronousEvent() throws InvalidOperationException { - EventManager eventManager = new EventManager(); - try { - int sEventId = eventManager.create(60); - eventManager.start(sEventId); - sEventId = eventManager.create(60); - eventManager.start(sEventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } + assertThrows(InvalidOperationException.class, () -> { + EventManager eventManager = new EventManager(); + try { + int sEventId = eventManager.create(60); + eventManager.start(sEventId); + sEventId = eventManager.create(60); + eventManager.start(sEventId); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + }); } @Test diff --git a/event-driven-architecture/README.md b/event-driven-architecture/README.md index a263defec..e2f06cf5a 100644 --- a/event-driven-architecture/README.md +++ b/event-driven-architecture/README.md @@ -3,7 +3,6 @@ layout: pattern title: Event Driven Architecture folder: event-driven-architecture permalink: /patterns/event-driven-architecture/ -pumlid: TOhH3SCW30LNQGS0_tSRnrZ15H1adfFromBzkfFktZQaHT7mzgh0N1yYvoUVXXf7B7Mv1dGWozN9MZmCTlhopQdeidEaoO3wMDHvRI6zzvwAssPYbsfGGRYIGlxN7DxpZDv- categories: Architectural tags: - Java diff --git a/event-driven-architecture/etc/event-driven-architecture.urm.puml b/event-driven-architecture/etc/event-driven-architecture.urm.puml deleted file mode 100644 index 2eb79e438..000000000 --- a/event-driven-architecture/etc/event-driven-architecture.urm.puml +++ /dev/null @@ -1,64 +0,0 @@ -@startuml -package com.iluwatar.eda.handler { - class UserCreatedEventHandler { - - LOGGER : Logger {static} - + UserCreatedEventHandler() - + onEvent(event : UserCreatedEvent) - } - class UserUpdatedEventHandler { - - LOGGER : Logger {static} - + UserUpdatedEventHandler() - + onEvent(event : UserUpdatedEvent) - } -} -package com.iluwatar.eda.event { - abstract class AbstractEvent { - + AbstractEvent() - + getType() : Class - } - class UserCreatedEvent { - - user : User - + UserCreatedEvent(user : User) - + getUser() : User - } - class UserUpdatedEvent { - - user : User - + UserUpdatedEvent(user : User) - + getUser() : User - } -} -package com.iluwatar.eda.framework { - interface Event { - + getType() : Class {abstract} - } - class EventDispatcher { - - handlers : Map, Handler> - + EventDispatcher() - + dispatch(event : E extends Event) - + registerHandler(eventType : Class, handler : Handler) - } - interface Handler { - + onEvent(E extends Event) {abstract} - } -} -package com.iluwatar.eda.model { - class User { - - username : String - + User(username : String) - + getUsername() : String - } -} -package com.iluwatar.eda { - class App { - + App() - + main(args : String[]) {static} - } -} -UserUpdatedEvent --> "-user" User -UserCreatedEvent --> "-user" User -AbstractEvent ..|> Event -UserCreatedEvent --|> AbstractEvent -UserUpdatedEvent --|> AbstractEvent -UserCreatedEventHandler ..|> Handler -UserUpdatedEventHandler ..|> Handler -@enduml \ No newline at end of file diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index 4f2c34b5e..4eb2a6946 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -31,15 +31,20 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT event-driven-architecture - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java index e7d642b95..f74232ac1 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.eda; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java index 6e95f5fd2..823605e9d 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java @@ -23,10 +23,9 @@ package com.iluwatar.eda.event; import com.iluwatar.eda.model.User; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java index 7501653f6..6f647245d 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java @@ -27,8 +27,7 @@ import com.iluwatar.eda.event.UserUpdatedEvent; import com.iluwatar.eda.handler.UserCreatedEventHandler; import com.iluwatar.eda.handler.UserUpdatedEventHandler; import com.iluwatar.eda.model.User; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; diff --git a/event-queue/etc/event-queue.urm.puml b/event-queue/etc/event-queue.urm.puml deleted file mode 100644 index e2aabee31..000000000 --- a/event-queue/etc/event-queue.urm.puml +++ /dev/null @@ -1,26 +0,0 @@ -@startuml -package com.iluwatar.event.queue { - class App { - + App() - + getAudioStream(filePath : String) : AudioInputStream {static} - + main(args : String[]) {static} - } - class Audio { - - MAX_PENDING : int {static} - - headIndex : int {static} - - pendingAudio : PlayMessage[] {static} - - tailIndex : int {static} - - updateThread : Thread {static} - + Audio() - + init() {static} - + playSound(stream : AudioInputStream, volume : float) {static} - + stopService() {static} - + update() {static} - } - class PlayMessage { - ~ stream : AudioInputStream - ~ volume : float - + PlayMessage() - } -} -@enduml \ No newline at end of file diff --git a/event-queue/pom.xml b/event-queue/pom.xml index 59dfa9119..1ef8e28af 100644 --- a/event-queue/pom.xml +++ b/event-queue/pom.xml @@ -30,13 +30,18 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT event-queue - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java index f8f1b1e3c..6534b563e 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java @@ -59,7 +59,7 @@ public class Audio { } /** - * This method stops the Update Method's thread. + * This method check the Update Method's thread is started. * @return boolean */ public static synchronized boolean isServiceRunning() { diff --git a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java index 8e31ec6c3..47f332526 100644 --- a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java +++ b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java @@ -22,13 +22,15 @@ */ package com.iluwatar.event.queue; -import static org.junit.Assert.*; -import java.io.IOException; +import org.junit.jupiter.api.Test; import javax.sound.sampled.UnsupportedAudioFileException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; /** * Testing the Audio service of the Queue @@ -53,7 +55,7 @@ public class AudioTest { // test that service is finished assertFalse(!Audio.isServiceRunning()); } - + /** * Test here that the Queue * @throws UnsupportedAudioFileException when the audio file is not supported diff --git a/event-sourcing/etc/event-sourcing.urm.puml b/event-sourcing/etc/event-sourcing.urm.puml deleted file mode 100644 index 207d238e6..000000000 --- a/event-sourcing/etc/event-sourcing.urm.puml +++ /dev/null @@ -1,184 +0,0 @@ -@startuml -package com.iluwatar.event.sourcing.journal { - class JsonFileJournal { - - aFile : File - - events : List - - index : int - + JsonFileJournal() - + readNext() : DomainEvent - + reset() - + write(domainEvent : DomainEvent) - } -} -package com.iluwatar.event.sourcing.processor { - class DomainEventProcessor { - - precessorJournal : ProcessorJournal - + DomainEventProcessor() - + process(domainEvent : DomainEvent) - + recover() - + setPrecessorJournal(precessorJournal : ProcessorJournal) - } -} -package com.iluwatar.event.sourcing.service { - class AccountService { - - eventProcessor : EventProcessor - + AccountService(eventProcessor : EventProcessor) - + createAccount(accountNo : int, owner : String) - } - class MoneyTransactionService { - - eventProcessor : EventProcessor - + MoneyTransactionService(eventProcessor : EventProcessor) - + depositMoney(accountNo : int, money : BigDecimal) - + transferMoney(accountNoFrom : int, accountNoTo : int, money : BigDecimal) - + withdrawalMoney(accountNo : int, money : BigDecimal) - } - class SequenceIdGenerator { - - sequenceId : long {static} - + SequenceIdGenerator() - + nextSequenceId() : long {static} - } -} -package com.iluwatar.event.sourcing.event { - class AccountCreateEvent { - - accountNo : int - - owner : String - + AccountCreateEvent(sequenceId : long, createdTime : long, accountNo : int, owner : String) - + getAccountNo() : int - + getOwner() : String - + process() - } - class MoneyDepositEvent { - - accountNo : int - - money : BigDecimal - + MoneyDepositEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal) - + getAccountNo() : int - + getMoney() : BigDecimal - + process() - } - class MoneyTransferEvent { - - accountNoFrom : int - - accountNoTo : int - - money : BigDecimal - + MoneyTransferEvent(sequenceId : long, createdTime : long, money : BigDecimal, accountNoFrom : int, accountNoTo : int) - + getAccountNoFrom() : int - + getAccountNoTo() : int - + getMoney() : BigDecimal - + process() - } - class MoneyWithdrawalEvent { - - accountNo : int - - money : BigDecimal - + MoneyWithdrawalEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal) - + getAccountNo() : int - + getMoney() : BigDecimal - + process() - } -} -package com.iluwatar.event.sourcing.gateway { - class AccountCreateContractSender { - + AccountCreateContractSender() - + sendContractInfo(account : Account) - } - class Gateways { - - accountCreateContractSender : AccountCreateContractSender {static} - - transactionLogger : TransactionLogger {static} - + Gateways() - + getAccountCreateContractSender() : AccountCreateContractSender {static} - + getTransactionLogger() : TransactionLogger {static} - } - class TransactionLogger { - + TransactionLogger() - + log(transaction : Transaction) - } -} -package com.iluwatar.event.sourcing.app { - class App { - + App() - + main(args : String[]) {static} - } -} -package com.iluwatar.event.sourcing.state { - class AccountAggregate { - - accounts : Map {static} - + AccountAggregate() - + getAccount(accountNo : int) : Account {static} - + putAccount(account : Account) {static} - + resetState() {static} - } -} -package com.iluwatar.event.sourcing.domain { - class Account { - - accountNo : int - - money : BigDecimal - - owner : String - - transactions : List - + Account(accountNo : int, owner : String) - + copy() : Account - - depositMoney(money : BigDecimal) : Transaction - + getAccountNo() : int - + getMoney() : BigDecimal - + getOwner() : String - + getTransactions() : List - - handleDeposit(money : BigDecimal, realTime : boolean) - + handleEvent(accountCreateEvent : AccountCreateEvent) - + handleEvent(moneyDepositEvent : MoneyDepositEvent) - + handleEvent(moneyWithdrawalEvent : MoneyWithdrawalEvent) - + handleTransferFromEvent(moneyTransferEvent : MoneyTransferEvent) - + handleTransferToEvent(moneyTransferEvent : MoneyTransferEvent) - - handleWithdrawal(money : BigDecimal, realTime : boolean) - + setMoney(money : BigDecimal) - + setTransactions(transactions : List) - + toString() : String - - withdrawMoney(money : BigDecimal) : Transaction - } - class Transaction { - - accountNo : int - - lastBalance : BigDecimal - - moneyIn : BigDecimal - - moneyOut : BigDecimal - + Transaction(accountNo : int, moneyIn : BigDecimal, moneyOut : BigDecimal, lastBalance : BigDecimal) - + getAccountNo() : int - + getLastBalance() : BigDecimal - + getMoneyIn() : BigDecimal - + getMoneyOut() : BigDecimal - + toString() : String - } -} -package com.iluwatar.event.sourcing.api { - abstract class DomainEvent { - - createdTime : long - - eventClassName : String - - realTime : boolean - - sequenceId : long - + DomainEvent(sequenceId : long, createdTime : long, eventClassName : String) - + getCreatedTime() : long - + getEventClassName() : String - + getSequenceId() : long - + isRealTime() : boolean - + process() {abstract} - + setRealTime(realTime : boolean) - } - interface EventProcessor { - + process(DomainEvent) {abstract} - + recover() {abstract} - + setPrecessorJournal(ProcessorJournal) {abstract} - } - interface ProcessorJournal { - + readNext() : DomainEvent {abstract} - + reset() {abstract} - + write(DomainEvent) {abstract} - } -} -Gateways --> "-accountCreateContractSender" AccountCreateContractSender -DomainEventProcessor --> "-precessorJournal" ProcessorJournal -Account --> "-transactions" Transaction -Gateways --> "-transactionLogger" TransactionLogger -AccountService --> "-eventProcessor" EventProcessor -MoneyTransactionService --> "-eventProcessor" EventProcessor -AccountCreateEvent --|> DomainEvent -MoneyDepositEvent --|> DomainEvent -MoneyTransferEvent --|> DomainEvent -MoneyWithdrawalEvent --|> DomainEvent -JsonFileJournal ..|> ProcessorJournal -DomainEventProcessor ..|> EventProcessor -@enduml \ No newline at end of file diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 35d462cb1..a17d02379 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -30,13 +30,18 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT event-sourcing - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/event-sourcing/src/test/java/IntegrationTest.java b/event-sourcing/src/test/java/IntegrationTest.java index 5a3f5718a..aab1ea7ea 100644 --- a/event-sourcing/src/test/java/IntegrationTest.java +++ b/event-sourcing/src/test/java/IntegrationTest.java @@ -21,20 +21,21 @@ * THE SOFTWARE. */ -import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; -import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; - import com.iluwatar.event.sourcing.domain.Account; import com.iluwatar.event.sourcing.event.AccountCreateEvent; import com.iluwatar.event.sourcing.event.MoneyDepositEvent; import com.iluwatar.event.sourcing.event.MoneyTransferEvent; import com.iluwatar.event.sourcing.processor.DomainEventProcessor; import com.iluwatar.event.sourcing.state.AccountAggregate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.math.BigDecimal; import java.util.Date; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; + +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Intergartion Test for Event Sourcing state recovery @@ -51,7 +52,7 @@ public class IntegrationTest { /** * Initialize. */ - @Before + @BeforeEach public void initialize() { eventProcessor = new DomainEventProcessor(); } @@ -90,10 +91,9 @@ public class IntegrationTest { Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); - Assert.assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), + assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), accountOfDaenerysAfterShotDown.getMoney()); - Assert - .assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); + assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); } } \ No newline at end of file diff --git a/execute-around/README.md b/execute-around/README.md index e0ae128b5..f669f18ff 100644 --- a/execute-around/README.md +++ b/execute-around/README.md @@ -3,7 +3,6 @@ layout: pattern title: Execute Around folder: execute-around permalink: /patterns/execute-around/ -pumlid: NSZ14G8n20NGLhI0XBlT865suoGa0n_NylNixSsxTvEHJTF7xGHsF8YShtfqdFdCK9TbK4ELDQcFl1ZizE8tbwRH3okR0NKBcXm_a7vK4bhOLreZXVnLJPzrvnnV categories: Other tags: - Java diff --git a/execute-around/etc/execute-around.urm.puml b/execute-around/etc/execute-around.urm.puml deleted file mode 100644 index fd01a5fe1..000000000 --- a/execute-around/etc/execute-around.urm.puml +++ /dev/null @@ -1,14 +0,0 @@ -@startuml -package com.iluwatar.execute.around { - class App { - + App() - + main(args : String[]) {static} - } - interface FileWriterAction { - + writeFile(FileWriter) {abstract} - } - class SimpleFileWriter { - + SimpleFileWriter(filename : String, action : FileWriterAction) - } -} -@enduml \ No newline at end of file diff --git a/execute-around/pom.xml b/execute-around/pom.xml index c4b3ac504..2e43c3e4b 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT execute-around - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-migrationsupport test diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java index 7604db16d..298f7e0d7 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.execute.around; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -42,8 +42,8 @@ public class AppTest { App.main(args); } - @Before - @After + @BeforeEach + @AfterEach public void cleanup() { File file = new File("testfile.txt"); file.delete(); diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java index fd13a92a9..22bdf68f7 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -22,23 +22,26 @@ */ package com.iluwatar.execute.around; -import org.junit.Assert; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/12/15 - 3:21 PM * * @author Jeroen Meulemeester */ +@EnableRuleMigrationSupport public class SimpleFileWriterTest { /** @@ -53,7 +56,7 @@ public class SimpleFileWriterTest { @Test public void testWriterNotNull() throws Exception { final File temporaryFile = this.testFolder.newFile(); - new SimpleFileWriter(temporaryFile.getPath(), Assert::assertNotNull); + new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull); } /** @@ -64,7 +67,7 @@ public class SimpleFileWriterTest { final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); assertFalse(nonExistingFile.exists()); - new SimpleFileWriter(nonExistingFile.getPath(), Assert::assertNotNull); + new SimpleFileWriter(nonExistingFile.getPath(), Assertions::assertNotNull); assertTrue(nonExistingFile.exists()); } @@ -85,11 +88,13 @@ public class SimpleFileWriterTest { /** * Verify if an {@link IOException} during the write ripples through */ - @Test(expected = IOException.class) + @Test public void testIoException() throws Exception { - final File temporaryFile = this.testFolder.newFile(); - new SimpleFileWriter(temporaryFile.getPath(), writer -> { - throw new IOException(""); + assertThrows(IOException.class, () -> { + final File temporaryFile = this.testFolder.newFile(); + new SimpleFileWriter(temporaryFile.getPath(), writer -> { + throw new IOException(""); + }); }); } diff --git a/extension-objects/etc/extension-objects.urm.puml b/extension-objects/etc/extension-objects.urm.puml deleted file mode 100644 index 02af47ddf..000000000 --- a/extension-objects/etc/extension-objects.urm.puml +++ /dev/null @@ -1,2 +0,0 @@ -@startuml -@enduml \ No newline at end of file diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml index c5ee535fe..bd68a2758 100644 --- a/extension-objects/pom.xml +++ b/extension-objects/pom.xml @@ -29,15 +29,20 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 extension-objects - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/extension-objects/src/test/java/AppTest.java b/extension-objects/src/test/java/AppTest.java index 485788112..f3111bebb 100644 --- a/extension-objects/src/test/java/AppTest.java +++ b/extension-objects/src/test/java/AppTest.java @@ -20,7 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.Test; + +import org.junit.jupiter.api.Test; /** * Created by Srdjan on 03-May-17. diff --git a/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/extension-objects/src/test/java/concreteextensions/CommanderTest.java index 11f0cc60e..5dac551f4 100644 --- a/extension-objects/src/test/java/concreteextensions/CommanderTest.java +++ b/extension-objects/src/test/java/concreteextensions/CommanderTest.java @@ -22,7 +22,7 @@ */ package concreteextensions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import units.CommanderUnit; /** diff --git a/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/extension-objects/src/test/java/concreteextensions/SergeantTest.java index 2deddca90..f26830e2c 100644 --- a/extension-objects/src/test/java/concreteextensions/SergeantTest.java +++ b/extension-objects/src/test/java/concreteextensions/SergeantTest.java @@ -22,7 +22,7 @@ */ package concreteextensions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import units.SergeantUnit; /** diff --git a/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/extension-objects/src/test/java/concreteextensions/SoldierTest.java index affc6ee8b..a9a6c4768 100644 --- a/extension-objects/src/test/java/concreteextensions/SoldierTest.java +++ b/extension-objects/src/test/java/concreteextensions/SoldierTest.java @@ -22,7 +22,7 @@ */ package concreteextensions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import units.SoldierUnit; /** diff --git a/extension-objects/src/test/java/units/CommanderUnitTest.java b/extension-objects/src/test/java/units/CommanderUnitTest.java index 8f4c1ca8d..536c3ae3f 100644 --- a/extension-objects/src/test/java/units/CommanderUnitTest.java +++ b/extension-objects/src/test/java/units/CommanderUnitTest.java @@ -23,10 +23,10 @@ package units; import abstractextensions.CommanderExtension; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Created by Srdjan on 03-May-17. diff --git a/extension-objects/src/test/java/units/SergeantUnitTest.java b/extension-objects/src/test/java/units/SergeantUnitTest.java index de773b59e..ac518b488 100644 --- a/extension-objects/src/test/java/units/SergeantUnitTest.java +++ b/extension-objects/src/test/java/units/SergeantUnitTest.java @@ -23,10 +23,10 @@ package units; import abstractextensions.SergeantExtension; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Created by Srdjan on 03-May-17. diff --git a/extension-objects/src/test/java/units/SoldierUnitTest.java b/extension-objects/src/test/java/units/SoldierUnitTest.java index 06a1f7611..1aeb9a3cd 100644 --- a/extension-objects/src/test/java/units/SoldierUnitTest.java +++ b/extension-objects/src/test/java/units/SoldierUnitTest.java @@ -23,10 +23,10 @@ package units; import abstractextensions.SoldierExtension; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Created by Srdjan on 03-May-17. diff --git a/extension-objects/src/test/java/units/UnitTest.java b/extension-objects/src/test/java/units/UnitTest.java index a7d530032..389c9f753 100644 --- a/extension-objects/src/test/java/units/UnitTest.java +++ b/extension-objects/src/test/java/units/UnitTest.java @@ -22,10 +22,10 @@ */ package units; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Created by Srdjan on 03-May-17. diff --git a/facade/README.md b/facade/README.md index 66ca84256..7caa89d94 100644 --- a/facade/README.md +++ b/facade/README.md @@ -3,7 +3,6 @@ layout: pattern title: Facade folder: facade permalink: /patterns/facade/ -pumlid: BSP15eCm20N0gxG7CEoz3ILKqvTW7dpq-hhehERTJ7fMJU-l7PYn4ZbVPMlOyvEXBeT13KMEGQtdnM2d7v-yL8sssJ8PKBUWmV64lYnSbHJoRqaVPUReDm00 categories: Structural tags: - Java @@ -203,7 +202,7 @@ Use the Facade pattern when * you want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients needing more customizability will need to look beyond the facade. * there are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability. -* you want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, the you can simplify the dependencies between them by making them communicate with each other solely through their facades +* you want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades. ## Credits diff --git a/facade/pom.xml b/facade/pom.xml index d699ac8fe..deb56a382 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT facade - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java index e890f42d4..366315e9e 100644 --- a/facade/src/test/java/com/iluwatar/facade/AppTest.java +++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.facade; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 6457307cf..19987acbc 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -25,16 +25,16 @@ package com.iluwatar.facade; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/9/15 - 9:40 PM @@ -45,12 +45,12 @@ public class DwarvenGoldmineFacadeTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/factory-kit/README.md b/factory-kit/README.md index b47cbff76..c25701047 100644 --- a/factory-kit/README.md +++ b/factory-kit/README.md @@ -3,7 +3,6 @@ layout: pattern title: Factory Kit folder: factory-kit permalink: /patterns/factory-kit/ -pumlid: JST15i8m20N0g-W14lRU1YcsQ4BooCS-RwzBTpDNSscvQKQx7C1SDwBWi-w68--vD6Gur55bTBAM9uE3dlpcikcotSjaGCCNTLu_q8C58pxbPI25_Bzcz3gpjoy0 categories: Creational tags: - Java diff --git a/factory-kit/etc/factory-kit.urm.puml b/factory-kit/etc/factory-kit.urm.puml deleted file mode 100644 index 23cf658f4..000000000 --- a/factory-kit/etc/factory-kit.urm.puml +++ /dev/null @@ -1,46 +0,0 @@ -@startuml -package com.iluwatar.factorykit { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Axe { - + Axe() - + toString() : String - } - class Bow { - + Bow() - + toString() : String - } - interface Builder { - + add(WeaponType, Supplier) {abstract} - } - class Spear { - + Spear() - + toString() : String - } - class Sword { - + Sword() - + toString() : String - } - interface Weapon { - } - interface WeaponFactory { - + create(WeaponType) : Weapon {abstract} - + factory(consumer : Consumer) : WeaponFactory {static} - } - enum WeaponType { - + AXE {static} - + BOW {static} - + SPEAR {static} - + SWORD {static} - + valueOf(name : String) : WeaponType {static} - + values() : WeaponType[] {static} - } -} -Axe ..|> Weapon -Bow ..|> Weapon -Spear ..|> Weapon -Sword ..|> Weapon -@enduml \ No newline at end of file diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index 50942b3a0..71973928f 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -30,18 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT factory-kit - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java index 4d8691ef0..0be22b9b0 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java @@ -23,7 +23,7 @@ package com.iluwatar.factorykit.app; import com.iluwatar.factorykit.App; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application Test Entrypoint diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java index 3f732546d..f15223feb 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java @@ -22,24 +22,25 @@ */ package com.iluwatar.factorykit.factorykit; -import static org.junit.Assert.assertTrue; - import com.iluwatar.factorykit.Axe; import com.iluwatar.factorykit.Spear; import com.iluwatar.factorykit.Sword; import com.iluwatar.factorykit.Weapon; import com.iluwatar.factorykit.WeaponFactory; import com.iluwatar.factorykit.WeaponType; -import org.junit.Before; -import org.junit.Test; -/** +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + + /** * Test Factory Kit Pattern */ public class FactoryKitTest { private WeaponFactory factory; - @Before + @BeforeEach public void init() { factory = WeaponFactory.factory(builder -> { builder.add(WeaponType.SPEAR, Spear::new); @@ -83,6 +84,6 @@ public class FactoryKitTest { * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, Class clazz) { - assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon)); + assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); } } diff --git a/factory-method/README.md b/factory-method/README.md index 07c92d0e5..ab3739ac3 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -3,7 +3,6 @@ layout: pattern title: Factory Method folder: factory-method permalink: /patterns/factory-method/ -pumlid: NSZB3G8n30N0Lg20n7UwCOxPP9MVx6TMT0zdRgEvjoazYeRrMmMsFuYChtmqr7Y6gycQq8aiQr3hSJ7OwEGtfwBUZfas0shJQR3_G2yMBFkaeQYha4B-AeUDl6FqBm00 categories: Creational tags: - Java @@ -70,7 +69,11 @@ Use the Factory Method pattern when * a class wants its subclasses to specify the objects it creates * classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate -## Known uses +## Presentations + +* [Factory Method Pattern](etc/presentation.html) + +## Real world examples * [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-) diff --git a/factory-method/etc/diagram1.png b/factory-method/etc/diagram1.png new file mode 100644 index 000000000..fa325edf0 Binary files /dev/null and b/factory-method/etc/diagram1.png differ diff --git a/factory-method/etc/presentation.html b/factory-method/etc/presentation.html new file mode 100644 index 000000000..a78057836 --- /dev/null +++ b/factory-method/etc/presentation.html @@ -0,0 +1,185 @@ + + + + + Design Patterns - Factory Method Presentation + + + + + + + + + \ No newline at end of file diff --git a/factory-method/pom.xml b/factory-method/pom.xml index 61d0058ae..4cad86fdd 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT factory-method - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java index 88b40d4fe..4a73077c1 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.factory.method; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java index 4f3a5930d..75d8e4677 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.factory.method; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * The Factory Method is a creational design pattern which uses factory methods to deal with the @@ -53,7 +53,7 @@ public class FactoryMethodTest { } /** - * Testing {@link OrcBlacksmith} to produce a AXE asserting that the Weapon is an instance + * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance * of {@link OrcWeapon}. */ @Test @@ -94,8 +94,7 @@ public class FactoryMethodTest { * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { - assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon)); - assertEquals("Weapon must be of weaponType: " + clazz.getName(), expectedWeaponType, - weapon.getWeaponType()); + assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); + assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); } } diff --git a/feature-toggle/README.md b/feature-toggle/README.md index 06d956178..c466b8a94 100644 --- a/feature-toggle/README.md +++ b/feature-toggle/README.md @@ -3,7 +3,6 @@ layout: pattern title: Feature Toggle folder: feature-toggle permalink: /patterns/feature-toggle/ -pumlid: NSZ14G8X30NGLhG0oDrk8XjPd12OvCTjNy_UthpxiAPvIBhUJc37WyZvgdtWp6U6U5i6CTIs9WtDYy5ER_vmEIH6jx8P4BUWoV43lOIHBWMhTnKIjB-gwRFkdFe5 categories: Behavioral tags: - Java diff --git a/feature-toggle/etc/feature-toggle.urm.puml b/feature-toggle/etc/feature-toggle.urm.puml deleted file mode 100644 index 0febb2631..000000000 --- a/feature-toggle/etc/feature-toggle.urm.puml +++ /dev/null @@ -1,48 +0,0 @@ -@startuml -package com.iluwatar.featuretoggle.pattern { - interface Service { - + getWelcomeMessage(User) : String {abstract} - + isEnhanced() : boolean {abstract} - } -} -package com.iluwatar.featuretoggle.user { - class User { - - name : String - + User(name : String) - + toString() : String - } - class UserGroup { - - freeGroup : List {static} - - paidGroup : List {static} - + UserGroup() - + addUserToFreeGroup(user : User) {static} - + addUserToPaidGroup(user : User) {static} - + isPaid(user : User) : boolean {static} - } -} -package com.iluwatar.featuretoggle.pattern.tieredversion { - class TieredFeatureToggleVersion { - + TieredFeatureToggleVersion() - + getWelcomeMessage(user : User) : String - + isEnhanced() : boolean - } -} -package com.iluwatar.featuretoggle.pattern.propertiesversion { - class PropertiesFeatureToggleVersion { - - isEnhanced : boolean - + PropertiesFeatureToggleVersion(properties : Properties) - + getWelcomeMessage(user : User) : String - + isEnhanced() : boolean - } -} -package com.iluwatar.featuretoggle { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } -} -UserGroup --> "-freeGroup" User -PropertiesFeatureToggleVersion ..|> Service -TieredFeatureToggleVersion ..|> Service -@enduml \ No newline at end of file diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index b8201aa4f..665847e5e 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -39,10 +39,14 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test - \ No newline at end of file diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java index 846b46bcf..9f0d377fa 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java @@ -23,30 +23,36 @@ package com.iluwatar.featuretoggle.pattern.propertiesversion; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.user.User; +import org.junit.jupiter.api.Test; + import java.util.Properties; -import org.junit.Test; + +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; /** * Test Properties Toggle */ public class PropertiesFeatureToggleVersionTest { - @Test(expected = IllegalArgumentException.class) + @Test public void testNullPropertiesPassed() throws Exception { - new PropertiesFeatureToggleVersion(null); + assertThrows(IllegalArgumentException.class, () -> { + new PropertiesFeatureToggleVersion(null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNonBooleanProperty() throws Exception { - final Properties properties = new Properties(); - properties.setProperty("enhancedWelcome", "Something"); - new PropertiesFeatureToggleVersion(properties); + assertThrows(IllegalArgumentException.class, () -> { + final Properties properties = new Properties(); + properties.setProperty("enhancedWelcome", "Something"); + new PropertiesFeatureToggleVersion(properties); + }); } @Test diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java index 3966032d5..0ed0afea9 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java @@ -22,14 +22,14 @@ */ package com.iluwatar.featuretoggle.pattern.tieredversion; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.UserGroup; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Tiered Feature Toggle @@ -40,7 +40,7 @@ public class TieredFeatureToggleVersionTest { final User freeUser = new User("Alan Defect"); final Service service = new TieredFeatureToggleVersion(); - @Before + @BeforeEach public void setUp() throws Exception { UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToFreeGroup(freeUser); diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java index b2c6e5859..2771655dd 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java @@ -22,10 +22,11 @@ */ package com.iluwatar.featuretoggle.user; -import static junit.framework.TestCase.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test User Group specific feature @@ -46,17 +47,21 @@ public class UserGroupTest { assertTrue(UserGroup.isPaid(user)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddUserToPaidWhenOnFree() throws Exception { User user = new User("Paid User"); UserGroup.addUserToFreeGroup(user); - UserGroup.addUserToPaidGroup(user); + assertThrows(IllegalArgumentException.class, () -> { + UserGroup.addUserToPaidGroup(user); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddUserToFreeWhenOnPaid() throws Exception { User user = new User("Free User"); UserGroup.addUserToPaidGroup(user); - UserGroup.addUserToFreeGroup(user); + assertThrows(IllegalArgumentException.class, () -> { + UserGroup.addUserToFreeGroup(user); + }); } } diff --git a/fluentinterface/README.md b/fluentinterface/README.md index 8bf43d974..767792da7 100644 --- a/fluentinterface/README.md +++ b/fluentinterface/README.md @@ -3,7 +3,6 @@ layout: pattern title: Fluent Interface folder: fluentinterface permalink: /patterns/fluentinterface/ -pumlid: NOj93eCm302_KXv0VEzlN6F0bMCYB_3zvjpRQ3IpY97MnkNwEZD7l04SdtP8dlMfOAVBaYqRNHr4wy54Xo_Uk6uSSjWwC9FT0Zh61DYrPY_pyXs9WPF-NIllRLJN7m00 categories: Other tags: - Java diff --git a/fluentinterface/etc/fluentinterface.urm.puml b/fluentinterface/etc/fluentinterface.urm.puml deleted file mode 100644 index ef71a0f4b..000000000 --- a/fluentinterface/etc/fluentinterface.urm.puml +++ /dev/null @@ -1,72 +0,0 @@ -@startuml -package com.iluwatar.fluentinterface.fluentiterable.simple { - class SimpleFluentIterable { - - iterable : Iterable - # SimpleFluentIterable(iterable : Iterable) - + asList() : List - + filter(predicate : Predicate) : FluentIterable - + first() : Optional - + first(count : int) : FluentIterable - + forEach(action : Consumer) - + from(iterable : Iterable) : FluentIterable {static} - + fromCopyOf(iterable : Iterable) : FluentIterable {static} - + getRemainingElementsCount() : int - + iterator() : Iterator - + last() : Optional - + last(count : int) : FluentIterable - + map(function : Function) : FluentIterable - + spliterator() : Spliterator - + toList(iterator : Iterator) : List {static} - } -} -package com.iluwatar.fluentinterface.app { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - - negatives() : Predicate {static} - - positives() : Predicate {static} - - prettyPrint(delimiter : String, prefix : String, iterable : Iterable) {static} - - prettyPrint(prefix : String, iterable : Iterable) {static} - - transformToString() : Function {static} - } -} -package com.iluwatar.fluentinterface.fluentiterable.lazy { - abstract class DecoratingIterator { - # fromIterator : Iterator - - next : E - + DecoratingIterator(fromIterator : Iterator) - + computeNext() : E {abstract} - + hasNext() : boolean - + next() : E - } - class LazyFluentIterable { - - iterable : Iterable - # LazyFluentIterable() - # LazyFluentIterable(iterable : Iterable) - + asList() : List - + filter(predicate : Predicate) : FluentIterable - + first() : Optional - + first(count : int) : FluentIterable - + from(iterable : Iterable) : FluentIterable {static} - + iterator() : Iterator - + last() : Optional - + last(count : int) : FluentIterable - + map(function : Function) : FluentIterable - } -} -package com.iluwatar.fluentinterface.fluentiterable { - interface FluentIterable { - + asList() : List {abstract} - + copyToList(iterable : Iterable) : List {static} - + filter(Predicate) : FluentIterable {abstract} - + first() : Optional {abstract} - + first(int) : FluentIterable {abstract} - + last() : Optional {abstract} - + last(int) : FluentIterable {abstract} - + map(Function) : FluentIterable {abstract} - } -} -LazyFluentIterable ..|> FluentIterable -SimpleFluentIterable ..|> FluentIterable -@enduml \ No newline at end of file diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml index 9c352f1a9..234504396 100644 --- a/fluentinterface/pom.xml +++ b/fluentinterface/pom.xml @@ -29,15 +29,20 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 fluentinterface - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java index 11740bf1a..6e21bd8e4 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -22,7 +22,8 @@ */ package com.iluwatar.fluentinterface.app; -import org.junit.Test; +import org.junit.jupiter.api.Test; + /** * Application Test Entry */ diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java index 4cc2b1a7a..0eb9e003a 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -22,13 +22,23 @@ */ package com.iluwatar.fluentinterface.fluentiterable; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Spliterator; import java.util.function.Consumer; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +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 static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Date: 12/12/15 - 7:00 PM @@ -56,7 +66,7 @@ public abstract class FluentIterableTest { @Test public void testFirstEmptyCollection() throws Exception { - final List integers = Collections.emptyList(); + final List integers = Collections.emptyList(); final Optional first = createFluentIterable(integers).first(); assertNotNull(first); assertFalse(first.isPresent()); diff --git a/flux/README.md b/flux/README.md index e36b73900..7ac312c44 100644 --- a/flux/README.md +++ b/flux/README.md @@ -3,7 +3,6 @@ layout: pattern title: Flux folder: flux permalink: /patterns/flux/ -pumlid: 7SP14eCm20NGg-W13FlU1YFLE0GpyAazVZk-rPkRLSrDqdKwW14l8kUxx0r7hXdYzJA8eTIhKzEy6UnqyeUNJQBjjWm6n2seS_n3Ryql2UgJajxBoAu_ categories: Presentation Tier tags: - Java diff --git a/flux/etc/flux.urm.puml b/flux/etc/flux.urm.puml deleted file mode 100644 index 11ac26d60..000000000 --- a/flux/etc/flux.urm.puml +++ /dev/null @@ -1,117 +0,0 @@ -@startuml -package com.iluwatar.flux.view { - class ContentView { - - LOGGER : Logger {static} - - content : Content - + ContentView() - + render() - + storeChanged(store : Store) - } - class MenuView { - - LOGGER : Logger {static} - - selected : MenuItem - + MenuView() - + itemClicked(item : MenuItem) - + render() - + storeChanged(store : Store) - } - interface View { - + render() {abstract} - + storeChanged(Store) {abstract} - } -} -package com.iluwatar.flux.action { - abstract class Action { - - type : ActionType - + Action(type : ActionType) - + getType() : ActionType - } - enum ActionType { - + CONTENT_CHANGED {static} - + MENU_ITEM_SELECTED {static} - + valueOf(name : String) : ActionType {static} - + values() : ActionType[] {static} - } - enum Content { - + COMPANY {static} - + PRODUCTS {static} - - title : String - + toString() : String - + valueOf(name : String) : Content {static} - + values() : Content[] {static} - } - class ContentAction { - - content : Content - + ContentAction(content : Content) - + getContent() : Content - } - class MenuAction { - - menuItem : MenuItem - + MenuAction(menuItem : MenuItem) - + getMenuItem() : MenuItem - } - enum MenuItem { - + COMPANY {static} - + HOME {static} - + PRODUCTS {static} - - title : String - + toString() : String - + valueOf(name : String) : MenuItem {static} - + values() : MenuItem[] {static} - } -} -package com.iluwatar.flux.app { - class App { - + App() - + main(args : String[]) {static} - } -} -package com.iluwatar.flux.store { - class ContentStore { - - content : Content - + ContentStore() - + getContent() : Content - + onAction(action : Action) - } - class MenuStore { - - selected : MenuItem - + MenuStore() - + getSelected() : MenuItem - + onAction(action : Action) - } - abstract class Store { - - views : List - + Store() - # notifyChange() - + onAction(Action) {abstract} - + registerView(view : View) - } -} -package com.iluwatar.flux.dispatcher { - class Dispatcher { - - instance : Dispatcher {static} - - stores : List - - Dispatcher() - - dispatchAction(action : Action) - + getInstance() : Dispatcher {static} - + menuItemSelected(menuItem : MenuItem) - + registerStore(store : Store) - } -} -MenuAction --> "-menuItem" MenuItem -Action --> "-type" ActionType -Dispatcher --> "-instance" Dispatcher -MenuStore --> "-selected" MenuItem -ContentView --> "-content" Content -Dispatcher --> "-stores" Store -MenuView --> "-selected" MenuItem -Store --> "-views" View -ContentAction --> "-content" Content -ContentStore --> "-content" Content -ContentAction --|> Action -MenuAction --|> Action -ContentStore --|> Store -MenuStore --|> Store -ContentView ..|> View -MenuView ..|> View -@enduml \ No newline at end of file diff --git a/flux/pom.xml b/flux/pom.xml index 01e3c4a90..6b9b968c8 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT flux - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java index 3ddf7805c..53db61ddd 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.flux.action; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/12/15 - 10:11 PM diff --git a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java index e40133586..60f19d8f3 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.flux.action; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/12/15 - 10:15 PM diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java index 7e6475ee7..0a8375916 100644 --- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java +++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.flux.app; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java index b245de6ac..54760557b 100644 --- a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java +++ b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -29,8 +29,8 @@ import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.store.Store; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.lang.reflect.Constructor; @@ -38,9 +38,9 @@ import java.lang.reflect.Field; import java.util.List; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -58,7 +58,7 @@ public class DispatcherTest { * Replace the instance with a fresh one before each test to make sure test cases have no * influence on each other. */ - @Before + @BeforeEach public void setUp() throws Exception { final Constructor constructor; constructor = Dispatcher.class.getDeclaredConstructor(); diff --git a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java index 85c0e46f4..02a16ef33 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -27,9 +27,9 @@ import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.view.View; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; diff --git a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java index 63d1dfdfb..aa432e1ff 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -27,9 +27,9 @@ import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.view.View; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; diff --git a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java index b97d751bf..c4498bacf 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -24,7 +24,7 @@ package com.iluwatar.flux.view; import com.iluwatar.flux.action.Content; import com.iluwatar.flux.store.ContentStore; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; diff --git a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java index 528549e9c..0967d51a8 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -27,7 +27,7 @@ import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.dispatcher.Dispatcher; import com.iluwatar.flux.store.MenuStore; import com.iluwatar.flux.store.Store; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; diff --git a/flyweight/README.md b/flyweight/README.md index 9a0e13e19..d65995755 100644 --- a/flyweight/README.md +++ b/flyweight/README.md @@ -3,7 +3,6 @@ layout: pattern title: Flyweight folder: flyweight permalink: /patterns/flyweight/ -pumlid: HSV94S8m3030Lg20M7-w4OvYAoCh7Xtnq3ty-Eq-MQlaJcdow17JNm26gpIEdkzqidffa4Qfrm2MN1XeSEADsqxEJRU94MJgCD1_W4C-YxZr08hwNqaRPUQGBm00 categories: Structural tags: - Java diff --git a/flyweight/pom.xml b/flyweight/pom.xml index d93f66681..58bbd95a8 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT flyweight - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index 96cc455a7..86d231e22 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.flyweight; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/12/15 - 10:54 PM diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java index 5d2d6815f..f7a33f050 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.flyweight; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/front-controller/README.md b/front-controller/README.md index c832674dc..a462a08e0 100644 --- a/front-controller/README.md +++ b/front-controller/README.md @@ -3,7 +3,6 @@ layout: pattern title: Front Controller folder: front-controller permalink: /patterns/front-controller/ -pumlid: PSlB3OGm303HLfO24j-t6nCC13bEvC_IFk6yjz6JPgbIE3OAvS_fFkmBe7Zde_ePQnXfwU8adajlK3bkT5Iuy8Tf8wk7f87kf6BGq6R0hlD8xwQTUG9v-SCSslA8nWy0 categories: Presentation Tier tags: - Java diff --git a/front-controller/etc/front-controller.urm.puml b/front-controller/etc/front-controller.urm.puml deleted file mode 100644 index 246e7657c..000000000 --- a/front-controller/etc/front-controller.urm.puml +++ /dev/null @@ -1,53 +0,0 @@ -@startuml -package com.iluwatar.front.controller { - class App { - + App() - + main(args : String[]) {static} - } - class ArcherCommand { - + ArcherCommand() - + process() - } - class ArcherView { - - LOGGER : Logger {static} - + ArcherView() - + display() - } - class CatapultCommand { - + CatapultCommand() - + process() - } - class CatapultView { - - LOGGER : Logger {static} - + CatapultView() - + display() - } - interface Command { - + process() {abstract} - } - class ErrorView { - - LOGGER : Logger {static} - + ErrorView() - + display() - } - class FrontController { - + FrontController() - - getCommand(request : String) : Command - - getCommandClass(request : String) : Class {static} - + handleRequest(request : String) - } - class UnknownCommand { - + UnknownCommand() - + process() - } - interface View { - + display() {abstract} - } -} -ArcherCommand ..|> Command -ArcherView ..|> View -CatapultCommand ..|> Command -CatapultView ..|> View -ErrorView ..|> View -UnknownCommand ..|> Command -@enduml \ No newline at end of file diff --git a/front-controller/pom.xml b/front-controller/pom.xml index 720f6d2ee..966e5becc 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -30,13 +30,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT front-controller - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java index dd15be495..f7fe59cf1 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.front.controller; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java index c68a4ebf6..ee13d47d7 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.front.controller; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/13/15 - 1:35 PM diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java index edb5032ed..9e8f986e2 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -23,40 +23,36 @@ package com.iluwatar.front.controller; import com.iluwatar.front.controller.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class CommandTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } - @Parameters - public static List data() { + static List dataProvider() { final List parameters = new ArrayList<>(); parameters.add(new Object[]{"Archer", "Displaying archers"}); parameters.add(new Object[]{"Catapult", "Displaying catapults"}); @@ -65,28 +61,12 @@ public class CommandTest { } /** - * The view that's been tested - */ - private final String request; - - /** - * The expected display message - */ - private final String displayMessage; - - /** - * Create a new instance of the {@link CommandTest} with the given view and expected message - * * @param request The request that's been tested * @param displayMessage The expected display message */ - public CommandTest(final String request, final String displayMessage) { - this.displayMessage = displayMessage; - this.request = request; - } - - @Test - public void testDisplay() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(String request, String displayMessage) { final FrontController frontController = new FrontController(); assertEquals(0, appender.getLogSize()); frontController.handleRequest(request); diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java index 5367403f9..4b4eb6fdd 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -23,40 +23,36 @@ package com.iluwatar.front.controller; import com.iluwatar.front.controller.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class FrontControllerTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } - @Parameters - public static List data() { + static List dataProvider() { final List parameters = new ArrayList<>(); parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); @@ -65,30 +61,14 @@ public class FrontControllerTest { } /** - * The view that's been tested - */ - private final Command command; - - /** - * The expected display message - */ - private final String displayMessage; - - /** - * Create a new instance of the {@link FrontControllerTest} with the given view and expected message - * * @param command The command that's been tested * @param displayMessage The expected display message */ - public FrontControllerTest(final Command command, final String displayMessage) { - this.displayMessage = displayMessage; - this.command = command; - } - - @Test - public void testDisplay() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(Command command, String displayMessage) { assertEquals(0, appender.getLogSize()); - this.command.process(); + command.process(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java index a5786b97e..a0c303235 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -23,40 +23,36 @@ package com.iluwatar.front.controller; import com.iluwatar.front.controller.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class ViewTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } - @Parameters - public static List data() { + static List dataProvider() { final List parameters = new ArrayList<>(); parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); @@ -65,30 +61,14 @@ public class ViewTest { } /** - * The view that's been tested - */ - private final View view; - - /** - * The expected display message - */ - private final String displayMessage; - - /** - * Create a new instance of the {@link ViewTest} with the given view and expected message - * * @param view The view that's been tested * @param displayMessage The expected display message */ - public ViewTest(final View view, final String displayMessage) { - this.displayMessage = displayMessage; - this.view = view; - } - - @Test - public void testDisplay() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(View view, String displayMessage) { assertEquals(0, appender.getLogSize()); - this.view.display(); + view.display(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } diff --git a/guarded-suspension/README.md b/guarded-suspension/README.md index 3e00539a2..35044f9b2 100644 --- a/guarded-suspension/README.md +++ b/guarded-suspension/README.md @@ -3,7 +3,6 @@ layout: pattern title: Guarded Suspension folder: guarded-suspension permalink: /patterns/guarded-suspension/ -pumlid: ROux3W8n30LxJW47IDnJxLLCOcMD4YVoXxq-eQTwev56UeSvgiVejmTBwL4fjDzFzsLF0CKhD_OpNc6aPOgJU2vp0FUuSAVmnW-cIiPDqa9tKZ4OQ1kW1MgbcYniaHXF0VBoH-VGaTVlnK5Iztu1 categories: Concurrency tags: - Java diff --git a/guarded-suspension/etc/guarded-suspension.urm.puml b/guarded-suspension/etc/guarded-suspension.urm.puml deleted file mode 100644 index 45a7d3790..000000000 --- a/guarded-suspension/etc/guarded-suspension.urm.puml +++ /dev/null @@ -1,15 +0,0 @@ -@startuml -package com.iluwatar.guarded.suspension { - class App { - + App() - + main(args : String[]) {static} - } - class GuardedQueue { - - LOGGER : Logger {static} - - sourceList : Queue - + GuardedQueue() - + get() : Integer - + put(e : Integer) - } -} -@enduml \ No newline at end of file diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index 9b6d70ef8..5ac0a6e32 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -30,14 +30,19 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT jar guarded-suspension - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java index 5a741d399..2834bd4ef 100644 --- a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java +++ b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java @@ -22,13 +22,14 @@ */ package com.iluwatar.guarded.suspension; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Test for Guarded Queue */ @@ -47,15 +48,14 @@ public class GuardedQueueTest { } catch (InterruptedException e) { e.printStackTrace(); } - Assert.assertEquals(Integer.valueOf(10), value); + assertEquals(Integer.valueOf(10), value); } @Test public void testPut() { GuardedQueue g = new GuardedQueue(); g.put(12); - Assert.assertEquals(Integer.valueOf(12), g.get()); - + assertEquals(Integer.valueOf(12), g.get()); } } diff --git a/half-sync-half-async/README.md b/half-sync-half-async/README.md index 55891e770..8a091f813 100644 --- a/half-sync-half-async/README.md +++ b/half-sync-half-async/README.md @@ -3,7 +3,6 @@ layout: pattern title: Half-Sync/Half-Async folder: half-sync-half-async permalink: /patterns/half-sync-half-async/ -pumlid: RScv3SCm3030LU819FRPXg5fIm552tnYPFiyjRi3RkbAaYkdoQr5JBy369vrxz7oaSv6XmPhL3e6TCaJ0msU-CAoilTToyG8DdKOw5z0GzcAlvNAN_WZSD1brBHHPmxv0000 categories: Concurrency tags: - Java diff --git a/half-sync-half-async/etc/half-sync-half-async.urm.puml b/half-sync-half-async/etc/half-sync-half-async.urm.puml deleted file mode 100644 index 1dd9c1d83..000000000 --- a/half-sync-half-async/etc/half-sync-half-async.urm.puml +++ /dev/null @@ -1,31 +0,0 @@ -@startuml -package com.iluwatar.halfsynchalfasync { - class App { - - LOGGER : Logger {static} - + App() - - ap(i : long) : long {static} - + main(args : String[]) {static} - } - ~class ArithmeticSumTask { - - n : long - + ArithmeticSumTask(n : long) - + call() : Long - + onError(throwable : Throwable) - + onPostCall(result : Long) - + onPreCall() - } - interface AsyncTask { - + call() : O {abstract} - + onError(Throwable) {abstract} - + onPostCall(O) {abstract} - + onPreCall() {abstract} - } - class AsynchronousService { - - service : ExecutorService - + AsynchronousService(workQueue : BlockingQueue) - + execute(task : AsyncTask) - } -} -ArithmeticSumTask ..+ App -ArithmeticSumTask ..|> AsyncTask -@enduml \ No newline at end of file diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index 16940cefa..3ed2da411 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT half-sync-half-async - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java index 2dfc2bf5c..dea242f85 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.halfsynchalfasync; -import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.util.concurrent.ExecutionException; /** * diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java index c6d00b1ac..a5496415e 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -22,14 +22,21 @@ */ package com.iluwatar.halfsynchalfasync; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.io.IOException; import java.util.concurrent.LinkedBlockingQueue; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; /** * Date: 12/12/15 - 11:15 PM diff --git a/hexagonal/README.md b/hexagonal/README.md index dc1566625..7d27f4b62 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -3,7 +3,6 @@ layout: pattern title: Hexagonal Architecture folder: hexagonal permalink: /patterns/hexagonal/ -pumlid: HSTB4W8X30N0g-W1XkozpPD90LO8L3wEnzUTk-xxq2fvSfhSUiJs1v7XAcr4psSwMrqQh57gcZGaBmICNdZZEDb7qsCZWasT9lm7wln1MmeXZlfVIPjbvvGl pumlformat: svg categories: Architectural tags: diff --git a/hexagonal/etc/hexagonal.urm.puml b/hexagonal/etc/hexagonal.urm.puml deleted file mode 100644 index 9ca6e6f9f..000000000 --- a/hexagonal/etc/hexagonal.urm.puml +++ /dev/null @@ -1,279 +0,0 @@ -@startuml -package com.iluwatar.hexagonal.sampledata { - class SampleData { - - PLAYERS : List {static} - + SampleData() - - getRandomPlayerDetails() : PlayerDetails {static} - + submitTickets(lotteryService : LotteryService, numTickets : int) {static} - } -} -package com.iluwatar.hexagonal.service { - class ConsoleLottery { - - LOGGER : Logger {static} - + ConsoleLottery() - - addFundsToLotteryAccount(bank : WireTransfers, scanner : Scanner) {static} - - checkTicket(service : LotteryService, scanner : Scanner) {static} - + main(args : String[]) {static} - - printMainMenu() {static} - - queryLotteryAccountFunds(bank : WireTransfers, scanner : Scanner) {static} - - readString(scanner : Scanner) : String {static} - - submitTicket(service : LotteryService, scanner : Scanner) {static} - } -} -package com.iluwatar.hexagonal.mongo { - class MongoConnectionPropertiesLoader { - - DEFAULT_HOST : String {static} - - DEFAULT_PORT : int {static} - + MongoConnectionPropertiesLoader() - + load() {static} - } -} -package com.iluwatar.hexagonal.domain { - class LotteryAdministration { - - notifications : LotteryEventLog - - repository : LotteryTicketRepository - - wireTransfers : WireTransfers - + LotteryAdministration(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) - + getAllSubmittedTickets() : Map - + performLottery() : LotteryNumbers - + resetLottery() - } - class LotteryConstants { - + PLAYER_MAX_SALDO : int {static} - + PRIZE_AMOUNT : int {static} - + SERVICE_BANK_ACCOUNT : String {static} - + SERVICE_BANK_ACCOUNT_SALDO : int {static} - + TICKET_PRIZE : int {static} - - LotteryConstants() - } - class LotteryNumbers { - + MAX_NUMBER : int {static} - + MIN_NUMBER : int {static} - + NUM_NUMBERS : int {static} - - numbers : Set - - LotteryNumbers() - - LotteryNumbers(givenNumbers : Set) - + create(givenNumbers : Set) : LotteryNumbers {static} - + createRandom() : LotteryNumbers {static} - + equals(obj : Object) : boolean - - generateRandomNumbers() - + getNumbers() : Set - + getNumbersAsString() : String - + hashCode() : int - + toString() : String - } - -class RandomNumberGenerator { - - randomIterator : OfInt - + RandomNumberGenerator(min : int, max : int) - + nextInt() : int - } - class LotteryService { - - notifications : LotteryEventLog - - repository : LotteryTicketRepository - - wireTransfers : WireTransfers - + LotteryService(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) - + checkTicketForPrize(id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult - + submitTicket(ticket : LotteryTicket) : Optional - } - class LotteryTicket { - - id : LotteryTicketId - - lotteryNumbers : LotteryNumbers - - playerDetails : PlayerDetails - + LotteryTicket(id : LotteryTicketId, details : PlayerDetails, numbers : LotteryNumbers) - + equals(obj : Object) : boolean - + getId() : LotteryTicketId - + getNumbers() : LotteryNumbers - + getPlayerDetails() : PlayerDetails - + hashCode() : int - + setId(id : LotteryTicketId) - + toString() : String - } - class LotteryTicketCheckResult { - - checkResult : CheckResult - - prizeAmount : int - + LotteryTicketCheckResult(result : CheckResult) - + LotteryTicketCheckResult(result : CheckResult, amount : int) - + equals(obj : Object) : boolean - + getPrizeAmount() : int - + getResult() : CheckResult - + hashCode() : int - } - enum CheckResult { - + NO_PRIZE {static} - + TICKET_NOT_SUBMITTED {static} - + WIN_PRIZE {static} - + valueOf(name : String) : CheckResult {static} - + values() : CheckResult[] {static} - } - class LotteryTicketId { - - id : int - - numAllocated : int {static} - + LotteryTicketId() - + LotteryTicketId(id : int) - + equals(o : Object) : boolean - + getId() : int - + hashCode() : int - + toString() : String - } - class LotteryUtils { - - LotteryUtils() - + checkTicketForPrize(repository : LotteryTicketRepository, id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult {static} - } - class PlayerDetails { - - bankAccountNumber : String - - emailAddress : String - - phoneNumber : String - + PlayerDetails(email : String, bankAccount : String, phone : String) - + equals(obj : Object) : boolean - + getBankAccount() : String - + getEmail() : String - + getPhoneNumber() : String - + hashCode() : int - + toString() : String - } -} -package com.iluwatar.hexagonal.banking { - class InMemoryBank { - - accounts : Map {static} - + InMemoryBank() - + getFunds(bankAccount : String) : int - + setFunds(bankAccount : String, amount : int) - + transferFunds(amount : int, sourceBackAccount : String, destinationBankAccount : String) : boolean - } - class MongoBank { - - DEFAULT_ACCOUNTS_COLLECTION : String {static} - - DEFAULT_DB : String {static} - - accountsCollection : MongoCollection - - database : MongoDatabase - - mongoClient : MongoClient - + MongoBank() - + MongoBank(dbName : String, accountsCollectionName : String) - + connect() - + connect(dbName : String, accountsCollectionName : String) - + getAccountsCollection() : MongoCollection - + getFunds(bankAccount : String) : int - + getMongoClient() : MongoClient - + getMongoDatabase() : MongoDatabase - + setFunds(bankAccount : String, amount : int) - + transferFunds(amount : int, sourceBackAccount : String, destinationBankAccount : String) : boolean - } - interface WireTransfers { - + getFunds(String) : int {abstract} - + setFunds(String, int) {abstract} - + transferFunds(int, String, String) : boolean {abstract} - } -} -package com.iluwatar.hexagonal.database { - class InMemoryTicketRepository { - - tickets : Map {static} - + InMemoryTicketRepository() - + deleteAll() - + findAll() : Map - + findById(id : LotteryTicketId) : Optional - + save(ticket : LotteryTicket) : Optional - } - interface LotteryTicketRepository { - + deleteAll() {abstract} - + findAll() : Map {abstract} - + findById(LotteryTicketId) : Optional {abstract} - + save(LotteryTicket) : Optional {abstract} - } - class MongoTicketRepository { - - DEFAULT_COUNTERS_COLLECTION : String {static} - - DEFAULT_DB : String {static} - - DEFAULT_TICKETS_COLLECTION : String {static} - - countersCollection : MongoCollection - - database : MongoDatabase - - mongoClient : MongoClient - - ticketsCollection : MongoCollection - + MongoTicketRepository() - + MongoTicketRepository(dbName : String, ticketsCollectionName : String, countersCollectionName : String) - + connect() - + connect(dbName : String, ticketsCollectionName : String, countersCollectionName : String) - + deleteAll() - - docToTicket(doc : Document) : LotteryTicket - + findAll() : Map - + findById(id : LotteryTicketId) : Optional - + getCountersCollection() : MongoCollection - + getMongoClient() : MongoClient - + getMongoDatabase() : MongoDatabase - + getNextId() : int - + getTicketsCollection() : MongoCollection - - initCounters() - + save(ticket : LotteryTicket) : Optional - } -} -package com.iluwatar.hexagonal { - class App { - + App() - + main(args : String[]) {static} - } -} -package com.iluwatar.hexagonal.administration { - class ConsoleAdministration { - - LOGGER : Logger {static} - + ConsoleAdministration() - + main(args : String[]) {static} - - printMainMenu() {static} - - readString(scanner : Scanner) : String {static} - } -} -package com.iluwatar.hexagonal.eventlog { - interface LotteryEventLog { - + prizeError(PlayerDetails, int) {abstract} - + ticketDidNotWin(PlayerDetails) {abstract} - + ticketSubmitError(PlayerDetails) {abstract} - + ticketSubmitted(PlayerDetails) {abstract} - + ticketWon(PlayerDetails, int) {abstract} - } - class MongoEventLog { - - DEFAULT_DB : String {static} - - DEFAULT_EVENTS_COLLECTION : String {static} - - database : MongoDatabase - - eventsCollection : MongoCollection - - mongoClient : MongoClient - - stdOutEventLog : StdOutEventLog - + MongoEventLog() - + MongoEventLog(dbName : String, eventsCollectionName : String) - + connect() - + connect(dbName : String, eventsCollectionName : String) - + getEventsCollection() : MongoCollection - + getMongoClient() : MongoClient - + getMongoDatabase() : MongoDatabase - + prizeError(details : PlayerDetails, prizeAmount : int) - + ticketDidNotWin(details : PlayerDetails) - + ticketSubmitError(details : PlayerDetails) - + ticketSubmitted(details : PlayerDetails) - + ticketWon(details : PlayerDetails, prizeAmount : int) - } - class StdOutEventLog { - - LOGGER : Logger {static} - + StdOutEventLog() - + prizeError(details : PlayerDetails, prizeAmount : int) - + ticketDidNotWin(details : PlayerDetails) - + ticketSubmitError(details : PlayerDetails) - + ticketSubmitted(details : PlayerDetails) - + ticketWon(details : PlayerDetails, prizeAmount : int) - } -} -LotteryTicket --> "-playerDetails" PlayerDetails -MongoEventLog --> "-stdOutEventLog" StdOutEventLog -LotteryService --> "-wireTransfers" WireTransfers -LotteryAdministration --> "-notifications" LotteryEventLog -LotteryAdministration --> "-wireTransfers" WireTransfers -LotteryService --> "-notifications" LotteryEventLog -LotteryTicket --> "-id" LotteryTicketId -LotteryAdministration --> "-repository" LotteryTicketRepository -LotteryTicket --> "-lotteryNumbers" LotteryNumbers -SampleData --> "-PLAYERS" PlayerDetails -RandomNumberGenerator ..+ LotteryNumbers -LotteryService --> "-repository" LotteryTicketRepository -CheckResult ..+ LotteryTicketCheckResult -LotteryTicketCheckResult --> "-checkResult" CheckResult -InMemoryBank ..|> WireTransfers -MongoBank ..|> WireTransfers -InMemoryTicketRepository ..|> LotteryTicketRepository -MongoTicketRepository ..|> LotteryTicketRepository -MongoEventLog ..|> LotteryEventLog -StdOutEventLog ..|> LotteryEventLog -@enduml \ No newline at end of file diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml index b18127f4b..6907ca10c 100644 --- a/hexagonal/pom.xml +++ b/hexagonal/pom.xml @@ -30,13 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT hexagonal - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java index 1e35847b2..d034ee865 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.hexagonal; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit test for simple App. diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java index 9c265a2ab..f32a7068f 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.hexagonal.banking; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java index 61529f3e4..d3589b0c7 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -24,16 +24,16 @@ package com.iluwatar.hexagonal.banking; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.mongodb.MongoClient; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for Mongo banking adapter */ -@Ignore +@Disabled public class MongoBankTest { private static final String TEST_DB = "lotteryDBTest"; @@ -41,7 +41,7 @@ public class MongoBankTest { private MongoBank mongoBank; - @Before + @BeforeEach public void init() { MongoConnectionPropertiesLoader.load(); MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java index ce5038369..f14caa94f 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -22,17 +22,16 @@ */ package com.iluwatar.hexagonal.database; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.Optional; -import org.junit.Before; -import org.junit.Test; - import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.test.LotteryTestUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -43,7 +42,7 @@ public class InMemoryTicketRepositoryTest { private final LotteryTicketRepository repository = new InMemoryTicketRepository(); - @Before + @BeforeEach public void clear() { repository.deleteAll(); } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java index 8b248de8c..08dcc51c3 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -28,19 +28,19 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.mongodb.MongoClient; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for Mongo based ticket repository */ -@Ignore +@Disabled public class MongoTicketRepositoryTest { private static final String TEST_DB = "lotteryTestDB"; @@ -49,7 +49,7 @@ public class MongoTicketRepositoryTest { private MongoTicketRepository repository; - @Before + @BeforeEach public void init() { MongoConnectionPropertiesLoader.load(); MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java index 8bd61db9c..b823bc3c7 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -22,14 +22,15 @@ */ package com.iluwatar.hexagonal.domain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; -import org.junit.Test; +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; /** * @@ -49,11 +50,13 @@ public class LotteryNumbersTest { assertTrue(numbers.getNumbers().contains(4)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testNumbersCantBeModified() { LotteryNumbers numbers = LotteryNumbers.create( new HashSet<>(Arrays.asList(1, 2, 3, 4))); - numbers.getNumbers().add(5); + assertThrows(UnsupportedOperationException.class, () -> { + numbers.getNumbers().add(5); + }); } @Test diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java index 4af8da3ea..2290b7d49 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -22,24 +22,23 @@ */ package com.iluwatar.hexagonal.domain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import com.iluwatar.hexagonal.module.LotteryTestingModule; +import com.iluwatar.hexagonal.test.LotteryTestUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Optional; -import com.google.inject.Guice; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.iluwatar.hexagonal.module.LotteryTestingModule; -import org.junit.Before; -import org.junit.Test; - -import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -import com.iluwatar.hexagonal.test.LotteryTestUtils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -60,7 +59,7 @@ public class LotteryTest { this.injector = Guice.createInjector(new LotteryTestingModule()); } - @Before + @BeforeEach public void setup() { injector.injectMembers(this); // add funds to the test player's bank account diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java index 454d0dd01..4ded94bc4 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -22,12 +22,11 @@ */ package com.iluwatar.hexagonal.domain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import org.junit.Test; - import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java index d4f0848ba..6bcaea4f0 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.hexagonal.domain; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for lottery ticket id diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java index a83f9033c..2c0332458 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.hexagonal.domain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Test Lottery Tickets for equality diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java index 2271ebf7c..4d49fcae5 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.hexagonal.domain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java index 07c40691b..06942a032 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -25,16 +25,16 @@ package com.iluwatar.hexagonal.eventlog; import com.iluwatar.hexagonal.domain.PlayerDetails; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.mongodb.MongoClient; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for Mongo event log */ -@Ignore +@Disabled public class MongoEventLogTest { private static final String TEST_DB = "lotteryDBTest"; @@ -42,7 +42,7 @@ public class MongoEventLogTest { private MongoEventLog mongoEventLog; - @Before + @BeforeEach public void init() { MongoConnectionPropertiesLoader.load(); MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md index 4981299ad..7d53472a0 100644 --- a/intercepting-filter/README.md +++ b/intercepting-filter/README.md @@ -3,7 +3,6 @@ layout: pattern title: Intercepting Filter folder: intercepting-filter permalink: /patterns/intercepting-filter/ -pumlid: RSfB3i8m303Hgy014k-vZN5DQkIuaJ_q-fGzkz7JtCL8Q-DolUsPAnu0ZcSVadizAzZfi6JBJiS4qJenqU6D7smRXmnh2pFPBM1YN05o_KwyKcoqb-ZFEEcVz_BPLqtz0W00 categories: Behavioral tags: - Java diff --git a/intercepting-filter/etc/intercepting-filter.urm.puml b/intercepting-filter/etc/intercepting-filter.urm.puml deleted file mode 100644 index 74444c2d0..000000000 --- a/intercepting-filter/etc/intercepting-filter.urm.puml +++ /dev/null @@ -1,89 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.intercepting.filter { - abstract class AbstractFilter { - - next : Filter - + AbstractFilter() - + AbstractFilter(next : Filter) - + execute(order : Order) : String - + getLast() : Filter - + getNext() : Filter - + setNext(filter : Filter) - } - class AddressFilter { - + AddressFilter() - + execute(order : Order) : String - } - class App { - + App() - + main(args : String[]) {static} - } - class ContactFilter { - + ContactFilter() - + execute(order : Order) : String - } - class DepositFilter { - + DepositFilter() - + execute(order : Order) : String - } - interface Filter { - + execute(Order) : String {abstract} - + getLast() : Filter {abstract} - + getNext() : Filter {abstract} - + setNext(Filter) {abstract} - } - class FilterChain { - - chain : Filter - + FilterChain() - + addFilter(filter : Filter) - + execute(order : Order) : String - } - class FilterManager { - - filterChain : FilterChain - + FilterManager() - + addFilter(filter : Filter) - + filterRequest(order : Order) : String - } - class NameFilter { - + NameFilter() - + execute(order : Order) : String - } - class Order { - - address : String - - contactNumber : String - - depositNumber : String - - name : String - - order : String - + Order() - + Order(name : String, contactNumber : String, address : String, depositNumber : String, order : String) - + getAddress() : String - + getContactNumber() : String - + getDepositNumber() : String - + getName() : String - + getOrder() : String - + setAddress(address : String) - + setContactNumber(contactNumber : String) - + setDepositNumber(depositNumber : String) - + setName(name : String) - + setOrder(order : String) - } - class OrderFilter { - + OrderFilter() - + execute(order : Order) : String - } - ~class DListener { - ~ DListener() - + actionPerformed(e : ActionEvent) - } -} -AbstractFilter --> "-next" Filter -DListener --+ Target -FilterChain --> "-chain" Filter -FilterManager --> "-filterChain" FilterChain -AbstractFilter ..|> Filter -AddressFilter --|> AbstractFilter -ContactFilter --|> AbstractFilter -DepositFilter --|> AbstractFilter -NameFilter --|> AbstractFilter -OrderFilter --|> AbstractFilter -@enduml diff --git a/intercepting-filter/pom.xml b/intercepting-filter/pom.xml index 91f61489c..dc4d6a923 100644 --- a/intercepting-filter/pom.xml +++ b/intercepting-filter/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT intercepting-filter - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java index eb347dce7..fb6cfb7e4 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java index 9b77ea19c..74259c152 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java index 877340355..43170af42 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -22,25 +22,22 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; -import static junit.framework.TestCase.assertSame; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/13/15 - 2:17 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class FilterTest { private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); @@ -50,8 +47,7 @@ public class FilterTest { private static final Order WRONG_CONTACT = new Order("name", "", "addr", "dep", "order"); private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); - @Parameters - public static List getTestData() { + static List getTestData() { final List testData = new ArrayList<>(); testData.add(new Object[]{new NameFilter(), PERFECT_ORDER, ""}); testData.add(new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}); @@ -91,30 +87,19 @@ public class FilterTest { return testData; } - private final Filter filter; - private final Order order; - private final String result; - - /** - * Constructor - */ - public FilterTest(Filter filter, Order order, String result) { - this.filter = filter; - this.order = order; - this.result = result; - } - - @Test - public void testExecute() throws Exception { - final String result = this.filter.execute(this.order); + @ParameterizedTest + @MethodSource("getTestData") + public void testExecute(Filter filter, Order order, String expectedResult) throws Exception { + final String result = filter.execute(order); assertNotNull(result); - assertEquals(this.result, result.trim()); + assertEquals(expectedResult, result.trim()); } - @Test - public void testNext() throws Exception { - assertNull(this.filter.getNext()); - assertSame(this.filter, this.filter.getLast()); + @ParameterizedTest + @MethodSource("getTestData") + public void testNext(Filter filter) throws Exception { + assertNull(filter.getNext()); + assertSame(filter, filter.getLast()); } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java index f52f6deec..3b03e4599 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/13/15 - 2:57 PM diff --git a/interpreter/README.md b/interpreter/README.md index 8600f0300..be6517962 100644 --- a/interpreter/README.md +++ b/interpreter/README.md @@ -3,7 +3,6 @@ layout: pattern title: Interpreter folder: interpreter permalink: /patterns/interpreter/ -pumlid: JSf13eCm30NHgz034E-vZGaM62Kcih_BzQ6xxjv8yr6hBJT9RzC1Z5Y8dE-oAuvSCyJhPH13gLSdRNapsEdaBy-RXEus3mR4BQXpl21zVnykFmlgVvVqNaRszW00 categories: Behavioral tags: - Java diff --git a/interpreter/etc/interpreter.urm.puml b/interpreter/etc/interpreter.urm.puml deleted file mode 100644 index e1286a2a9..000000000 --- a/interpreter/etc/interpreter.urm.puml +++ /dev/null @@ -1,52 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.interpreter { - class App { - - LOGGER : Logger {static} - + App() - + getOperatorInstance(s : String, left : Expression, right : Expression) : Expression {static} - + isOperator(s : String) : boolean {static} - + main(args : String[]) {static} - } - abstract class Expression { - + Expression() - + interpret() : int {abstract} - + toString() : String {abstract} - } - class MinusExpression { - - leftExpression : Expression - - rightExpression : Expression - + MinusExpression(leftExpression : Expression, rightExpression : Expression) - + interpret() : int - + toString() : String - } - class MultiplyExpression { - - leftExpression : Expression - - rightExpression : Expression - + MultiplyExpression(leftExpression : Expression, rightExpression : Expression) - + interpret() : int - + toString() : String - } - class NumberExpression { - - number : int - + NumberExpression(number : int) - + NumberExpression(s : String) - + interpret() : int - + toString() : String - } - class PlusExpression { - - leftExpression : Expression - - rightExpression : Expression - + PlusExpression(leftExpression : Expression, rightExpression : Expression) - + interpret() : int - + toString() : String - } -} -MultiplyExpression --> "-leftExpression" Expression -MinusExpression --> "-leftExpression" Expression -PlusExpression --> "-leftExpression" Expression -MinusExpression --|> Expression -MultiplyExpression --|> Expression -NumberExpression --|> Expression -PlusExpression --|> Expression -@enduml diff --git a/interpreter/pom.xml b/interpreter/pom.xml index 2fda838ea..99e399159 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT interpreter - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java index b2d6db157..547c0fa13 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.interpreter; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index 2241b882b..a3d9f21f2 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -22,15 +22,19 @@ */ package com.iluwatar.interpreter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; import java.util.function.IntBinaryOperator; +import java.util.stream.Stream; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/14/15 - 11:48 AM @@ -45,37 +49,22 @@ public abstract class ExpressionTest { * Generate inputs ranging from -10 to 10 for both input params and calculate the expected result * * @param resultCalc The function used to calculate the expected result - * @return A data set with test entries + * @return A stream with test entries */ - static List prepareParameters(final IntBinaryOperator resultCalc) { - final List testData = new ArrayList<>(); + static Stream prepareParameters(final IntBinaryOperator resultCalc) { + final List testData = new ArrayList<>(); for (int i = -10; i < 10; i++) { for (int j = -10; j < 10; j++) { - testData.add(new Object[]{ - new NumberExpression(i), - new NumberExpression(j), - resultCalc.applyAsInt(i, j) - }); + testData.add(Arguments.of( + new NumberExpression(i), + new NumberExpression(j), + resultCalc.applyAsInt(i, j) + )); } } - return testData; + return testData.stream(); } - /** - * The input used as first parameter during the test - */ - private final NumberExpression first; - - /** - * The input used as second parameter during the test - */ - private final NumberExpression second; - - /** - * The expected result of the calculation, taking the first and second parameter in account - */ - private final int result; - /** * The expected {@link E#toString()} response */ @@ -89,47 +78,34 @@ public abstract class ExpressionTest { /** * Create a new test instance with the given parameters and expected results * - * @param first The input used as first parameter during the test - * @param second The input used as second parameter during the test - * @param result The expected result of the tested expression * @param expectedToString The expected {@link E#toString()} response * @param factory Factory, used to create a new test object instance */ - ExpressionTest(final NumberExpression first, final NumberExpression second, final int result, - final String expectedToString, final BiFunction factory) { - - this.first = first; - this.second = second; - this.result = result; + ExpressionTest(final String expectedToString, + final BiFunction factory + ) { this.expectedToString = expectedToString; this.factory = factory; } - /** - * Get the first parameter - * - * @return The first parameter - */ - final NumberExpression getFirst() { - return this.first; - } - /** * Verify if the expression calculates the correct result when calling {@link E#interpret()} */ - @Test - public void testInterpret() { - final E expression = this.factory.apply(this.first, this.second); + @ParameterizedTest + @MethodSource("expressionProvider") + public void testInterpret(NumberExpression first, NumberExpression second, int result) { + final E expression = factory.apply(first, second); assertNotNull(expression); - assertEquals(this.result, expression.interpret()); + assertEquals(result, expression.interpret()); } /** * Verify if the expression has the expected {@link E#toString()} value */ - @Test - public void testToString() { - final E expression = this.factory.apply(this.first, this.second); + @ParameterizedTest + @MethodSource("expressionProvider") + public void testToString(NumberExpression first, NumberExpression second) { + final E expression = factory.apply(first, second); assertNotNull(expression); assertEquals(expectedToString, expression.toString()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java index 65e7e4515..eab0ea011 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -22,18 +22,15 @@ */ package com.iluwatar.interpreter; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; -import java.util.List; +import java.util.stream.Stream; /** * Date: 12/14/15 - 12:08 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class MinusExpressionTest extends ExpressionTest { /** @@ -41,20 +38,15 @@ public class MinusExpressionTest extends ExpressionTest { * * @return The list of parameters used during this test */ - @Parameters - public static List data() { + public static Stream expressionProvider() { return prepareParameters((f, s) -> f - s); } /** * Create a new test instance using the given test parameters and expected result - * - * @param first The first expression parameter - * @param second The second expression parameter - * @param result The expected result */ - public MinusExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { - super(first, second, result, "-", MinusExpression::new); + public MinusExpressionTest() { + super("-", MinusExpression::new); } } \ No newline at end of file diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java index 12ea35863..6e5384f8b 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -22,18 +22,15 @@ */ package com.iluwatar.interpreter; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; -import java.util.List; +import java.util.stream.Stream; /** * Date: 12/14/15 - 12:08 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class MultiplyExpressionTest extends ExpressionTest { /** @@ -41,20 +38,16 @@ public class MultiplyExpressionTest extends ExpressionTest { * * @return The list of parameters used during this test */ - @Parameters - public static List data() { + public static Stream expressionProvider() { return prepareParameters((f, s) -> f * s); } /** * Create a new test instance using the given test parameters and expected result * - * @param first The first expression parameter - * @param second The second expression parameter - * @param result The expected result */ - public MultiplyExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { - super(first, second, result, "*", MultiplyExpression::new); + public MultiplyExpressionTest() { + super("*", MultiplyExpression::new); } } \ No newline at end of file diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java index 9f18355ef..698da52bc 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -22,21 +22,19 @@ */ package com.iluwatar.interpreter; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -import java.util.List; +import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/14/15 - 12:08 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class NumberExpressionTest extends ExpressionTest { /** @@ -44,30 +42,26 @@ public class NumberExpressionTest extends ExpressionTest { * * @return The list of parameters used during this test */ - @Parameters - public static List data() { + public static Stream expressionProvider() { return prepareParameters((f, s) -> f); } /** * Create a new test instance using the given test parameters and expected result - * - * @param first The first expression parameter - * @param second The second expression parameter - * @param result The expected result */ - public NumberExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { - super(first, second, result, "number", (f, s) -> f); + public NumberExpressionTest() { + super("number", (f, s) -> f); } /** * Verify if the {@link NumberExpression#NumberExpression(String)} constructor works as expected */ - @Test - public void testFromString() throws Exception { - final int expectedValue = getFirst().interpret(); - final String testStingValue = String.valueOf(expectedValue); - final NumberExpression numberExpression = new NumberExpression(testStingValue); + @ParameterizedTest + @MethodSource("expressionProvider") + public void testFromString(NumberExpression first) throws Exception { + final int expectedValue = first.interpret(); + final String testStringValue = String.valueOf(expectedValue); + final NumberExpression numberExpression = new NumberExpression(testStringValue); assertEquals(expectedValue, numberExpression.interpret()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java index d11ba8a8d..ae2423c7a 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -22,18 +22,15 @@ */ package com.iluwatar.interpreter; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; -import java.util.List; +import java.util.stream.Stream; /** * Date: 12/14/15 - 12:08 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class PlusExpressionTest extends ExpressionTest { /** @@ -41,20 +38,15 @@ public class PlusExpressionTest extends ExpressionTest { * * @return The list of parameters used during this test */ - @Parameters - public static List data() { + public static Stream expressionProvider() { return prepareParameters((f, s) -> f + s); } /** * Create a new test instance using the given test parameters and expected result - * - * @param first The first expression parameter - * @param second The second expression parameter - * @param result The expected result */ - public PlusExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { - super(first, second, result, "+", PlusExpression::new); + public PlusExpressionTest() { + super("+", PlusExpression::new); } } \ No newline at end of file diff --git a/iterator/README.md b/iterator/README.md index 61bd8f6f5..723e7f03c 100644 --- a/iterator/README.md +++ b/iterator/README.md @@ -3,7 +3,6 @@ layout: pattern title: Iterator folder: iterator permalink: /patterns/iterator/ -pumlid: FSV13OGm30NHLg00uljsOu85HeaJsTzB-yjfBwCtgrfjUKXwMovWneV8-IcduiezGxmEWnXA7PsqvSDWfvk_l1qIUjes6H2teCxnWlGDOpW9wdzAUYypU_i1 categories: Behavioral tags: - Java diff --git a/iterator/etc/iterator.urm.puml b/iterator/etc/iterator.urm.puml deleted file mode 100644 index 881b9a6d4..000000000 --- a/iterator/etc/iterator.urm.puml +++ /dev/null @@ -1,49 +0,0 @@ -@startuml -package com.iluwatar.iterator { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Item { - - name : String - - type : ItemType - + Item(type : ItemType, name : String) - + getType() : ItemType - + setType(type : ItemType) - + toString() : String - } - interface ItemIterator { - + hasNext() : boolean {abstract} - + next() : Item {abstract} - } - enum ItemType { - + ANY {static} - + POTION {static} - + RING {static} - + WEAPON {static} - + valueOf(name : String) : ItemType {static} - + values() : ItemType[] {static} - } - class TreasureChest { - - items : List - + TreasureChest() - + getItems() : List - ~ iterator(itemType : ItemType) : ItemIterator - } - class TreasureChestItemIterator { - - chest : TreasureChest - - idx : int - - type : ItemType - + TreasureChestItemIterator(chest : TreasureChest, type : ItemType) - - findNextIdx() : int - + hasNext() : boolean - + next() : Item - } -} -Item --> "-type" ItemType -TreasureChest --> "-items" Item -TreasureChestItemIterator --> "-type" ItemType -TreasureChestItemIterator --> "-chest" TreasureChest -TreasureChestItemIterator ..|> ItemIterator -@enduml \ No newline at end of file diff --git a/iterator/pom.xml b/iterator/pom.xml index 5a751db9c..2afca644c 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT iterator - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java index 75cad3ced..f448a378e 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java index 196e08216..665666aa7 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java @@ -22,23 +22,21 @@ */ package com.iluwatar.iterator; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Date: 12/14/15 - 2:58 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class TreasureChestTest { /** @@ -46,8 +44,7 @@ public class TreasureChestTest { * * @return The set of all expected items in the chest */ - @Parameterized.Parameters - public static List data() { + public static List dataProvider() { final List parameters = new ArrayList<>(); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); @@ -62,25 +59,12 @@ public class TreasureChestTest { return parameters; } - /** - * One of the expected items in the chest - */ - private final Item expectedItem; - - /** - * Create a new test instance, test if the given expected item can be retrieved from the chest - * - * @param expectedItem One of the items that should be in the chest - */ - public TreasureChestTest(final Item expectedItem) { - this.expectedItem = expectedItem; - } - /** * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} */ - @Test - public void testIterator() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testIterator(Item expectedItem) { final TreasureChest chest = new TreasureChest(); final ItemIterator iterator = chest.iterator(expectedItem.getType()); assertNotNull(iterator); @@ -88,16 +72,16 @@ public class TreasureChestTest { while (iterator.hasNext()) { final Item item = iterator.next(); assertNotNull(item); - assertEquals(this.expectedItem.getType(), item.getType()); + assertEquals(expectedItem.getType(), item.getType()); final String name = item.toString(); assertNotNull(name); - if (this.expectedItem.toString().equals(name)) { + if (expectedItem.toString().equals(name)) { return; } } - fail("Expected to find item [" + this.expectedItem + "] using iterator, but we didn't."); + fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't."); } @@ -105,8 +89,9 @@ public class TreasureChestTest { * Test if the expected item can be retrieved from the chest using the {@link * TreasureChest#getItems()} method */ - @Test - public void testGetItems() throws Exception { + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetItems(Item expectedItem) throws Exception { final TreasureChest chest = new TreasureChest(); final List items = chest.getItems(); assertNotNull(items); @@ -116,14 +101,14 @@ public class TreasureChestTest { assertNotNull(item.getType()); assertNotNull(item.toString()); - final boolean sameType = this.expectedItem.getType() == item.getType(); - final boolean sameName = this.expectedItem.toString().equals(item.toString()); + final boolean sameType = expectedItem.getType() == item.getType(); + final boolean sameName = expectedItem.toString().equals(item.toString()); if (sameType && sameName) { return; } } - fail("Expected to find item [" + this.expectedItem + "] in the item list, but we didn't."); + fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't."); } diff --git a/layers/README.md b/layers/README.md index 62b562938..49b74c175 100644 --- a/layers/README.md +++ b/layers/README.md @@ -3,7 +3,6 @@ layout: pattern title: Layers folder: layers permalink: /patterns/layers/ -pumlid: BSR13OCm30NGLSe0n7UsCS62L8w9x6yGszD3t-bDpQhc9kdwEO0H2v7pNVQ68zSCyNeQn53gsQbftWns-lB5yoRHTfi70-8Mr3b-8UL7F4XG_otflOpi-W80 pumlformat: svg categories: Architectural tags: diff --git a/layers/etc/layers.urm.puml b/layers/etc/layers.urm.puml deleted file mode 100644 index e597c7546..000000000 --- a/layers/etc/layers.urm.puml +++ /dev/null @@ -1,126 +0,0 @@ -@startuml -package com.iluwatar.layers { - class App { - - cakeBakingService : CakeBakingService {static} - + App() - - initializeData(cakeBakingService : CakeBakingService) {static} - + main(args : String[]) {static} - } - class Cake { - - id : Long - - layers : Set - - topping : CakeTopping - + Cake() - + addLayer(layer : CakeLayer) - + getId() : Long - + getLayers() : Set - + getTopping() : CakeTopping - + setId(id : Long) - + setLayers(layers : Set) - + setTopping(topping : CakeTopping) - + toString() : String - } - interface CakeBakingService { - + bakeNewCake(CakeInfo) {abstract} - + getAllCakes() : List {abstract} - + getAvailableLayers() : List {abstract} - + getAvailableToppings() : List {abstract} - + saveNewLayer(CakeLayerInfo) {abstract} - + saveNewTopping(CakeToppingInfo) {abstract} - } - class CakeBakingServiceImpl { - - context : AbstractApplicationContext - + CakeBakingServiceImpl() - + bakeNewCake(cakeInfo : CakeInfo) - + getAllCakes() : List - - getAvailableLayerEntities() : List - + getAvailableLayers() : List - - getAvailableToppingEntities() : List - + getAvailableToppings() : List - + saveNewLayer(layerInfo : CakeLayerInfo) - + saveNewTopping(toppingInfo : CakeToppingInfo) - } - interface CakeDao { - } - class CakeInfo { - + cakeLayerInfos : List - + cakeToppingInfo : CakeToppingInfo - + id : Optional - + CakeInfo(cakeToppingInfo : CakeToppingInfo, cakeLayerInfos : List) - + CakeInfo(id : Long, cakeToppingInfo : CakeToppingInfo, cakeLayerInfos : List) - + calculateTotalCalories() : int - + toString() : String - } - class CakeLayer { - - cake : Cake - - calories : int - - id : Long - - name : String - + CakeLayer() - + CakeLayer(name : String, calories : int) - + getCake() : Cake - + getCalories() : int - + getId() : Long - + getName() : String - + setCake(cake : Cake) - + setCalories(calories : int) - + setId(id : Long) - + setName(name : String) - + toString() : String - } - interface CakeLayerDao { - } - class CakeLayerInfo { - + calories : int - + id : Optional - + name : String - + CakeLayerInfo(id : Long, name : String, calories : int) - + CakeLayerInfo(name : String, calories : int) - + toString() : String - } - class CakeTopping { - - cake : Cake - - calories : int - - id : Long - - name : String - + CakeTopping() - + CakeTopping(name : String, calories : int) - + getCake() : Cake - + getCalories() : int - + getId() : Long - + getName() : String - + setCake(cake : Cake) - + setCalories(calories : int) - + setId(id : Long) - + setName(name : String) - + toString() : String - } - interface CakeToppingDao { - } - class CakeToppingInfo { - + calories : int - + id : Optional - + name : String - + CakeToppingInfo(id : Long, name : String, calories : int) - + CakeToppingInfo(name : String, calories : int) - + toString() : String - } - class CakeViewImpl { - - LOGGER : Logger {static} - - cakeBakingService : CakeBakingService - + CakeViewImpl(cakeBakingService : CakeBakingService) - + render() - } - interface View { - + render() {abstract} - } -} -CakeViewImpl --> "-cakeBakingService" CakeBakingService -CakeInfo --> "-cakeToppingInfo" CakeToppingInfo -CakeInfo --> "-cakeLayerInfos" CakeLayerInfo -App --> "-cakeBakingService" CakeBakingService -CakeLayer --> "-cake" Cake -Cake --> "-topping" CakeTopping -CakeBakingServiceImpl ..|> CakeBakingService -CakeViewImpl ..|> View -@enduml \ No newline at end of file diff --git a/layers/pom.xml b/layers/pom.xml index 084795acd..772c53a30 100644 --- a/layers/pom.xml +++ b/layers/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT com.iluwatar.layers layers @@ -52,8 +52,13 @@ h2 - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/layers/src/test/java/com/iluwatar/layers/AppTest.java b/layers/src/test/java/com/iluwatar/layers/AppTest.java index 841d0ecb5..aa14e039d 100644 --- a/layers/src/test/java/com/iluwatar/layers/AppTest.java +++ b/layers/src/test/java/com/iluwatar/layers/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.layers; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java b/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java index abefc9f2c..e13e148a3 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java +++ b/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java @@ -22,10 +22,10 @@ */ package com.iluwatar.layers; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Date: 12/15/15 - 7:57 PM diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java b/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java index 1c6eb1517..f740fb5f4 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java +++ b/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java @@ -22,16 +22,17 @@ */ package com.iluwatar.layers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/15/15 - 9:55 PM @@ -123,7 +124,7 @@ public class CakeBakingServiceImplTest { } - @Test(expected = CakeBakingException.class) + @Test public void testBakeCakeMissingTopping() throws CakeBakingException { final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); @@ -133,10 +134,12 @@ public class CakeBakingServiceImplTest { service.saveNewLayer(layer2); final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000); - service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); + }); } - @Test(expected = CakeBakingException.class) + @Test public void testBakeCakeMissingLayer() throws CakeBakingException { final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); @@ -151,11 +154,12 @@ public class CakeBakingServiceImplTest { service.saveNewLayer(layer1); final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000); - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); - + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); + }); } - @Test(expected = CakeBakingException.class) + @Test public void testBakeCakesUsedLayer() throws CakeBakingException { final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); @@ -174,8 +178,9 @@ public class CakeBakingServiceImplTest { service.saveNewLayer(layer2); service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); - service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); - + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); + }); } } diff --git a/layers/src/test/java/com/iluwatar/layers/CakeTest.java b/layers/src/test/java/com/iluwatar/layers/CakeTest.java index f43f5508f..f71a0b35d 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeTest.java +++ b/layers/src/test/java/com/iluwatar/layers/CakeTest.java @@ -22,15 +22,15 @@ */ package com.iluwatar.layers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/15/15 - 8:02 PM diff --git a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java index 8a62e074b..4aed18869 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java +++ b/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java @@ -25,17 +25,18 @@ package com.iluwatar.layers; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Date: 12/15/15 - 10:04 PM @@ -46,12 +47,12 @@ public class CakeViewImplTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(CakeViewImpl.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/lazy-loading/README.md b/lazy-loading/README.md index 4b7a580c3..d40061293 100644 --- a/lazy-loading/README.md +++ b/lazy-loading/README.md @@ -3,7 +3,6 @@ layout: pattern title: Lazy Loading folder: lazy-loading permalink: /patterns/lazy-loading/ -pumlid: LSXB3W8X303Gg-W1e7jlqu66gIc5zED4JwzRTo_lpjeaEwN9xOpO_W0mlEhWEFD89sjBWpHgMnDOyi90WoU-i7Ho7besHf2fmqJ_0GG_xo8BE-i0YlONDMtMdLE- categories: Other tags: - Java diff --git a/lazy-loading/etc/lazy-loading.urm.puml b/lazy-loading/etc/lazy-loading.urm.puml deleted file mode 100644 index aaf49f1df..000000000 --- a/lazy-loading/etc/lazy-loading.urm.puml +++ /dev/null @@ -1,40 +0,0 @@ -@startuml -package com.iluwatar.lazy.loading { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Heavy { - - LOGGER : Logger {static} - + Heavy() - } - class HolderNaive { - - LOGGER : Logger {static} - - heavy : Heavy - + HolderNaive() - + getHeavy() : Heavy - } - class HolderThreadSafe { - - LOGGER : Logger {static} - - heavy : Heavy - + HolderThreadSafe() - + getHeavy() : Heavy - } - class Java8Holder { - - LOGGER : Logger {static} - - heavy : Supplier - + Java8Holder() - - createAndCacheHeavy() : Heavy - + getHeavy() : Heavy - } - ~class HeavyFactory { - - heavyInstance : Heavy - ~ HeavyFactory() - + get() : Heavy - } -} -HolderThreadSafe --> "-heavy" Heavy -HolderNaive --> "-heavy" Heavy -HeavyFactory --> "-heavyInstance" Heavy -@enduml \ No newline at end of file diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index 0e54e6869..8d799d07c 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT lazy-loading - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java index 917ccb8d3..56b5a2c3d 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java @@ -22,11 +22,13 @@ */ package com.iluwatar.lazy.loading; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertSame; -import static junit.framework.TestCase.assertNull; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; /** * Date: 12/19/15 - 11:58 AM @@ -52,12 +54,14 @@ public abstract class AbstractHolderTest { /** * This test shows that the heavy field is not instantiated until the method getHeavy is called */ - @Test(timeout = 3000) + @Test public void testGetHeavy() throws Exception { - assertNull(getInternalHeavyValue()); - assertNotNull(getHeavy()); - assertNotNull(getInternalHeavyValue()); - assertSame(getHeavy(), getInternalHeavyValue()); + assertTimeout(ofMillis(3000), () -> { + assertNull(getInternalHeavyValue()); + assertNotNull(getHeavy()); + assertNotNull(getInternalHeavyValue()); + assertSame(getHeavy(), getInternalHeavyValue()); + }); } } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java index cefa9918a..bd43b0d35 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.lazy.loading; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/marker/README.md b/marker/README.md index 5bcdf9664..6f5fc1e91 100644 --- a/marker/README.md +++ b/marker/README.md @@ -3,7 +3,7 @@ layout: pattern title: Marker Interface folder: marker permalink: /patterns/marker/ -categories: Design +categories: Other tags: - Java - Difficulty-Beginner diff --git a/marker/etc/marker.urm.puml b/marker/etc/marker.urm.puml deleted file mode 100644 index 02af47ddf..000000000 --- a/marker/etc/marker.urm.puml +++ /dev/null @@ -1,2 +0,0 @@ -@startuml -@enduml \ No newline at end of file diff --git a/marker/pom.xml b/marker/pom.xml index ba68b825b..708072d8c 100644 --- a/marker/pom.xml +++ b/marker/pom.xml @@ -24,15 +24,26 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 marker - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.hamcrest + hamcrest-core + 1.3 test diff --git a/marker/src/test/java/AppTest.java b/marker/src/test/java/AppTest.java index 85fb61b16..856635007 100644 --- a/marker/src/test/java/AppTest.java +++ b/marker/src/test/java/AppTest.java @@ -20,7 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.Test; + +import org.junit.jupiter.api.Test; /** * Application test diff --git a/marker/src/test/java/GuardTest.java b/marker/src/test/java/GuardTest.java index eb3a4b757..cadd82f82 100644 --- a/marker/src/test/java/GuardTest.java +++ b/marker/src/test/java/GuardTest.java @@ -20,10 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.Test; + +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Guard test diff --git a/marker/src/test/java/ThiefTest.java b/marker/src/test/java/ThiefTest.java index f950809cc..56492334c 100644 --- a/marker/src/test/java/ThiefTest.java +++ b/marker/src/test/java/ThiefTest.java @@ -20,9 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.Test; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Thief test diff --git a/mediator/README.md b/mediator/README.md index 084e59256..3452082ef 100644 --- a/mediator/README.md +++ b/mediator/README.md @@ -3,7 +3,6 @@ layout: pattern title: Mediator folder: mediator permalink: /patterns/mediator/ -pumlid: FSV14SCm20J0Lk82BFxf1akCJKOW3JhizfDNVhkRUktP9AE_Bc2kDr7mKqx5bKSkYJeSuYXr66dFXy517xvvRxBqz7qo8E6BZDSFPDAKCO84zP-IOMMczIy0 categories: Behavioral tags: - Java diff --git a/mediator/etc/mediator.urm.puml b/mediator/etc/mediator.urm.puml deleted file mode 100644 index 04e75d2b8..000000000 --- a/mediator/etc/mediator.urm.puml +++ /dev/null @@ -1,69 +0,0 @@ -@startuml -package com.iluwatar.mediator { - enum Action { - + ENEMY {static} - + GOLD {static} - + HUNT {static} - + NONE {static} - + TALE {static} - - description : String - - title : String - + getDescription() : String - + toString() : String - + valueOf(name : String) : Action {static} - + values() : Action[] {static} - } - class App { - + App() - + main(args : String[]) {static} - } - class Hobbit { - + Hobbit() - + toString() : String - } - class Hunter { - + Hunter() - + toString() : String - } - interface Party { - + act(PartyMember, Action) {abstract} - + addMember(PartyMember) {abstract} - } - class PartyImpl { - - members : List - + PartyImpl() - + act(actor : PartyMember, action : Action) - + addMember(member : PartyMember) - } - interface PartyMember { - + act(Action) {abstract} - + joinedParty(Party) {abstract} - + partyAction(Action) {abstract} - } - abstract class PartyMemberBase { - - LOGGER : Logger {static} - # party : Party - + PartyMemberBase() - + act(action : Action) - + joinedParty(party : Party) - + partyAction(action : Action) - + toString() : String {abstract} - } - class Rogue { - + Rogue() - + toString() : String - } - class Wizard { - + Wizard() - + toString() : String - } -} -PartyImpl --> "-members" PartyMember -PartyMemberBase --> "-party" Party -Hobbit --|> PartyMemberBase -Hunter --|> PartyMemberBase -PartyImpl ..|> Party -PartyMemberBase ..|> PartyMember -Rogue --|> PartyMemberBase -Wizard --|> PartyMemberBase -@enduml \ No newline at end of file diff --git a/mediator/pom.xml b/mediator/pom.xml index a15134368..c9369b1a9 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT mediator - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java index d92b8969b..a375490cd 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.mediator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java index bb3c51474..820bf17ee 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.mediator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java index 4d578c333..61f926c31 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -25,11 +25,10 @@ package com.iluwatar.mediator; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; import java.util.Arrays; @@ -38,7 +37,7 @@ import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -47,11 +46,9 @@ import static org.mockito.Mockito.verify; * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class PartyMemberTest { - @Parameterized.Parameters - public static Collection[]> data() { + static Collection[]> dataProvider() { return Arrays.asList( new Supplier[]{Hobbit::new}, new Supplier[]{Hunter::new}, @@ -60,28 +57,14 @@ public class PartyMemberTest { ); } - /** - * The factory, used to create a new instance of the tested party member - */ - private final Supplier memberSupplier; - - /** - * Create a new test instance, using the given {@link PartyMember} factory - * - * @param memberSupplier The party member factory - */ - public PartyMemberTest(final Supplier memberSupplier) { - this.memberSupplier = memberSupplier; - } - private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(PartyMemberBase.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } @@ -89,9 +72,10 @@ public class PartyMemberTest { /** * Verify if a party action triggers the correct output to the std-Out */ - @Test - public void testPartyAction() { - final PartyMember member = this.memberSupplier.get(); + @ParameterizedTest + @MethodSource("dataProvider") + public void testPartyAction(Supplier memberSupplier) { + final PartyMember member = memberSupplier.get(); for (final Action action : Action.values()) { member.partyAction(action); @@ -104,9 +88,10 @@ public class PartyMemberTest { /** * Verify if a member action triggers the expected interactions with the party class */ - @Test - public void testAct() { - final PartyMember member = this.memberSupplier.get(); + @ParameterizedTest + @MethodSource("dataProvider") + public void testAct(Supplier memberSupplier) { + final PartyMember member = memberSupplier.get(); member.act(Action.GOLD); assertEquals(0, appender.getLogSize()); @@ -127,9 +112,10 @@ public class PartyMemberTest { /** * Verify if {@link PartyMember#toString()} generate the expected output */ - @Test - public void testToString() throws Exception { - final PartyMember member = this.memberSupplier.get(); + @ParameterizedTest + @MethodSource("dataProvider") + public void testToString(Supplier memberSupplier) throws Exception { + final PartyMember member = memberSupplier.get(); final Class memberClass = member.getClass(); assertEquals(memberClass.getSimpleName(), member.toString()); } diff --git a/memento/README.md b/memento/README.md index f43849329..463b5fec0 100644 --- a/memento/README.md +++ b/memento/README.md @@ -3,7 +3,6 @@ layout: pattern title: Memento folder: memento permalink: /patterns/memento/ -pumlid: DSgn4OCm30NGLM00h3xR2AC3SvRiaxx2-g59zugtDgiz3qdlomNC-10vF-Lik7BF4A_388PIXrBh-J3OwUOlRuT4EssR38XRa7Ay81Lz_o11_RkaQvcf_GS0 categories: Behavioral tags: - Java diff --git a/memento/etc/memento.urm.puml b/memento/etc/memento.urm.puml deleted file mode 100644 index 319227ad2..000000000 --- a/memento/etc/memento.urm.puml +++ /dev/null @@ -1,49 +0,0 @@ -@startuml -package com.iluwatar.memento { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Star { - - ageYears : int - - massTons : int - - type : StarType - + Star(startType : StarType, startAge : int, startMass : int) - ~ getMemento() : StarMemento - ~ setMemento(memento : StarMemento) - + timePasses() - + toString() : String - } - -class StarMementoInternal { - - ageYears : int - - massTons : int - - type : StarType - - StarMementoInternal() - + getAgeYears() : int - + getMassTons() : int - + getType() : StarType - + setAgeYears(ageYears : int) - + setMassTons(massTons : int) - + setType(type : StarType) - } - interface StarMemento { - } - enum StarType { - + DEAD {static} - + RED_GIANT {static} - + SUN {static} - + SUPERNOVA {static} - + UNDEFINED {static} - + WHITE_DWARF {static} - - title : String - + toString() : String - + valueOf(name : String) : StarType {static} - + values() : StarType[] {static} - } -} -StarMementoInternal --> "-type" StarType -Star --> "-type" StarType -StarMementoInternal ..+ Star -StarMementoInternal ..|> StarMemento -@enduml \ No newline at end of file diff --git a/memento/pom.xml b/memento/pom.xml index 8d95f32bb..2ad5321ba 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT memento - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/memento/src/test/java/com/iluwatar/memento/AppTest.java b/memento/src/test/java/com/iluwatar/memento/AppTest.java index b98757122..c6ea91e9b 100644 --- a/memento/src/test/java/com/iluwatar/memento/AppTest.java +++ b/memento/src/test/java/com/iluwatar/memento/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.memento; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/memento/src/test/java/com/iluwatar/memento/StarTest.java b/memento/src/test/java/com/iluwatar/memento/StarTest.java index 2a7efc70f..c3d16efe5 100644 --- a/memento/src/test/java/com/iluwatar/memento/StarTest.java +++ b/memento/src/test/java/com/iluwatar/memento/StarTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.memento; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/20/15 - 10:08 AM diff --git a/message-channel/etc/message-channel.urm.puml b/message-channel/etc/message-channel.urm.puml deleted file mode 100644 index 852f190b4..000000000 --- a/message-channel/etc/message-channel.urm.puml +++ /dev/null @@ -1,9 +0,0 @@ -@startuml -package com.iluwatar.message.channel { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } -} -@enduml \ No newline at end of file diff --git a/message-channel/pom.xml b/message-channel/pom.xml index f73214855..3e3028f2a 100644 --- a/message-channel/pom.xml +++ b/message-channel/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT message-channel @@ -43,8 +43,13 @@ camel-stream - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java index e41977a00..97094b864 100644 --- a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java +++ b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.message.channel; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/model-view-controller/README.md b/model-view-controller/README.md index 9907b98bd..bc96f7ab1 100644 --- a/model-view-controller/README.md +++ b/model-view-controller/README.md @@ -3,7 +3,6 @@ layout: pattern title: Model-View-Controller folder: model-view-controller permalink: /patterns/model-view-controller/ -pumlid: ROl13SCm201NQGUm-NSRQgE42h258Lw_wR-_qvtkoTOaEwNBuuoOwmNWkEl1SUOx5taR5cHHsr1WoOs13X-yi7HQV5YP645k2nJN3Q2ZavIBQPVVwqFajXJjVwdfMcUgV040 categories: Presentation Tier tags: - Java diff --git a/model-view-controller/etc/model-view-controller.urm.puml b/model-view-controller/etc/model-view-controller.urm.puml deleted file mode 100644 index 92ec1e949..000000000 --- a/model-view-controller/etc/model-view-controller.urm.puml +++ /dev/null @@ -1,70 +0,0 @@ -@startuml -package com.iluwatar.model.view.controller { - class App { - + App() - + main(args : String[]) {static} - } - enum Fatigue { - + ALERT {static} - + SLEEPING {static} - + TIRED {static} - - title : String - + toString() : String - + valueOf(name : String) : Fatigue {static} - + values() : Fatigue[] {static} - } - class GiantController { - - giant : GiantModel - - view : GiantView - + GiantController(giant : GiantModel, view : GiantView) - + getFatigue() : Fatigue - + getHealth() : Health - + getNourishment() : Nourishment - + setFatigue(fatigue : Fatigue) - + setHealth(health : Health) - + setNourishment(nourishment : Nourishment) - + updateView() - } - class GiantModel { - - fatigue : Fatigue - - health : Health - - nourishment : Nourishment - ~ GiantModel(health : Health, fatigue : Fatigue, nourishment : Nourishment) - + getFatigue() : Fatigue - + getHealth() : Health - + getNourishment() : Nourishment - + setFatigue(fatigue : Fatigue) - + setHealth(health : Health) - + setNourishment(nourishment : Nourishment) - + toString() : String - } - class GiantView { - - LOGGER : Logger {static} - + GiantView() - + displayGiant(giant : GiantModel) - } - enum Health { - + DEAD {static} - + HEALTHY {static} - + WOUNDED {static} - - title : String - + toString() : String - + valueOf(name : String) : Health {static} - + values() : Health[] {static} - } - enum Nourishment { - + HUNGRY {static} - + SATURATED {static} - + STARVING {static} - - title : String - + toString() : String - + valueOf(name : String) : Nourishment {static} - + values() : Nourishment[] {static} - } -} -GiantModel --> "-nourishment" Nourishment -GiantController --> "-giant" GiantModel -GiantModel --> "-fatigue" Fatigue -GiantModel --> "-health" Health -GiantController --> "-view" GiantView -@enduml \ No newline at end of file diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 4aeb69715..f873107fa 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT model-view-controller - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java index 66062faf5..1c4dc3dad 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.model.view.controller; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java index ab9b3e0a4..73f348770 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.model.view.controller; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java index ecf713a61..339c170f4 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.model.view.controller; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/20/15 - 2:10 PM diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java index ec0aabd15..855c97606 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.model.view.controller; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import ch.qos.logback.classic.Logger; @@ -30,9 +30,10 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** @@ -44,12 +45,12 @@ public class GiantViewTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(GiantView.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/model-view-presenter/README.md b/model-view-presenter/README.md index 04a1fa559..a3b921ce4 100644 --- a/model-view-presenter/README.md +++ b/model-view-presenter/README.md @@ -3,7 +3,6 @@ layout: pattern title: Model-View-Presenter folder: model-view-presenter permalink: /patterns/model-view-presenter/ -pumlid: ROlR3SGW3C1MkGu0-RzjKeXQJWcWFChwPO3xispvQBrmL0hbp-q-xGkWkFBL_8upZBICxjGzbo7GE1OwAlpmmLJ9sjNJH7VIRY1e6q169KvFevMcakrtI_BoD-HGoJE4Nm00 categories: Presentation Tier tags: - Java diff --git a/model-view-presenter/etc/model-view-presenter.urm.puml b/model-view-presenter/etc/model-view-presenter.urm.puml deleted file mode 100644 index 188b3fb4d..000000000 --- a/model-view-presenter/etc/model-view-presenter.urm.puml +++ /dev/null @@ -1,87 +0,0 @@ -@startuml -package com.iluwatar.model.view.presenter { - class App { - + App() - + main(args : String[]) {static} - } - class FileLoader { - - fileName : String - - loaded : boolean - + FileLoader() - + fileExists() : boolean - + getFileName() : String - + isLoaded() : boolean - + loadData() : String - + setFileName(fileName : String) - } - class FileSelectorJFrame { - - area : JTextArea - - cancel : JButton - - contents : JLabel - - fileName : String - - info : JLabel - - input : JTextField - - ok : JButton - - panel : JPanel - - presenter : FileSelectorPresenter - - serialVersionUID : long {static} - + FileSelectorJFrame() - + actionPerformed(e : ActionEvent) - + close() - + displayData(data : String) - + getFileName() : String - + getPresenter() : FileSelectorPresenter - + isOpened() : boolean - + open() - + setFileName(name : String) - + setPresenter(presenter : FileSelectorPresenter) - + showMessage(message : String) - } - class FileSelectorPresenter { - - loader : FileLoader - - view : FileSelectorView - + FileSelectorPresenter(view : FileSelectorView) - + cancelled() - + confirmed() - + fileNameChanged() - + setLoader(loader : FileLoader) - + start() - } - class FileSelectorStub { - - dataDisplayed : boolean - - name : String - - numOfMessageSent : int - - opened : boolean - - presenter : FileSelectorPresenter - + FileSelectorStub() - + close() - + dataDisplayed() : boolean - + displayData(data : String) - + getFileName() : String - + getMessagesSent() : int - + getPresenter() : FileSelectorPresenter - + isOpened() : boolean - + open() - + setFileName(name : String) - + setPresenter(presenter : FileSelectorPresenter) - + showMessage(message : String) - } - interface FileSelectorView { - + close() {abstract} - + displayData(String) {abstract} - + getFileName() : String {abstract} - + getPresenter() : FileSelectorPresenter {abstract} - + isOpened() : boolean {abstract} - + open() {abstract} - + setFileName(String) {abstract} - + setPresenter(FileSelectorPresenter) {abstract} - + showMessage(String) {abstract} - } -} -FileSelectorStub --> "-presenter" FileSelectorPresenter -FileSelectorJFrame --> "-presenter" FileSelectorPresenter -FileSelectorPresenter --> "-loader" FileLoader -FileSelectorPresenter --> "-view" FileSelectorView -FileSelectorJFrame ..|> FileSelectorView -FileSelectorStub ..|> FileSelectorView -@enduml \ No newline at end of file diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index ec6f570ee..60a379996 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -29,15 +29,20 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT model-view-presenter model-view-presenter http://maven.apache.org - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java index f5606e638..5952cf5f1 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java @@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory; *

* It is responsible for reading and loading the contents of a given file. */ -public class FileLoader implements Serializable{ +public class FileLoader implements Serializable { /** * Generated serial version UID diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java index 560a8d274..233b1dcf7 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java @@ -30,7 +30,7 @@ import java.io.Serializable; *

* It is responsible for reacting to the user's actions and update the View component. */ -public class FileSelectorPresenter implements Serializable{ +public class FileSelectorPresenter implements Serializable { /** * Generated serial version UID diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java index 5272ea0b7..e6ab93f66 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java @@ -28,7 +28,7 @@ import java.io.Serializable; * This interface represents the View component in the Model-View-Presenter pattern. It can be * implemented by either the GUI components, or by the Stub. */ -public interface FileSelectorView extends Serializable{ +public interface FileSelectorView extends Serializable { /** * Opens the view. diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java index 83639c0b2..c1b33cb30 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.model.view.presenter; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java index 8e9a558a7..56bc3b8bd 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.model.view.presenter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Date: 12/21/15 - 12:12 PM diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java index 057d4dcdc..ff68cef6e 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.model.view.presenter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +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; /** * This test case is responsible for testing our application by taking advantage of the @@ -54,7 +54,7 @@ public class FileSelectorPresenterTest { /** * Initializes the components of the test case. */ - @Before + @BeforeEach public void setUp() { this.stub = new FileSelectorStub(); this.loader = new FileLoader(); diff --git a/module/README.md b/module/README.md index 24bd3f543..39f4dbffd 100644 --- a/module/README.md +++ b/module/README.md @@ -3,7 +3,6 @@ layout: pattern title: Module folder: module permalink: /patterns/module/ -pumlid: JShB3OGm303HLg20nFVjnYGM1CN6ycTfVtFSsnjfzY5jPgUqkLqHwXy0mxUU8wuyqidQ8q4IjJqCO-QBWGOtVh5qyd5AKOmW4mT6Nu2-ZiAekapH_hkcSTNa-GC0 categories: Creational Pattern tags: - Java diff --git a/module/etc/module.urm.puml b/module/etc/module.urm.puml deleted file mode 100644 index 233691cf7..000000000 --- a/module/etc/module.urm.puml +++ /dev/null @@ -1,43 +0,0 @@ -@startuml -package com.iluwatar.module { - class App { - + consoleLoggerModule : ConsoleLoggerModule {static} - + fileLoggerModule : FileLoggerModule {static} - - App() - + execute(args : String[]) {static} - + main(args : String[]) {static} - + prepare() {static} - + unprepare() {static} - } - class ConsoleLoggerModule { - - LOGGER : Logger {static} - + error : PrintStream - + output : PrintStream - - singleton : ConsoleLoggerModule {static} - - ConsoleLoggerModule() - + getSingleton() : ConsoleLoggerModule {static} - + prepare() : ConsoleLoggerModule - + printErrorString(value : String) - + printString(value : String) - + unprepare() - } - class FileLoggerModule { - - ERROR_FILE : String {static} - - LOGGER : Logger {static} - - OUTPUT_FILE : String {static} - + error : PrintStream - + output : PrintStream - - singleton : FileLoggerModule {static} - - FileLoggerModule() - + getSingleton() : FileLoggerModule {static} - + prepare() : FileLoggerModule - + printErrorString(value : String) - + printString(value : String) - + unprepare() - } -} -FileLoggerModule --> "-singleton" FileLoggerModule -App --> "-consoleLoggerModule" ConsoleLoggerModule -ConsoleLoggerModule --> "-singleton" ConsoleLoggerModule -App --> "-fileLoggerModule" FileLoggerModule -@enduml \ No newline at end of file diff --git a/module/pom.xml b/module/pom.xml index b86069b16..dde967bc6 100644 --- a/module/pom.xml +++ b/module/pom.xml @@ -28,13 +28,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT module - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/module/src/test/java/com/iluwatar/module/AppTest.java b/module/src/test/java/com/iluwatar/module/AppTest.java index 5df6ab0f3..0514dff3a 100644 --- a/module/src/test/java/com/iluwatar/module/AppTest.java +++ b/module/src/test/java/com/iluwatar/module/AppTest.java @@ -18,12 +18,10 @@ */ package com.iluwatar.module; +import org.junit.jupiter.api.Test; + import java.io.FileNotFoundException; -import com.iluwatar.module.App; - -import org.junit.Test; - /** * Tests that Module example runs without errors. */ diff --git a/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java b/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java index 7274aab14..bdae597bc 100644 --- a/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java +++ b/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java @@ -18,15 +18,15 @@ */ package com.iluwatar.module; -import static org.junit.Assert.assertEquals; +import org.apache.log4j.Logger; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import org.apache.log4j.Logger; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages diff --git a/monad/README.md b/monad/README.md index bf6ee58b8..41edd3d92 100644 --- a/monad/README.md +++ b/monad/README.md @@ -3,7 +3,6 @@ layout: pattern title: Monad folder: monad permalink: /patterns/monad/ -pumlid: 9SR13SCm20NGLPe1OkxTXjWeSMMm1Pza_LRgExsjMntP97syBc35cyZvAMV7bKU6U9q6CPGwbVh8Xy5E7xvvRnBzj7qn86v1ol4BwJHk9AZ_bNGjAtLy0G00 categories: Other tags: - Java diff --git a/monad/etc/monad.urm.puml b/monad/etc/monad.urm.puml deleted file mode 100644 index c9dcc8db6..000000000 --- a/monad/etc/monad.urm.puml +++ /dev/null @@ -1,36 +0,0 @@ -@startuml -package com.iluwatar.monad { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - enum Sex { - + FEMALE {static} - + MALE {static} - + valueOf(name : String) : Sex {static} - + values() : Sex[] {static} - } - class User { - - age : int - - email : String - - name : String - - sex : Sex - + User(name : String, age : int, sex : Sex, email : String) - + getAge() : int - + getEmail() : String - + getName() : String - + getSex() : Sex - } - class Validator { - - exceptions : List - - t : T - - Validator(t : T) - + get() : T - + of(t : T) : Validator {static} - + validate(projection : Function, validation : Predicate, message : String) : Validator - + validate(validation : Predicate, message : String) : Validator - } -} -User --> "-sex" Sex -@enduml \ No newline at end of file diff --git a/monad/pom.xml b/monad/pom.xml index 23d5e0c0e..316c4ff9b 100644 --- a/monad/pom.xml +++ b/monad/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT monad - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/monad/src/test/java/com/iluwatar/monad/AppTest.java b/monad/src/test/java/com/iluwatar/monad/AppTest.java index 69464ff87..d6515dfc2 100644 --- a/monad/src/test/java/com/iluwatar/monad/AppTest.java +++ b/monad/src/test/java/com/iluwatar/monad/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.monad; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application Test diff --git a/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/monad/src/test/java/com/iluwatar/monad/MonadTest.java index a34243978..d5c4ded80 100644 --- a/monad/src/test/java/com/iluwatar/monad/MonadTest.java +++ b/monad/src/test/java/com/iluwatar/monad/MonadTest.java @@ -22,36 +22,34 @@ */ package com.iluwatar.monad; - -import junit.framework.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Objects; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * Test for Monad Pattern */ public class MonadTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testForInvalidName() { - thrown.expect(IllegalStateException.class); User tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); - Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get(); + assertThrows(IllegalStateException.class, () -> { + Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get(); + }); } @Test public void testForInvalidAge() { - thrown.expect(IllegalStateException.class); User john = new User("John", 17, Sex.MALE, "john@qwe.bar"); - Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null") - .validate(User::getAge, age -> age > 21, "user is underaged") - .get(); + assertThrows(IllegalStateException.class, () -> { + Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null") + .validate(User::getAge, age -> age > 21, "user is underaged") + .get(); + }); } @Test @@ -62,6 +60,6 @@ public class MonadTest { .validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female") .validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign") .get(); - Assert.assertSame(validated, sarah); + assertSame(validated, sarah); } } diff --git a/monostate/README.md b/monostate/README.md index 8c47b5da4..3576dc659 100644 --- a/monostate/README.md +++ b/monostate/README.md @@ -3,7 +3,6 @@ layout: pattern title: MonoState folder: monostate permalink: /patterns/monostate/ -pumlid: HSV14OGm20NGLjO23FVj1YEZsGaa0nzjVxrvUszfLdlkaju_9p3ZI-HybwFXp2r3l0w364eTIgtdpM2d7r-yxXBji7Ko86v1ol60TDW8C8G4zLr9rp9J-ny0 categories: Creational tags: - Java diff --git a/monostate/etc/monostate.urm.puml b/monostate/etc/monostate.urm.puml deleted file mode 100644 index b7797d5e4..000000000 --- a/monostate/etc/monostate.urm.puml +++ /dev/null @@ -1,33 +0,0 @@ -@startuml -package com.iluwatar.monostate { - class App { - + App() - + main(args : String[]) {static} - } - class LoadBalancer { - - id : int {static} - - lastServedId : int {static} - - servers : List {static} - + LoadBalancer() - + addServer(server : Server) - + getLastServedId() : int {static} - + getNoOfServers() : int - + serverRequest(request : Request) - } - class Request { - + value : String - + Request(value : String) - } - class Server { - - LOGGER : Logger {static} - + host : String - + id : int - + port : int - + Server(host : String, port : int, id : int) - + getHost() : String - + getPort() : int - + serve(request : Request) - } -} -LoadBalancer --> "-servers" Server -@enduml \ No newline at end of file diff --git a/monostate/pom.xml b/monostate/pom.xml index 5343d2094..5aa68e75b 100644 --- a/monostate/pom.xml +++ b/monostate/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT monostate - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java index e440dfba2..b280de767 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java +++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java @@ -35,10 +35,10 @@ import java.util.List; public class LoadBalancer { private static List servers = new ArrayList<>(); - private static int id; private static int lastServedId; static { + int id = 0; servers.add(new Server("localhost", 8081, ++id)); servers.add(new Server("localhost", 8080, ++id)); servers.add(new Server("localhost", 8082, ++id)); @@ -67,14 +67,12 @@ public class LoadBalancer { /** * Handle request */ - public void serverRequest(Request request) { + public synchronized void serverRequest(Request request) { if (lastServedId >= servers.size()) { lastServedId = 0; } Server server = servers.get(lastServedId++); server.serve(request); } - - - + } diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java index 3e88b3bf2..dfa2542aa 100644 --- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java +++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.monostate; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application Test Entry diff --git a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java index 96b4830c7..51cbcdecd 100644 --- a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java +++ b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java @@ -22,11 +22,17 @@ */ package com.iluwatar.monostate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * Date: 12/21/15 - 12:26 PM @@ -41,9 +47,9 @@ public class LoadBalancerTest { final LoadBalancer secondBalancer = new LoadBalancer(); firstBalancer.addServer(new Server("localhost", 8085, 6)); // Both should have the same number of servers. - Assert.assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers()); + assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers()); // Both Should have the same LastServedId - Assert.assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId()); + assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId()); } @Test diff --git a/multiton/README.md b/multiton/README.md index a1154e7bb..0462ff0ec 100644 --- a/multiton/README.md +++ b/multiton/README.md @@ -3,7 +3,6 @@ layout: pattern title: Multiton folder: multiton permalink: /patterns/multiton/ -pumlid: FST14i8m20NGg-W16lRUXgPCYnD81Zxs-hfozzvJlOywf68yBc3bYoZuRgVYghrIea-7E5gVHZhgPd3Gcp-y7P9w-hOOaF0au_o1h0OKqqdG_saLrbRP-080 categories: Creational tags: - Java diff --git a/multiton/etc/multiton.urm.puml b/multiton/etc/multiton.urm.puml deleted file mode 100644 index 63a74b1f1..000000000 --- a/multiton/etc/multiton.urm.puml +++ /dev/null @@ -1,30 +0,0 @@ -@startuml -package com.iluwatar.multiton { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Nazgul { - - name : NazgulName - - nazguls : Map {static} - - Nazgul(name : NazgulName) - + getInstance(name : NazgulName) : Nazgul {static} - + getName() : NazgulName - } - enum NazgulName { - + ADUNAPHEL {static} - + AKHORAHIL {static} - + DWAR {static} - + HOARMURATH {static} - + JI_INDUR {static} - + KHAMUL {static} - + MURAZOR {static} - + REN {static} - + UVATHA {static} - + valueOf(name : String) : NazgulName {static} - + values() : NazgulName[] {static} - } -} -Nazgul --> "-name" NazgulName -@enduml \ No newline at end of file diff --git a/multiton/pom.xml b/multiton/pom.xml index 2e5553588..4ee128a1d 100644 --- a/multiton/pom.xml +++ b/multiton/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT multiton - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java index 370a2665b..14e725b26 100644 --- a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java +++ b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.multiton; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java index ad10a9eb0..941ceeee4 100644 --- a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java +++ b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java @@ -22,11 +22,11 @@ */ package com.iluwatar.multiton; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/22/15 - 22:28 AM diff --git a/mute-idiom/README.md b/mute-idiom/README.md index 5c3dbf10b..bb674b648 100644 --- a/mute-idiom/README.md +++ b/mute-idiom/README.md @@ -3,7 +3,6 @@ layout: pattern title: Mute Idiom folder: mute-idiom permalink: /patterns/mute-idiom/ -pumlid: JSf13iCm20NHgxG7iDdtDjH62PKX5luarq-MtSsJvgtUHdR96AyTcEj357pLJR7dDvT4EnpYgEqmqf4NWuD-V7BfidJpCXcGy4N6wmcoX1Jj-lo2ziUQONMcZHi0 categories: Other tags: - Java diff --git a/mute-idiom/etc/mute-idiom.urm.puml b/mute-idiom/etc/mute-idiom.urm.puml deleted file mode 100644 index 32d036bc8..000000000 --- a/mute-idiom/etc/mute-idiom.urm.puml +++ /dev/null @@ -1,24 +0,0 @@ -@startuml -package com.iluwatar.mute { - class App { - - LOGGER : Logger {static} - + App() - - acquireResource() : Resource {static} - - closeResource(resource : Resource) {static} - + main(args : String[]) {static} - - useOfLoggedMute() {static} - - useOfMute() {static} - - utilizeResource(resource : Resource) {static} - } - interface CheckedRunnable { - + run() {abstract} - } - class Mute { - - Mute() - + loggedMute(runnable : CheckedRunnable) {static} - + mute(runnable : CheckedRunnable) {static} - } - interface Resource { - } -} -@enduml \ No newline at end of file diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml index 92b36915d..905909384 100644 --- a/mute-idiom/pom.xml +++ b/mute-idiom/pom.xml @@ -21,13 +21,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT mute-idiom - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java index 8534ff2ad..31624c994 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java @@ -23,7 +23,7 @@ package com.iluwatar.mute; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that Mute idiom example runs without errors. diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java index 7e1d2e1af..73bab01d2 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -23,17 +23,16 @@ package com.iluwatar.mute; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the mute-idiom pattern @@ -44,8 +43,6 @@ public class MuteTest { private static final String MESSAGE = "should not occur"; - @Rule public ExpectedException exception = ExpectedException.none(); - @Test public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { Mute.mute(() -> methodNotThrowingAnyException()); @@ -53,10 +50,9 @@ public class MuteTest { @Test public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception { - exception.expect(AssertionError.class); - exception.expectMessage(MESSAGE); - - Mute.mute(() -> methodThrowingException()); + assertThrows(AssertionError.class, () -> { + Mute.mute(() -> methodThrowingException()); + }); } @Test diff --git a/mutex/README.md b/mutex/README.md index 78cda9060..84755872f 100644 --- a/mutex/README.md +++ b/mutex/README.md @@ -3,7 +3,6 @@ layout: pattern title: Mutex folder: mutex permalink: /patterns/mutex/ -pumlid: 9SR13OCm30NGLSe0n7UsCS62LB69x6zWV2hrdTxKhFRS9Br_3c34GkHybxtXo3L3l9u6CPHwAhMUDuETldpnl4cqtUR1WBW5ASSlf0bvI53_A-bQHcf_0G00 categories: Concurrency tags: - Java diff --git a/mutex/etc/mutex.urm.puml b/mutex/etc/mutex.urm.puml deleted file mode 100644 index 08cf43b90..000000000 --- a/mutex/etc/mutex.urm.puml +++ /dev/null @@ -1,27 +0,0 @@ -@startuml -package com.iluwatar.mutex { - class App { - + App() - + main(args : String[]) {static} - } - class Jar { - - beans : int - - lock : Lock - + Jar(beans : int, lock : Lock) - + takeBean() : boolean - } - interface Lock { - + acquire() {abstract} - + release() {abstract} - } - class Mutex { - - owner : Object - + Mutex() - + acquire() - + getOwner() : Object - + release() - } -} -Jar --> "-lock" Lock -Mutex ..|> Lock -@enduml \ No newline at end of file diff --git a/mutex/pom.xml b/mutex/pom.xml index 6ba6c74a3..5c65d6305 100644 --- a/mutex/pom.xml +++ b/mutex/pom.xml @@ -29,14 +29,19 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT mutex - junit - junit + org.junit.jupiter + junit-jupiter-api test - + + + org.junit.jupiter + junit-jupiter-engine + test + diff --git a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java index f224a56f5..8e9ecf875 100644 --- a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java +++ b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java @@ -22,13 +22,14 @@ */ package com.iluwatar.mutex; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; /** * Application Test Entrypoint */ -public class AppTest{ +public class AppTest { @Test public void test() throws IOException { String[] args = {}; diff --git a/mutex/src/test/java/com/iluwatar/mutex/JarTest.java b/mutex/src/test/java/com/iluwatar/mutex/JarTest.java index b9e0c52ca..4f2e91d7e 100644 --- a/mutex/src/test/java/com/iluwatar/mutex/JarTest.java +++ b/mutex/src/test/java/com/iluwatar/mutex/JarTest.java @@ -22,8 +22,10 @@ */ package com.iluwatar.mutex; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test case for taking beans from a Jar diff --git a/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java b/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java index 93649002f..4d61764d8 100644 --- a/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java +++ b/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java @@ -22,8 +22,11 @@ */ package com.iluwatar.mutex; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Test case for acquiring and releasing a Mutex diff --git a/naked-objects/README.md b/naked-objects/README.md index 66e6ac2b0..eb1c083b1 100644 --- a/naked-objects/README.md +++ b/naked-objects/README.md @@ -29,4 +29,4 @@ Use the Naked Objects pattern when ## Credits -* [Richard Pawson - Naked Objects](https://isis.apache.org/resources/thesis/Pawson-Naked-Objects-thesis.pdf) +* [Richard Pawson - Naked Objects](http://downloads.nakedobjects.net/resources/Pawson%20thesis.pdf) diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index f26060fbf..3efcecdca 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT naked-objects-dom @@ -50,6 +50,12 @@ test + + org.junit.vintage + junit-vintage-engine + test + + org.objenesis diff --git a/naked-objects/etc/naked-objects-dom.urm.puml b/naked-objects/etc/naked-objects-dom.urm.puml deleted file mode 100644 index 462364099..000000000 --- a/naked-objects/etc/naked-objects-dom.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package domainapp.dom.app.homepage { - class HomePageService { - ~ container : DomainObjectContainer - + HomePageService() - + homePage() : HomePageViewModel - } - class HomePageViewModel { - ~ simpleObjects : SimpleObjects - + HomePageViewModel() - + getObjects() : List - + title() : String - } -} -package domainapp.dom.modules.simple { - class SimpleObject { - - container : DomainObjectContainer - - name : String - + SimpleObject() - + compareTo(other : SimpleObject) : int - + default0UpdateName() : String - + getName() : String - + getVersionSequence() : Long - + setName(name : String) - + title() : TranslatableString - + updateName(name : String) : SimpleObject - + validateUpdateName(name : String) : TranslatableString - } - class SimpleObjects { - ~ container : DomainObjectContainer - + SimpleObjects() - + create(name : String) : SimpleObject - + findByName(name : String) : List - + listAll() : List - + title() : TranslatableString - } -} -HomePageViewModel --> "-simpleObjects" SimpleObjects -@enduml \ No newline at end of file diff --git a/naked-objects/etc/naked-objects-fixture.urm.puml b/naked-objects/etc/naked-objects-fixture.urm.puml deleted file mode 100644 index 04b3b1350..000000000 --- a/naked-objects/etc/naked-objects-fixture.urm.puml +++ /dev/null @@ -1,93 +0,0 @@ -@startuml -package domainapp.dom.app.homepage { - class HomePageService { - ~ container : DomainObjectContainer - + HomePageService() - + homePage() : HomePageViewModel - } - class HomePageViewModel { - ~ simpleObjects : SimpleObjects - + HomePageViewModel() - + getObjects() : List - + title() : String - } -} -package domainapp.dom.modules.simple { - class SimpleObject { - - container : DomainObjectContainer - - dnFieldFlags : byte[] {static} - - dnFieldNames : String[] {static} - - dnFieldTypes : Class[] {static} - # dnFlags : byte - - dnInheritedFieldCount : int {static} - - dnPersistableSuperclass : Class {static} - # dnStateManager : StateManager - - name : String - + SimpleObject() - + ___dn$loadClass(className : String) : Class {static} - - __dnFieldFlagsInit() : byte[] {static} - - __dnFieldNamesInit() : String[] {static} - - __dnFieldTypesInit() : Class[] {static} - # __dnGetInheritedFieldCount() : int {static} - - __dnPersistableSuperclassInit() : Class {static} - + compareTo(other : SimpleObject) : int - + default0UpdateName() : String - # dnCopyField(obj : SimpleObject, index : int) - + dnCopyFields(obj : Object, indices : int[]) - + dnCopyKeyFieldsFromObjectId(fc : ObjectIdFieldConsumer, oid : Object) - # dnCopyKeyFieldsFromObjectId(oid : Object) - + dnCopyKeyFieldsToObjectId(fs : ObjectIdFieldSupplier, oid : Object) - + dnCopyKeyFieldsToObjectId(oid : Object) - + dnGetExecutionContext() : ExecutionContextReference - # dnGetManagedFieldCount() : int {static} - + dnGetObjectId() : Object - + dnGetTransactionalObjectId() : Object - + dnGetVersion() : Object - + dnGetname() : String - + dnIsDeleted() : boolean - + dnIsDetached() : boolean - + dnIsDirty() : boolean - + dnIsNew() : boolean - + dnIsPersistent() : boolean - + dnIsTransactional() : boolean - + dnMakeDirty(fieldName : String) - + dnNewInstance(sm : StateManager) : Persistable - + dnNewInstance(sm : StateManager, obj : Object) : Persistable - + dnNewObjectIdInstance() : Object - + dnNewObjectIdInstance(key : Object) : Object - # dnPreSerialize() - + dnProvideField(index : int) - + dnProvideFields(indices : int[]) - + dnReplaceField(index : int) - + dnReplaceFields(indices : int[]) - + dnReplaceFlags() - + dnReplaceStateManager(sm : StateManager) - + dnSetname(name : String) - - dnSuperClone() : Object - + getName() : String - + getVersionSequence() : Long - + setName(val : String) - + title() : TranslatableString - + updateName(name : String) : SimpleObject - + validateUpdateName(name : String) : TranslatableString - } - class SimpleObjects { - ~ container : DomainObjectContainer - + SimpleObjects() - + create(name : String) : SimpleObject - + findByName(name : String) : List - + listAll() : List - + title() : TranslatableString - } -} -package domainapp.fixture { - class DomainAppFixturesProvider { - + DomainAppFixturesProvider() - + getSpecification() : FixtureScriptsSpecification - } -} -Builder ..+ FixtureScriptsSpecification -DropDownPolicy ..+ FixtureScriptsSpecification -MultipleExecutionStrategy ..+ FixtureScripts -HomePageViewModel --> "-simpleObjects" SimpleObjects -@enduml \ No newline at end of file diff --git a/naked-objects/etc/naked-objects-integtests.urm.puml b/naked-objects/etc/naked-objects-integtests.urm.puml deleted file mode 100644 index 04b3b1350..000000000 --- a/naked-objects/etc/naked-objects-integtests.urm.puml +++ /dev/null @@ -1,93 +0,0 @@ -@startuml -package domainapp.dom.app.homepage { - class HomePageService { - ~ container : DomainObjectContainer - + HomePageService() - + homePage() : HomePageViewModel - } - class HomePageViewModel { - ~ simpleObjects : SimpleObjects - + HomePageViewModel() - + getObjects() : List - + title() : String - } -} -package domainapp.dom.modules.simple { - class SimpleObject { - - container : DomainObjectContainer - - dnFieldFlags : byte[] {static} - - dnFieldNames : String[] {static} - - dnFieldTypes : Class[] {static} - # dnFlags : byte - - dnInheritedFieldCount : int {static} - - dnPersistableSuperclass : Class {static} - # dnStateManager : StateManager - - name : String - + SimpleObject() - + ___dn$loadClass(className : String) : Class {static} - - __dnFieldFlagsInit() : byte[] {static} - - __dnFieldNamesInit() : String[] {static} - - __dnFieldTypesInit() : Class[] {static} - # __dnGetInheritedFieldCount() : int {static} - - __dnPersistableSuperclassInit() : Class {static} - + compareTo(other : SimpleObject) : int - + default0UpdateName() : String - # dnCopyField(obj : SimpleObject, index : int) - + dnCopyFields(obj : Object, indices : int[]) - + dnCopyKeyFieldsFromObjectId(fc : ObjectIdFieldConsumer, oid : Object) - # dnCopyKeyFieldsFromObjectId(oid : Object) - + dnCopyKeyFieldsToObjectId(fs : ObjectIdFieldSupplier, oid : Object) - + dnCopyKeyFieldsToObjectId(oid : Object) - + dnGetExecutionContext() : ExecutionContextReference - # dnGetManagedFieldCount() : int {static} - + dnGetObjectId() : Object - + dnGetTransactionalObjectId() : Object - + dnGetVersion() : Object - + dnGetname() : String - + dnIsDeleted() : boolean - + dnIsDetached() : boolean - + dnIsDirty() : boolean - + dnIsNew() : boolean - + dnIsPersistent() : boolean - + dnIsTransactional() : boolean - + dnMakeDirty(fieldName : String) - + dnNewInstance(sm : StateManager) : Persistable - + dnNewInstance(sm : StateManager, obj : Object) : Persistable - + dnNewObjectIdInstance() : Object - + dnNewObjectIdInstance(key : Object) : Object - # dnPreSerialize() - + dnProvideField(index : int) - + dnProvideFields(indices : int[]) - + dnReplaceField(index : int) - + dnReplaceFields(indices : int[]) - + dnReplaceFlags() - + dnReplaceStateManager(sm : StateManager) - + dnSetname(name : String) - - dnSuperClone() : Object - + getName() : String - + getVersionSequence() : Long - + setName(val : String) - + title() : TranslatableString - + updateName(name : String) : SimpleObject - + validateUpdateName(name : String) : TranslatableString - } - class SimpleObjects { - ~ container : DomainObjectContainer - + SimpleObjects() - + create(name : String) : SimpleObject - + findByName(name : String) : List - + listAll() : List - + title() : TranslatableString - } -} -package domainapp.fixture { - class DomainAppFixturesProvider { - + DomainAppFixturesProvider() - + getSpecification() : FixtureScriptsSpecification - } -} -Builder ..+ FixtureScriptsSpecification -DropDownPolicy ..+ FixtureScriptsSpecification -MultipleExecutionStrategy ..+ FixtureScripts -HomePageViewModel --> "-simpleObjects" SimpleObjects -@enduml \ No newline at end of file diff --git a/naked-objects/fixture/pom.xml b/naked-objects/fixture/pom.xml index 0fccbaf56..bf3cc4de8 100644 --- a/naked-objects/fixture/pom.xml +++ b/naked-objects/fixture/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT naked-objects-fixture diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index ba620c5be..8d2cf3b55 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT naked-objects-integtests @@ -79,6 +79,12 @@ test + + org.junit.vintage + junit-vintage-engine + test + + org.hsqldb hsqldb diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml index 4dee87660..222a9d321 100644 --- a/naked-objects/pom.xml +++ b/naked-objects/pom.xml @@ -15,7 +15,7 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT naked-objects @@ -317,23 +317,6 @@ org.apache.maven.plugins maven-surefire-report-plugin - - com.github.markusmo3.urm - urm-maven-plugin - ${urm.version} - - ${project.basedir}/../etc - - com.iluwatar - domainapp - - - - naked-objects - naked-objects-webapp - - - @@ -367,17 +350,17 @@ ${project.groupId} naked-objects-dom - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT ${project.groupId} naked-objects-fixture - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT ${project.groupId} naked-objects-webapp - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT diff --git a/naked-objects/webapp/pom.xml b/naked-objects/webapp/pom.xml index d318da81d..0f9d33bc4 100644 --- a/naked-objects/webapp/pom.xml +++ b/naked-objects/webapp/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT naked-objects-webapp @@ -221,6 +221,18 @@ + + + junit + junit + test + + + + org.junit.vintage + junit-vintage-engine + test + diff --git a/null-object/README.md b/null-object/README.md index bfaaeac66..0ed28a0af 100644 --- a/null-object/README.md +++ b/null-object/README.md @@ -3,7 +3,6 @@ layout: pattern title: Null Object folder: null-object permalink: /patterns/null-object/ -pumlid: JSV14SCm20J0Lk829Fxf1cF6bWSX3JhYzfDdVhjRSx4yDCDU5p3NcoZugMV3bNik3HaETLGPdPhbm-2WcpzS3btjz38PqF15dTSFv6bMndwhW1Jo_vhHwynkNm00 categories: Behavioral tags: - Java diff --git a/null-object/etc/null-object.urm.puml b/null-object/etc/null-object.urm.puml deleted file mode 100644 index a937a2b17..000000000 --- a/null-object/etc/null-object.urm.puml +++ /dev/null @@ -1,41 +0,0 @@ -@startuml -package com.iluwatar.nullobject { - class App { - + App() - + main(args : String[]) {static} - } - interface Node { - + getLeft() : Node {abstract} - + getName() : String {abstract} - + getRight() : Node {abstract} - + getTreeSize() : int {abstract} - + walk() {abstract} - } - class NodeImpl { - - LOGGER : Logger {static} - - left : Node - - name : String - - right : Node - + NodeImpl(name : String, left : Node, right : Node) - + getLeft() : Node - + getName() : String - + getRight() : Node - + getTreeSize() : int - + walk() - } - class NullNode { - - instance : NullNode {static} - - NullNode() - + getInstance() : NullNode {static} - + getLeft() : Node - + getName() : String - + getRight() : Node - + getTreeSize() : int - + walk() - } -} -NullNode --> "-instance" NullNode -NodeImpl --> "-left" Node -NodeImpl ..|> Node -NullNode ..|> Node -@enduml \ No newline at end of file diff --git a/null-object/pom.xml b/null-object/pom.xml index 0d4248dbc..92831afb0 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT null-object - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java index 13e92034a..484807aea 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.nullobject; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java index 778344e06..0482b7f89 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java @@ -22,9 +22,12 @@ */ package com.iluwatar.nullobject; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/26/15 - 11:47 PM diff --git a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java index 6a683a60e..f0cdbf0c9 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java @@ -25,15 +25,18 @@ package com.iluwatar.nullobject; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/26/15 - 11:44 PM @@ -44,12 +47,12 @@ public class TreeTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/object-mother/README.md b/object-mother/README.md index cda3336cf..125ecdfe5 100644 --- a/object-mother/README.md +++ b/object-mother/README.md @@ -3,7 +3,6 @@ layout: pattern title: Object Mother folder: object-mother permalink: /patterns/object-mother/ -pumlid: LOr13iCW30JlVKNx0E3UKxxYW9KGWK7sklb-wR6dtLbfj9k15DxRurKbDo_isfudCEsTaj8TZuhJTpVMF0GiY7dqL9lVjDHqqOT2OQk7X4a0grZgPAkaiL-S4Vh0kOYH_vVeskFyVMyiPUKN categories: Creational tags: - Java diff --git a/object-mother/etc/object-mother.urm.puml b/object-mother/etc/object-mother.urm.puml deleted file mode 100644 index 1bb52f2ed..000000000 --- a/object-mother/etc/object-mother.urm.puml +++ /dev/null @@ -1,45 +0,0 @@ -@startuml -package com.iluwatar.objectmother { - class King { - ~ isDrunk : boolean - ~ isHappy : boolean - + King() - + flirt(queen : Queen) - + isHappy() : boolean - + makeDrunk() - + makeHappy() - + makeSober() - + makeUnhappy() - } - class Queen { - - isDrunk : boolean - - isFlirty : boolean - - isHappy : boolean - + Queen() - + getFlirted(king : King) : boolean - + isFlirty() : boolean - + makeDrunk() - + makeHappy() - + makeSober() - + makeUnhappy() - + setFlirtiness(flirtiness : boolean) - } - interface Royalty { - + makeDrunk() {abstract} - + makeHappy() {abstract} - + makeSober() {abstract} - + makeUnhappy() {abstract} - } - class RoyaltyObjectMother { - + RoyaltyObjectMother() - + createDrunkKing() : King {static} - + createFlirtyQueen() : Queen {static} - + createHappyDrunkKing() : King {static} - + createHappyKing() : King {static} - + createNotFlirtyQueen() : Queen {static} - + createSoberUnhappyKing() : King {static} - } -} -King ..|> Royalty -Queen ..|> Royalty -@enduml \ No newline at end of file diff --git a/object-mother/pom.xml b/object-mother/pom.xml index 7b598ed9a..e58d36f7d 100644 --- a/object-mother/pom.xml +++ b/object-mother/pom.xml @@ -30,13 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT object-mother - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java b/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java index cc5af45aa..9bc29611c 100644 --- a/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java +++ b/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java @@ -22,16 +22,15 @@ */ package com.iluwatar.objectmother.test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - import com.iluwatar.objectmother.King; import com.iluwatar.objectmother.Queen; import com.iluwatar.objectmother.Royalty; import com.iluwatar.objectmother.RoyaltyObjectMother; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Generation of Royalty Types using the object-mother diff --git a/object-pool/README.md b/object-pool/README.md index 15fee51aa..cf36d9880 100644 --- a/object-pool/README.md +++ b/object-pool/README.md @@ -3,7 +3,6 @@ layout: pattern title: Object Pool folder: object-pool permalink: /patterns/object-pool/ -pumlid: JSV94SCm2030Lk829Fxf1cF6bWU1XYDkFtdcjxiD9Qc3o-LrPQvu0pW-_HnvrLx1JgR9cfrimf1wCD7XnW-sWsESsXPcicl0nFW1RB-PiYqp0KxwVo-VVTMKBm00 categories: Creational tags: - Java diff --git a/object-pool/etc/object-pool.urm.puml b/object-pool/etc/object-pool.urm.puml deleted file mode 100644 index ca74f8cec..000000000 --- a/object-pool/etc/object-pool.urm.puml +++ /dev/null @@ -1,30 +0,0 @@ -@startuml -package com.iluwatar.object.pool { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - abstract class ObjectPool { - - available : Set - - inUse : Set - + ObjectPool() - + checkIn(instance : T) - + checkOut() : T - # create() : T {abstract} - + toString() : String - } - class Oliphaunt { - - counter : int {static} - - id : int - + Oliphaunt() - + getId() : int - + toString() : String - } - class OliphauntPool { - + OliphauntPool() - # create() : Oliphaunt - } -} -OliphauntPool --|> ObjectPool -@enduml \ No newline at end of file diff --git a/object-pool/pom.xml b/object-pool/pom.xml index 66d694169..5e59bbfd9 100644 --- a/object-pool/pom.xml +++ b/object-pool/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT object-pool - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java index c92399c32..54524c2f6 100644 --- a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java +++ b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.object.pool; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java index 46ed22b36..e92709fca 100644 --- a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java +++ b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java @@ -22,15 +22,17 @@ */ package com.iluwatar.object.pool; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/27/15 - 1:05 AM @@ -43,78 +45,80 @@ public class OliphauntPoolTest { * Use the same object 100 times subsequently. This should not take much time since the heavy * object instantiation is done only once. Verify if we get the same object each time. */ - @Test(timeout = 5000) + @Test public void testSubsequentCheckinCheckout() { - final OliphauntPool pool = new OliphauntPool(); - assertEquals(pool.toString(), "Pool available=0 inUse=0"); + assertTimeout(ofMillis(5000), () -> { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); - final Oliphaunt expectedOliphaunt = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=1"); - - pool.checkIn(expectedOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=0"); - - for (int i = 0; i < 100; i++) { - final Oliphaunt oliphaunt = pool.checkOut(); + final Oliphaunt expectedOliphaunt = pool.checkOut(); assertEquals(pool.toString(), "Pool available=0 inUse=1"); - assertSame(expectedOliphaunt, oliphaunt); - assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); - assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); - pool.checkIn(oliphaunt); + pool.checkIn(expectedOliphaunt); assertEquals(pool.toString(), "Pool available=1 inUse=0"); - } + for (int i = 0; i < 100; i++) { + final Oliphaunt oliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + assertSame(expectedOliphaunt, oliphaunt); + assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); + assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); + + pool.checkIn(oliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=0"); + } + }); } /** * Use the same object 100 times subsequently. This should not take much time since the heavy * object instantiation is done only once. Verify if we get the same object each time. */ - @Test(timeout = 5000) + @Test public void testConcurrentCheckinCheckout() { - final OliphauntPool pool = new OliphauntPool(); - assertEquals(pool.toString(), "Pool available=0 inUse=0"); + assertTimeout(ofMillis(5000), () -> { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); - final Oliphaunt firstOliphaunt = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=1"); + final Oliphaunt firstOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); - final Oliphaunt secondOliphaunt = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); + final Oliphaunt secondOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertNotSame(firstOliphaunt, secondOliphaunt); - assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); + assertNotSame(firstOliphaunt, secondOliphaunt); + assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); - // After checking in the second, we should get the same when checking out a new oliphaunt ... - pool.checkIn(secondOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // After checking in the second, we should get the same when checking out a new oliphaunt ... + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - final Oliphaunt oliphaunt3 = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertSame(secondOliphaunt, oliphaunt3); + final Oliphaunt oliphaunt3 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(secondOliphaunt, oliphaunt3); - // ... and the same applies for the first one - pool.checkIn(firstOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // ... and the same applies for the first one + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - final Oliphaunt oliphaunt4 = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertSame(firstOliphaunt, oliphaunt4); + final Oliphaunt oliphaunt4 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(firstOliphaunt, oliphaunt4); - // When both oliphaunt return to the pool, we should still get the same instances - pool.checkIn(firstOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // When both oliphaunt return to the pool, we should still get the same instances + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - pool.checkIn(secondOliphaunt); - assertEquals(pool.toString(), "Pool available=2 inUse=0"); - - // The order of the returned instances is not determined, so just put them in a list - // and verify if both expected instances are in there. - final List oliphaunts = Arrays.asList(pool.checkOut(), pool.checkOut()); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertTrue(oliphaunts.contains(firstOliphaunt)); - assertTrue(oliphaunts.contains(secondOliphaunt)); + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=2 inUse=0"); + // The order of the returned instances is not determined, so just put them in a list + // and verify if both expected instances are in there. + final List oliphaunts = Arrays.asList(pool.checkOut(), pool.checkOut()); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertTrue(oliphaunts.contains(firstOliphaunt)); + assertTrue(oliphaunts.contains(secondOliphaunt)); + }); } diff --git a/observer/README.md b/observer/README.md index 3b3fcd2c5..38a28032f 100644 --- a/observer/README.md +++ b/observer/README.md @@ -3,7 +3,6 @@ layout: pattern title: Observer folder: observer permalink: /patterns/observer/ -pumlid: FSkn4OGm30NHLg00hFow4KO3PcpP8tr1-pYwx6smQz5Suv2mkbp0y1-HyPlEWYlsSB7S5Q98kJSgDLu66ztyy7Q8brEtmO2OEZNs2Uhxl9u9GVv72cjfHAiV categories: Behavioral tags: - Java diff --git a/observer/etc/observer.urm.puml b/observer/etc/observer.urm.puml deleted file mode 100644 index 5d046d880..000000000 --- a/observer/etc/observer.urm.puml +++ /dev/null @@ -1,81 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.observer { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Hobbits { - - LOGGER : Logger {static} - + Hobbits() - + update(currentWeather : WeatherType) - } - class Orcs { - - LOGGER : Logger {static} - + Orcs() - + update(currentWeather : WeatherType) - } - class Weather { - - LOGGER : Logger {static} - - currentWeather : WeatherType - - observers : List - + Weather() - + addObserver(obs : WeatherObserver) - - notifyObservers() - + removeObserver(obs : WeatherObserver) - + timePasses() - } - interface WeatherObserver { - + update(WeatherType) {abstract} - } - enum WeatherType { - + COLD {static} - + RAINY {static} - + SUNNY {static} - + WINDY {static} - + toString() : String - + valueOf(name : String) : WeatherType {static} - + values() : WeatherType[] {static} - } -} -package com.iluwatar.observer.generic { - class GHobbits { - - LOGGER : Logger {static} - + GHobbits() - + update(weather : GWeather, weatherType : WeatherType) - } - class GOrcs { - - LOGGER : Logger {static} - + GOrcs() - + update(weather : GWeather, weatherType : WeatherType) - } - class GWeather { - - LOGGER : Logger {static} - - currentWeather : WeatherType - + GWeather() - + timePasses() - } - abstract class Observable, A> { - # observers : List> - + Observable, A>() - + addObserver(observer : O extends Observer) - + notifyObservers(argument : A) - + removeObserver(observer : O extends Observer) - } - interface Observer, O extends Observer, A> { - + update(S extends Observable, A) {abstract} - } - interface Race { - } -} -Weather --> "-currentWeather" WeatherType -GWeather --> "-currentWeather" WeatherType -Weather --> "-observers" WeatherObserver -Hobbits ..|> WeatherObserver -Orcs ..|> WeatherObserver -GHobbits ..|> Race -GOrcs ..|> Race -GWeather --|> Observable -Race --|> Observer -@enduml diff --git a/observer/pom.xml b/observer/pom.xml index e1f2cf6bd..20e4aa659 100644 --- a/observer/pom.xml +++ b/observer/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT observer - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/observer/src/test/java/com/iluwatar/observer/AppTest.java b/observer/src/test/java/com/iluwatar/observer/AppTest.java index 11bbb5496..086a5de76 100644 --- a/observer/src/test/java/com/iluwatar/observer/AppTest.java +++ b/observer/src/test/java/com/iluwatar/observer/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.observer; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java index 31a4fd667..21e4acd44 100644 --- a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java @@ -22,9 +22,6 @@ */ package com.iluwatar.observer; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -34,11 +31,9 @@ import java.util.List; * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class HobbitsTest extends WeatherObserverTest { - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { final List testData = new ArrayList<>(); testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); @@ -49,12 +44,9 @@ public class HobbitsTest extends WeatherObserverTest { /** * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer */ - public HobbitsTest(final WeatherType weather, final String response) { - super(weather, response, Hobbits::new); + public HobbitsTest() { + super(Hobbits::new); } } diff --git a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java index b1f0b82d7..78667b678 100644 --- a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java @@ -22,9 +22,6 @@ */ package com.iluwatar.observer; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -34,11 +31,9 @@ import java.util.List; * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class OrcsTest extends WeatherObserverTest { - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { final List testData = new ArrayList<>(); testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); @@ -49,12 +44,9 @@ public class OrcsTest extends WeatherObserverTest { /** * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer */ - public OrcsTest(final WeatherType weather, final String response) { - super(weather, response, Orcs::new); + public OrcsTest() { + super(Orcs::new); } } diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java index 70a7922c5..da3fad1eb 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -22,13 +22,16 @@ */ package com.iluwatar.observer; -import static org.junit.Assert.assertEquals; - import com.iluwatar.observer.utils.InMemoryAppender; import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 11:44 AM @@ -40,12 +43,12 @@ public abstract class WeatherObserverTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } @@ -55,38 +58,25 @@ public abstract class WeatherObserverTest { */ private final Supplier factory; - /** - * The weather type currently tested - */ - private final WeatherType weather; - - /** - * The expected response from the observer - */ - private final String response; - /** * Create a new test instance using the given parameters * - * @param weather The weather currently being tested - * @param response The expected response from the observer * @param factory The factory, used to create an instance of the tested observer */ - WeatherObserverTest(final WeatherType weather, final String response, final Supplier factory) { - this.weather = weather; - this.response = response; + WeatherObserverTest(final Supplier factory) { this.factory = factory; } /** * Verify if the weather has the expected influence on the observer */ - @Test - public void testObserver() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testObserver(WeatherType weather, String response) { final O observer = this.factory.get(); assertEquals(0, appender.getLogSize()); - observer.update(this.weather); + observer.update(weather); assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java index 88bf1c4c3..ca84be5f6 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -23,12 +23,12 @@ package com.iluwatar.observer; import com.iluwatar.observer.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -44,12 +44,12 @@ public class WeatherTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Weather.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java index a54f15689..8d86529c7 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java @@ -22,13 +22,8 @@ */ package com.iluwatar.observer.generic; -import com.iluwatar.observer.Hobbits; -import com.iluwatar.observer.WeatherObserverTest; import com.iluwatar.observer.WeatherType; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -38,11 +33,9 @@ import java.util.List; * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class GHobbitsTest extends ObserverTest { - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { final List testData = new ArrayList<>(); testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); @@ -53,12 +46,9 @@ public class GHobbitsTest extends ObserverTest { /** * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer */ - public GHobbitsTest(final WeatherType weather, final String response) { - super(weather, response, GHobbits::new); + public GHobbitsTest() { + super(GHobbits::new); } } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java index ab15ca884..d7adeff89 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java @@ -25,12 +25,12 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherObserver; import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; /** @@ -42,12 +42,12 @@ public class GWeatherTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(GWeather.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java index 930f7533f..0feba8ea2 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -22,14 +22,16 @@ */ package com.iluwatar.observer.generic; -import static org.junit.Assert.assertEquals; - import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 11:44 AM @@ -41,12 +43,12 @@ public abstract class ObserverTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } @@ -56,39 +58,26 @@ public abstract class ObserverTest { */ private final Supplier factory; - /** - * The weather type currently tested - */ - private final WeatherType weather; - - /** - * The expected response from the observer - */ - private final String response; - /** * Create a new test instance using the given parameters * - * @param weather The weather currently being tested - * @param response The expected response from the observer * @param factory The factory, used to create an instance of the tested observer */ - ObserverTest(final WeatherType weather, final String response, final Supplier factory) { - this.weather = weather; - this.response = response; + ObserverTest(final Supplier factory) { this.factory = factory; } /** * Verify if the weather has the expected influence on the observer */ - @Test - public void testObserver() { + @ParameterizedTest + @MethodSource("dataProvider") + public void testObserver(WeatherType weather, String response) { final O observer = this.factory.get(); assertEquals(0, appender.getLogSize()); - observer.update(null, this.weather); - assertEquals(this.response, appender.getLastMessage()); + observer.update(null, weather); + assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java index a61a91afe..95adf5a28 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java @@ -24,9 +24,6 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -36,11 +33,9 @@ import java.util.List; * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class OrcsTest extends ObserverTest { - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { final List testData = new ArrayList<>(); testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); @@ -51,12 +46,9 @@ public class OrcsTest extends ObserverTest { /** * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer */ - public OrcsTest(final WeatherType weather, final String response) { - super(weather, response, GOrcs::new); + public OrcsTest() { + super(GOrcs::new); } } diff --git a/page-object/etc/page-object.urm.puml b/page-object/etc/page-object.urm.puml deleted file mode 100644 index 735cf2889..000000000 --- a/page-object/etc/page-object.urm.puml +++ /dev/null @@ -1,8 +0,0 @@ -@startuml -package com.iluwatar.pageobject { - class App { - - App() - + main(args : String[]) {static} - } -} -@enduml \ No newline at end of file diff --git a/page-object/pom.xml b/page-object/pom.xml index ea17c372c..a54998d70 100644 --- a/page-object/pom.xml +++ b/page-object/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT page-object - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java index 79101f3d3..9cc3893f4 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -22,14 +22,13 @@ */ package com.iluwatar.pageobject; - -import static org.junit.Assert.assertTrue; - import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.AlbumPage; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Album Selection and Album Listing @@ -38,7 +37,7 @@ public class AlbumListPageTest { private AlbumListPage albumListPage = new AlbumListPage(new WebClient()); - @Before + @BeforeEach public void setUp() { albumListPage.navigateToPage(); } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java index cb07a8293..4b567fcad 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.pageobject; -import static org.junit.Assert.assertTrue; - import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.AlbumPage; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Album Page Operations @@ -37,7 +37,7 @@ public class AlbumPageTest { private AlbumPage albumPage = new AlbumPage(new WebClient()); - @Before + @BeforeEach public void setUp() { albumPage.navigateToPage(); } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java index ad10a1927..59f69552b 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.pageobject; -import static org.junit.Assert.assertTrue; - import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.LoginPage; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Login Page Object @@ -37,7 +37,7 @@ public class LoginPageTest { private LoginPage loginPage = new LoginPage(new WebClient()); - @Before + @BeforeEach public void setUp() { loginPage.navigateToPage(); } diff --git a/partial-response/etc/partial-response.urm.puml b/partial-response/etc/partial-response.urm.puml deleted file mode 100644 index 69efd0454..000000000 --- a/partial-response/etc/partial-response.urm.puml +++ /dev/null @@ -1,31 +0,0 @@ -@startuml -package com.iluwatar.partialresponse { - class FieldJsonMapper { - + FieldJsonMapper() - - getString(video : Video, declaredField : Field) : String - + toJson(video : Video, fields : String[]) : String - } - class Video { - - description : String - - director : String - - id : Integer - - language : String - - length : Integer - - title : String - + Video(id : Integer, title : String, length : Integer, description : String, director : String, language : String) - + toString() : String - } - class VideoClientApp { - - LOGGER : Logger {static} - + VideoClientApp() - + main(args : String[]) {static} - } - class VideoResource { - - fieldJsonMapper : FieldJsonMapper - - videos : Map - + VideoResource(fieldJsonMapper : FieldJsonMapper, videos : Map) - + getDetails(id : Integer, fields : String[]) : String - } -} -VideoResource --> "-fieldJsonMapper" FieldJsonMapper -@enduml \ No newline at end of file diff --git a/partial-response/pom.xml b/partial-response/pom.xml index ed685eb6a..db0a922ee 100644 --- a/partial-response/pom.xml +++ b/partial-response/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 @@ -39,6 +39,11 @@ junit junit + + org.junit.vintage + junit-vintage-engine + test + org.mockito mockito-core diff --git a/poison-pill/README.md b/poison-pill/README.md index 8f673ad49..0815b376e 100644 --- a/poison-pill/README.md +++ b/poison-pill/README.md @@ -3,7 +3,6 @@ layout: pattern title: Poison Pill folder: poison-pill permalink: /patterns/poison-pill/ -pumlid: JSZ14SCm20NHLf82BExfXiYCJGOX3NpYzkDZRllsgTwjTgcmnmciV145N-rGdFMkbEZJ8OxMvo2rkXWSzE4lRxka7huj1YGyQN3UGMjgpdkh6Gdwlrl5QAk6_G00 categories: Other tags: - Java diff --git a/poison-pill/etc/poison-pill.urm.puml b/poison-pill/etc/poison-pill.urm.puml deleted file mode 100644 index 5c2b9fa2b..000000000 --- a/poison-pill/etc/poison-pill.urm.puml +++ /dev/null @@ -1,71 +0,0 @@ -@startuml -package com.iluwatar.poison.pill { - class App { - + App() - + main(args : String[]) {static} - } - class Consumer { - - LOGGER : Logger {static} - - name : String - - queue : MqSubscribePoint - + Consumer(name : String, queue : MqSubscribePoint) - + consume() - } - interface Message { - + POISON_PILL : Message {static} - + addHeader(Headers, String) {abstract} - + getBody() : String {abstract} - + getHeader(Headers) : String {abstract} - + getHeaders() : Map {abstract} - + setBody(String) {abstract} - } - enum Headers { - + DATE {static} - + SENDER {static} - + valueOf(name : String) : Headers {static} - + values() : Headers[] {static} - } - interface MessageQueue { - } - interface MqPublishPoint { - + put(Message) {abstract} - } - interface MqSubscribePoint { - + take() : Message {abstract} - } - class Producer { - - LOGGER : Logger {static} - - isStopped : boolean - - name : String - - queue : MqPublishPoint - + Producer(name : String, queue : MqPublishPoint) - + send(body : String) - + stop() - } - class SimpleMessage { - - body : String - - headers : Map - + SimpleMessage() - + addHeader(header : Headers, value : String) - + getBody() : String - + getHeader(header : Headers) : String - + getHeaders() : Map - + setBody(body : String) - } - class SimpleMessageQueue { - - queue : BlockingQueue - + SimpleMessageQueue(bound : int) - + put(msg : Message) - + take() : Message - } -} -SimpleMessageQueue --> "-queue" Message -Consumer --> "-queue" MqSubscribePoint -Headers ..+ Message -Producer --> "-queue" MqPublishPoint -Message --> "-POISON_PILL" Message -MessageQueue --|> MqPublishPoint -MessageQueue --|> MqSubscribePoint -SimpleMessage ..|> Message -SimpleMessageQueue ..|> MessageQueue -@enduml \ No newline at end of file diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index 8c0935310..5b9d48126 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT poison-pill - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java index 8c15bcf0f..0bef8bfee 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.poison.pill; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java index 17bd4f89e..93b5f91e1 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java @@ -25,16 +25,16 @@ package com.iluwatar.poison.pill; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/27/15 - 9:45 PM @@ -45,12 +45,12 @@ public class ConsumerTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Consumer.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java index b15005695..334c49809 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java @@ -22,10 +22,11 @@ */ package com.iluwatar.poison.pill; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.iluwatar.poison.pill.Message.Headers; import static com.iluwatar.poison.pill.Message.POISON_PILL; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Date: 12/27/15 - 10:30 PM @@ -34,29 +35,39 @@ import static com.iluwatar.poison.pill.Message.POISON_PILL; */ public class PoisonMessageTest { - @Test(expected = UnsupportedOperationException.class) + @Test public void testAddHeader() throws Exception { - POISON_PILL.addHeader(Headers.SENDER, "sender"); + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.addHeader(Headers.SENDER, "sender"); + }); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testGetHeader() throws Exception { - POISON_PILL.getHeader(Headers.SENDER); + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getHeader(Headers.SENDER); + }); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testGetHeaders() throws Exception { - POISON_PILL.getHeaders(); + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getHeaders(); + }); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testSetBody() throws Exception { - POISON_PILL.setBody("Test message."); + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.setBody("Test message."); + }); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testGetBody() throws Exception { - POISON_PILL.getBody(); + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getBody(); + }); } } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java index 7b5982a3d..5d7420ecf 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java @@ -22,12 +22,12 @@ */ package com.iluwatar.poison.pill; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java index 2b0b3bd17..20f9287f4 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java @@ -22,14 +22,15 @@ */ package com.iluwatar.poison.pill; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/27/15 - 10:25 PM @@ -51,11 +52,13 @@ public class SimpleMessageTest { assertEquals(senderName, message.getHeaders().get(Message.Headers.SENDER)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testUnModifiableHeaders() { final SimpleMessage message = new SimpleMessage(); final Map headers = message.getHeaders(); - headers.put(Message.Headers.SENDER, "test"); + assertThrows(UnsupportedOperationException.class, () -> { + headers.put(Message.Headers.SENDER, "test"); + }); } diff --git a/pom.xml b/pom.xml index ed9981b34..66c5fa850 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 4.0.0 com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT pom 2014 @@ -32,17 +32,18 @@ 1.9.2.RELEASE 1.4.190 4.12 + 5.0.2 + ${junit.version}.2 + 1.0.2 + 1.0.2 3.0 0.7.2.201409121644 1.4 2.16.1 19.0 - 1.15.1 1.10.19 - 4.12.1 4.5.2 2.22 - 1.4.4 4.0 3.3.0 1.7.21 @@ -145,10 +146,23 @@ cqrs event-sourcing data-transfer-object - throttling + throttling + + unit-of-work partial-response + eip-wire-tap + eip-splitter + eip-aggregator + retry + + + jitpack.io + https://jitpack.io + + + @@ -161,11 +175,6 @@ hibernate-entitymanager ${hibernate.version} - - org.springframework - spring-test - ${spring.version} - org.springframework.boot spring-boot-dependencies @@ -213,12 +222,48 @@ camel-stream ${camel.version} + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + junit junit ${junit.version} test + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-migrationsupport + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-vintage.version} + test + + + com.github.sbrannen + spring-test-junit5 + ${sping-test-junit5.version} + test + org.mockito mockito-core @@ -230,18 +275,6 @@ guava ${guava.version} - - com.github.stefanbirkner - system-rules - ${systemrules.version} - test - - - de.bechte.junit - junit-hierarchicalcontextrunner - ${hierarchical-junit-runner-version} - test - net.sourceforge.htmlunit htmlunit @@ -309,25 +342,6 @@ - - - - com.github.markusmo3.urm - - - urm-maven-plugin - - - [1.4.1,) - - - map - - - - - - @@ -388,12 +402,12 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18.1 + 2.19.1 - org.apache.maven.surefire - surefire-junit47 - 2.18.1 + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} @@ -442,43 +456,6 @@ - - - com.github.markusmo3.urm - urm-maven-plugin - ${urm.version} - - - process-classes - - map - - - - - ${project.basedir}/etc - - com.iluwatar - - - - java-design-patterns - singleton - factory-method - abstract-factory - builder - prototype - adapter - bridge - composite - decorator - facade - flyweight - proxy - chain - - - diff --git a/private-class-data/README.md b/private-class-data/README.md index 061cc9e77..981208fa3 100644 --- a/private-class-data/README.md +++ b/private-class-data/README.md @@ -3,7 +3,6 @@ layout: pattern title: Private Class Data folder: private-class-data permalink: /patterns/private-class-data/ -pumlid: RShR3SCm243HLTe1RFwx3S4eeSB4uf6itmpGlwkZ-nOZhS7b-ZeoLtm07E--InwrLR3JQScMdSu9edLZeiCNBso3GtPh2pFPBM1YF07BvSBaHeeHRJm_SD8VxkMphvhw0m00 categories: Other tags: - Java diff --git a/private-class-data/etc/private-class-data.urm.puml b/private-class-data/etc/private-class-data.urm.puml deleted file mode 100644 index 990b53342..000000000 --- a/private-class-data/etc/private-class-data.urm.puml +++ /dev/null @@ -1,36 +0,0 @@ -@startuml -package com.iluwatar.privateclassdata { - class App { - + App() - + main(args : String[]) {static} - } - class ImmutableStew { - - LOGGER : Logger {static} - - data : StewData - + ImmutableStew(numPotatoes : int, numCarrots : int, numMeat : int, numPeppers : int) - + mix() - } - class Stew { - - LOGGER : Logger {static} - - numCarrots : int - - numMeat : int - - numPeppers : int - - numPotatoes : int - + Stew(numPotatoes : int, numCarrots : int, numMeat : int, numPeppers : int) - + mix() - + taste() - } - class StewData { - - numCarrots : int - - numMeat : int - - numPeppers : int - - numPotatoes : int - + StewData(numPotatoes : int, numCarrots : int, numMeat : int, numPeppers : int) - + getNumCarrots() : int - + getNumMeat() : int - + getNumPeppers() : int - + getNumPotatoes() : int - } -} -ImmutableStew --> "-data" StewData -@enduml \ No newline at end of file diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml index 98a60c3c7..ddf9cef28 100644 --- a/private-class-data/pom.xml +++ b/private-class-data/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT private-class-data - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java index ef80e87cb..efd387d75 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.privateclassdata; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java index 6e337e584..aac2d6ac4 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java @@ -23,11 +23,11 @@ package com.iluwatar.privateclassdata; import com.iluwatar.privateclassdata.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 10:46 PM @@ -38,12 +38,12 @@ public class ImmutableStewTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java index 6ac5b834f..3345a1db2 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java @@ -23,11 +23,11 @@ package com.iluwatar.privateclassdata; import com.iluwatar.privateclassdata.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 10:46 PM @@ -38,12 +38,12 @@ public class StewTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/producer-consumer/README.md b/producer-consumer/README.md index b3cb56af1..1bb84c35f 100644 --- a/producer-consumer/README.md +++ b/producer-consumer/README.md @@ -3,7 +3,6 @@ layout: pattern title: Producer Consumer folder: producer-consumer permalink: /patterns/producer-consumer/ -pumlid: PSjB3iCW303HgxG70Ezx6zTO2HKso9_a-c7VtUX9y-vA8nkdZTSPiVm3O7ZNeyUPttGscXgiKMaAz94t1XhyyCBIsFkXPM44cpe8-WvODbiIMzcdfspXe7-jQL9NodW0 categories: Concurrency tags: - Java diff --git a/producer-consumer/etc/producer-consumer.urm.puml b/producer-consumer/etc/producer-consumer.urm.puml deleted file mode 100644 index 05539a55e..000000000 --- a/producer-consumer/etc/producer-consumer.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package com.iluwatar.producer.consumer { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Consumer { - - LOGGER : Logger {static} - - name : String - - queue : ItemQueue - + Consumer(name : String, queue : ItemQueue) - + consume() - } - class Item { - - id : int - - producer : String - + Item(producer : String, id : int) - + getId() : int - + getProducer() : String - } - class ItemQueue { - - queue : BlockingQueue - + ItemQueue() - + put(item : Item) - + take() : Item - } - class Producer { - - itemId : int - - name : String - - queue : ItemQueue - + Producer(name : String, queue : ItemQueue) - + produce() - } -} -Consumer --> "-queue" ItemQueue -Producer --> "-queue" ItemQueue -ItemQueue --> "-queue" Item -@enduml \ No newline at end of file diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml index 2680a973e..ea9734518 100644 --- a/producer-consumer/pom.xml +++ b/producer-consumer/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT producer-consumer - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java index e7f7870f7..bae8ba635 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.producer.consumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java index 4c110cad2..114b39255 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java @@ -22,9 +22,12 @@ */ package com.iluwatar.producer.consumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * Date: 12/27/15 - 11:01 PM diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java index 5f756c938..c8fe60e09 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java @@ -22,8 +22,10 @@ */ package com.iluwatar.producer.consumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -36,15 +38,17 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class ProducerTest { - @Test(timeout = 6000) + @Test public void testProduce() throws Exception { - final ItemQueue queue = mock(ItemQueue.class); - final Producer producer = new Producer("producer", queue); + assertTimeout(ofMillis(6000), () -> { + final ItemQueue queue = mock(ItemQueue.class); + final Producer producer = new Producer("producer", queue); - producer.produce(); - verify(queue).put(any(Item.class)); + producer.produce(); + verify(queue).put(any(Item.class)); - verifyNoMoreInteractions(queue); + verifyNoMoreInteractions(queue); + }); } } \ No newline at end of file diff --git a/promise/README.md b/promise/README.md index 37fd214b7..fa9556547 100644 --- a/promise/README.md +++ b/promise/README.md @@ -3,7 +3,6 @@ layout: pattern title: Promise folder: promise permalink: /patterns/promise/ -pumlid: DOqv4i8m301xNW4FYDLJvIl2rYHYBDcZWtmVKr3jDZkxUw15IhyzM6lFHcdzVaPCVm8ONkNWEFELJbQ71ccKEWIuvuKhXJT-S6laVEWsCO9C7GHz2KmRmav0KVzUqgJCtsydROjV categories: Concurrency tags: - Java diff --git a/promise/etc/promise.urm.puml b/promise/etc/promise.urm.puml deleted file mode 100644 index 8aabc1d2a..000000000 --- a/promise/etc/promise.urm.puml +++ /dev/null @@ -1,79 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.promise { - class App { - - DEFAULT_URL : String {static} - - LOGGER : Logger {static} - - executor : ExecutorService - - stopLatch : CountDownLatch - - App() - - calculateLineCount() - - calculateLowestFrequencyChar() - - characterFrequency() : Promise> - - countLines() : Promise - - download(urlString : String) : Promise - - lowestFrequencyChar() : Promise - + main(args : String[]) {static} - - promiseUsage() - - stop() - - taskCompleted() - } - class Promise { - - exceptionHandler : Consumer - - fulfillmentAction : Runnable - + Promise() - + fulfill(value : T) - + fulfillExceptionally(exception : Exception) - + fulfillInAsync(task : Callable, executor : Executor) : Promise - - handleException(exception : Exception) - + onError(exceptionHandler : Consumer) : Promise - - postFulfillment() - + thenAccept(action : Consumer) : Promise - + thenApply(func : Function) : Promise - } - -class ConsumeAction { - - action : Consumer - - dest : Promise - - src : Promise - - ConsumeAction(src : Promise, dest : Promise, action : Consumer) - + run() - } - -class TransformAction { - - dest : Promise - - func : Function - - src : Promise - - TransformAction(src : Promise, dest : Promise, func : Function) - + run() - } - ~class PromiseSupport { - - COMPLETED : int {static} - - FAILED : int {static} - - RUNNING : int {static} - - exception : Exception - - lock : Object - - state : int - - value : T - ~ PromiseSupport() - + cancel(mayInterruptIfRunning : boolean) : boolean - ~ fulfill(value : T) - ~ fulfillExceptionally(exception : Exception) - + get() : T - + get(timeout : long, unit : TimeUnit) : T - + isCancelled() : boolean - + isDone() : boolean - } - class Utility { - - LOGGER : Logger {static} - + Utility() - + characterFrequency(fileLocation : String) : Map {static} - + countLines(fileLocation : String) : Integer {static} - + downloadFile(urlString : String) : String {static} - + lowestFrequencyChar(charFrequency : Map) : Character {static} - } -} -TransformAction --+ Promise -TransformAction --> "-src" Promise -ConsumeAction --+ Promise -ConsumeAction --> "-src" Promise -Promise --|> PromiseSupport -@enduml diff --git a/promise/pom.xml b/promise/pom.xml index 3753e4c25..9b600d5fb 100644 --- a/promise/pom.xml +++ b/promise/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT promise - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java index df4d0cc79..dd40ec15b 100644 --- a/promise/src/main/java/com/iluwatar/promise/App.java +++ b/promise/src/main/java/com/iluwatar/promise/App.java @@ -65,7 +65,7 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/Promise/promise/README.md"; + private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md"; private final ExecutorService executor; private final CountDownLatch stopLatch; diff --git a/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java b/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java index 3629b4b5d..ae90a927e 100644 --- a/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java +++ b/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java @@ -27,11 +27,16 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A really simplified implementation of future that allows completing it successfully with a value * or exceptionally with an exception. */ class PromiseSupport implements Future { + + private static final Logger LOGGER = LoggerFactory.getLogger(PromiseSupport.class); private static final int RUNNING = 1; private static final int FAILED = 2; @@ -80,40 +85,34 @@ class PromiseSupport implements Future { @Override public T get() throws InterruptedException, ExecutionException { - if (state == COMPLETED) { - return value; - } else if (state == FAILED) { - throw new ExecutionException(exception); - } else { - synchronized (lock) { + synchronized (lock) { + while (state == RUNNING) { lock.wait(); - if (state == COMPLETED) { - return value; - } else { - throw new ExecutionException(exception); - } } } + if (state == COMPLETED) { + return value; + } + throw new ExecutionException(exception); } @Override public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - if (state == COMPLETED) { - return value; - } else if (state == FAILED) { - throw new ExecutionException(exception); - } else { - synchronized (lock) { - lock.wait(unit.toMillis(timeout)); - if (state == COMPLETED) { - return value; - } else if (state == FAILED) { - throw new ExecutionException(exception); - } else { - throw new TimeoutException(); + throws ExecutionException, TimeoutException { + synchronized (lock) { + while (state == RUNNING) { + try { + lock.wait(unit.toMillis(timeout)); + } catch (InterruptedException e) { + LOGGER.warn("Interrupted!", e); + Thread.currentThread().interrupt(); } } } + + if (state == COMPLETED) { + return value; + } + throw new ExecutionException(exception); } } \ No newline at end of file diff --git a/promise/src/test/java/com/iluwatar/promise/AppTest.java b/promise/src/test/java/com/iluwatar/promise/AppTest.java index f7df415e8..eb8790a4a 100644 --- a/promise/src/test/java/com/iluwatar/promise/AppTest.java +++ b/promise/src/test/java/com/iluwatar/promise/AppTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.promise; -import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.util.concurrent.ExecutionException; /** * diff --git a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java index 6e17b9794..68868bd1e 100644 --- a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java +++ b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java @@ -22,13 +22,8 @@ */ package com.iluwatar.promise; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -39,10 +34,14 @@ import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + /** * Tests Promise class. */ @@ -50,9 +49,8 @@ public class PromiseTest { private Executor executor; private Promise promise; - @Rule public ExpectedException exception = ExpectedException.none(); - @Before + @BeforeEach public void setUp() { executor = Executors.newSingleThreadExecutor(); promise = new Promise<>(); diff --git a/property/README.md b/property/README.md index c1502f75c..0ac5c7a6c 100644 --- a/property/README.md +++ b/property/README.md @@ -3,7 +3,6 @@ layout: pattern title: Property folder: property permalink: /patterns/property/ -pumlid: FSV13OCm30NGLTe1YEziumOBKYMEPN-3s9wUUdlltRJst2Izlmx0OYLolihUSEGdGxnEXIXAdODQpul1Jby-UTaasgwBCI2kGOFZ1pAV9ewR1FMVaZwAvUWF categories: Creational tags: - Java diff --git a/property/etc/property.urm.puml b/property/etc/property.urm.puml deleted file mode 100644 index f281cd873..000000000 --- a/property/etc/property.urm.puml +++ /dev/null @@ -1,54 +0,0 @@ -@startuml -package com.iluwatar.property { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Character { - - name : String - - properties : Map - - prototype : Prototype - - type : Type - + Character() - + Character(name : String, prototype : Character) - + Character(type : Type, prototype : Prototype) - + get(stat : Stats) : Integer - + has(stat : Stats) : boolean - + name() : String - + remove(stat : Stats) - + set(stat : Stats, val : Integer) - + toString() : String - + type() : Type - } - enum Type { - + MAGE {static} - + ROGUE {static} - + WARRIOR {static} - + valueOf(name : String) : Type {static} - + values() : Type[] {static} - } - interface Prototype { - + get(Stats) : Integer {abstract} - + has(Stats) : boolean {abstract} - + remove(Stats) {abstract} - + set(Stats, Integer) {abstract} - } - enum Stats { - + AGILITY {static} - + ARMOR {static} - + ATTACK_POWER {static} - + ENERGY {static} - + INTELLECT {static} - + RAGE {static} - + SPIRIT {static} - + STRENGTH {static} - + valueOf(name : String) : Stats {static} - + values() : Stats[] {static} - } -} -Character --> "-prototype" Prototype -Type ..+ Character -Character --> "-type" Type -Character ..|> Prototype -@enduml \ No newline at end of file diff --git a/property/pom.xml b/property/pom.xml index 8b5d25c87..b3bc915e9 100644 --- a/property/pom.xml +++ b/property/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT property - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/property/src/test/java/com/iluwatar/property/AppTest.java b/property/src/test/java/com/iluwatar/property/AppTest.java index 08e0dbba1..4bc0beba4 100644 --- a/property/src/test/java/com/iluwatar/property/AppTest.java +++ b/property/src/test/java/com/iluwatar/property/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.property; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/property/src/test/java/com/iluwatar/property/CharacterTest.java b/property/src/test/java/com/iluwatar/property/CharacterTest.java index 5dc996f4d..95a66a2fb 100644 --- a/property/src/test/java/com/iluwatar/property/CharacterTest.java +++ b/property/src/test/java/com/iluwatar/property/CharacterTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.property; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.iluwatar.property.Character.Type; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/28/15 - 7:46 PM diff --git a/prototype/README.md b/prototype/README.md index 477cd6e6f..4bfeebe19 100644 --- a/prototype/README.md +++ b/prototype/README.md @@ -3,7 +3,6 @@ layout: pattern title: Prototype folder: prototype permalink: /patterns/prototype/ -pumlid: HSV13OCm30NGLM00udktCS62eCInxE-YRj_UUdjlRLfx7fBUbmkmU14vF-Lik7BF4AzJ8OfIvw3Mys6mqyrltWw9Tkfc38XhqE3uWSmd9Zuc9AZ_bVHHB4V_0W00 categories: Creational tags: - Java diff --git a/prototype/pom.xml b/prototype/pom.xml index de3571a77..54c9ac987 100644 --- a/prototype/pom.xml +++ b/prototype/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT prototype - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index dfebdab17..0a5531b24 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -52,7 +52,7 @@ public class App { Warlord warlord; Beast beast; - factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast()); + factory = new HeroFactoryImpl(new ElfMage("cooking"), new ElfWarlord("cleaning"), new ElfBeast("protecting")); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); @@ -60,7 +60,7 @@ public class App { LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); - factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast()); + factory = new HeroFactoryImpl(new OrcMage("axe"), new OrcWarlord("sword"), new OrcBeast("laser")); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java index fc81ac4e6..e2fe9823a 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java @@ -30,6 +30,6 @@ package com.iluwatar.prototype; public abstract class Beast extends Prototype { @Override - public abstract Beast clone() throws CloneNotSupportedException; + public abstract Beast copy() throws CloneNotSupportedException; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java index 11783611e..ec90b14b2 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java @@ -28,17 +28,25 @@ package com.iluwatar.prototype; * */ public class ElfBeast extends Beast { + + private String helpType; - public ElfBeast() {} + public ElfBeast(String helpType) { + this.helpType = helpType; + } + + public ElfBeast(ElfBeast elfBeast) { + this.helpType = elfBeast.helpType; + } @Override - public Beast clone() throws CloneNotSupportedException { - return new ElfBeast(); + public Beast copy() throws CloneNotSupportedException { + return new ElfBeast(this); } @Override public String toString() { - return "Elven eagle"; + return "Elven eagle helps in " + helpType; } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java index 5ddefcdf5..7a3e22b12 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java @@ -29,16 +29,25 @@ package com.iluwatar.prototype; */ public class ElfMage extends Mage { - public ElfMage() {} + + private String helpType; + + public ElfMage(String helpType) { + this.helpType = helpType; + } + + public ElfMage(ElfMage elfMage) { + this.helpType = elfMage.helpType; + } @Override - public Mage clone() throws CloneNotSupportedException { - return new ElfMage(); + public ElfMage copy() throws CloneNotSupportedException { + return new ElfMage(this); } @Override public String toString() { - return "Elven mage"; + return "Elven mage helps in " + helpType; } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java index d0dfde1db..f4aa42012 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java @@ -29,16 +29,24 @@ package com.iluwatar.prototype; */ public class ElfWarlord extends Warlord { - public ElfWarlord() {} + private String helpType; + + public ElfWarlord(String helpType) { + this.helpType = helpType; + } + + public ElfWarlord(ElfWarlord elfWarlord) { + this.helpType = elfWarlord.helpType; + } @Override - public Warlord clone() throws CloneNotSupportedException { - return new ElfWarlord(); + public ElfWarlord copy() throws CloneNotSupportedException { + return new ElfWarlord(this); } @Override public String toString() { - return "Elven warlord"; + return "Elven warlord helps in " + helpType; } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java index 4f05bb843..4e09eee6d 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java @@ -47,7 +47,7 @@ public class HeroFactoryImpl implements HeroFactory { */ public Mage createMage() { try { - return mage.clone(); + return mage.copy(); } catch (CloneNotSupportedException e) { return null; } @@ -58,7 +58,7 @@ public class HeroFactoryImpl implements HeroFactory { */ public Warlord createWarlord() { try { - return warlord.clone(); + return warlord.copy(); } catch (CloneNotSupportedException e) { return null; } @@ -69,7 +69,7 @@ public class HeroFactoryImpl implements HeroFactory { */ public Beast createBeast() { try { - return beast.clone(); + return beast.copy(); } catch (CloneNotSupportedException e) { return null; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java index 361b586b2..88341fbde 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java @@ -30,6 +30,6 @@ package com.iluwatar.prototype; public abstract class Mage extends Prototype { @Override - public abstract Mage clone() throws CloneNotSupportedException; + public abstract Mage copy() throws CloneNotSupportedException; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java index 212888fb4..07a19f970 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java @@ -28,17 +28,26 @@ package com.iluwatar.prototype; * */ public class OrcBeast extends Beast { + + private String weapon; - public OrcBeast() {} + public OrcBeast(String weapon) { + this.weapon = weapon; + } + + public OrcBeast(OrcBeast orcBeast) { + this.weapon = orcBeast.weapon; + } @Override - public Beast clone() throws CloneNotSupportedException { - return new OrcBeast(); + public Beast copy() throws CloneNotSupportedException { + return new OrcBeast(this); } @Override public String toString() { - return "Orcish wolf"; + return "Orcish wolf attacks with " + weapon; } + } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java index c15143bbb..e662dd44b 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java @@ -29,16 +29,24 @@ package com.iluwatar.prototype; */ public class OrcMage extends Mage { - public OrcMage() {} + private String weapon; + + public OrcMage(String weapon) { + this.weapon = weapon; + } + + public OrcMage(OrcMage orcMage) { + this.weapon = orcMage.weapon; + } @Override - public Mage clone() throws CloneNotSupportedException { - return new OrcMage(); + public OrcMage copy() throws CloneNotSupportedException { + return new OrcMage(this); } @Override public String toString() { - return "Orcish mage"; + return "Orcish mage attacks with " + weapon; } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java index e9f7c6cd4..697ec0b7e 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java @@ -29,16 +29,24 @@ package com.iluwatar.prototype; */ public class OrcWarlord extends Warlord { - public OrcWarlord() {} + private String weapon; + + public OrcWarlord(String weapon) { + this.weapon = weapon; + } + + public OrcWarlord(OrcWarlord orcWarlord) { + this.weapon = orcWarlord.weapon; + } @Override - public Warlord clone() throws CloneNotSupportedException { - return new OrcWarlord(); + public OrcWarlord copy() throws CloneNotSupportedException { + return new OrcWarlord(this); } @Override public String toString() { - return "Orcish warlord"; + return "Orcish warlord attacks with " + weapon; } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java index 10d8b66eb..2049ddc3b 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java @@ -29,7 +29,6 @@ package com.iluwatar.prototype; */ public abstract class Prototype implements Cloneable { - @Override - public abstract Object clone() throws CloneNotSupportedException; + public abstract Object copy() throws CloneNotSupportedException; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java index aef8676f4..da4a944d4 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java @@ -30,6 +30,6 @@ package com.iluwatar.prototype; public abstract class Warlord extends Prototype { @Override - public abstract Warlord clone() throws CloneNotSupportedException; + public abstract Warlord copy() throws CloneNotSupportedException; } diff --git a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java index 48c70429a..e7a8c81ae 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.prototype; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java b/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java index bee05bc5e..33c84cfa9 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.prototype; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -43,18 +43,18 @@ public class HeroFactoryImplTest { final Warlord warlord = mock(Warlord.class); final Beast beast = mock(Beast.class); - when(mage.clone()).thenThrow(CloneNotSupportedException.class); - when(warlord.clone()).thenThrow(CloneNotSupportedException.class); - when(beast.clone()).thenThrow(CloneNotSupportedException.class); + when(mage.copy()).thenThrow(CloneNotSupportedException.class); + when(warlord.copy()).thenThrow(CloneNotSupportedException.class); + when(beast.copy()).thenThrow(CloneNotSupportedException.class); final HeroFactoryImpl factory = new HeroFactoryImpl(mage, warlord, beast); assertNull(factory.createMage()); assertNull(factory.createWarlord()); assertNull(factory.createBeast()); - verify(mage).clone(); - verify(warlord).clone(); - verify(beast).clone(); + verify(mage).copy(); + verify(warlord).copy(); + verify(beast).copy(); verifyNoMoreInteractions(mage, warlord, beast); } diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java index add5617b1..c55369935 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -22,66 +22,43 @@ */ package com.iluwatar.prototype; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/28/15 - 8:45 PM * @param

Prototype * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class PrototypeTest

{ - - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { return Arrays.asList( - new Object[]{new OrcBeast(), "Orcish wolf"}, - new Object[]{new OrcMage(), "Orcish mage"}, - new Object[]{new OrcWarlord(), "Orcish warlord"}, - new Object[]{new ElfBeast(), "Elven eagle"}, - new Object[]{new ElfMage(), "Elven mage"}, - new Object[]{new ElfWarlord(), "Elven warlord"} + new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"}, + new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"}, + new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, + new Object[]{new ElfBeast("cooking"), "Elven eagle helps in cooking"}, + new Object[]{new ElfMage("cleaning"), "Elven mage helps in cleaning"}, + new Object[]{new ElfWarlord("protecting"), "Elven warlord helps in protecting"} ); } - /** - * The tested prototype instance - */ - private final Prototype testedPrototype; + @ParameterizedTest + @MethodSource("dataProvider") + public void testPrototype(P testedPrototype, String expectedToString) throws Exception { + assertEquals(expectedToString, testedPrototype.toString()); - /** - * The expected {@link Prototype#toString()} value - */ - private final String expectedToString; - - /** - * Create a new test instance, using the given test object and expected value - * - * @param testedPrototype The tested prototype instance - * @param expectedToString The expected {@link Prototype#toString()} value - */ - public PrototypeTest(final Prototype testedPrototype, final String expectedToString) { - this.expectedToString = expectedToString; - this.testedPrototype = testedPrototype; - } - - @Test - public void testPrototype() throws Exception { - assertEquals(this.expectedToString, this.testedPrototype.toString()); - - final Object clone = this.testedPrototype.clone(); + final Object clone = testedPrototype.copy(); assertNotNull(clone); - assertNotSame(clone, this.testedPrototype); - assertSame(this.testedPrototype.getClass(), clone.getClass()); + assertNotSame(clone, testedPrototype); + assertSame(testedPrototype.getClass(), clone.getClass()); } } diff --git a/proxy/README.md b/proxy/README.md index 615c02ced..80593c75e 100644 --- a/proxy/README.md +++ b/proxy/README.md @@ -3,7 +3,6 @@ layout: pattern title: Proxy folder: proxy permalink: /patterns/proxy/ -pumlid: 9SR13OCm30NGLM00udktCS62eCI9x6yesrEfx_Jcehd69c5rEe3X7oBZE-q5HwpXOhahH95oRrHgt0msEldYPHClkow30J5rQko_qB3-VKYG_qjXBOrezGK0 categories: Structural tags: - Java diff --git a/proxy/pom.xml b/proxy/pom.xml index b81611fa4..31e87c04b 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT proxy - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java index d22d9c4bd..45bb38adc 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.proxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java index 944193a0a..728223fa9 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java @@ -23,14 +23,12 @@ package com.iluwatar.proxy; import com.iluwatar.proxy.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link IvoryTower} @@ -39,12 +37,12 @@ public class IvoryTowerTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(IvoryTower.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java index ce5637214..f6bbe4a2d 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.proxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link Wizard} diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java index 2958376d6..b8c6c9ff5 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -23,12 +23,12 @@ package com.iluwatar.proxy; import com.iluwatar.proxy.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link WizardTowerProxy} @@ -37,12 +37,12 @@ public class WizardTowerProxyTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/publish-subscribe/etc/publish-subscribe.urm.puml b/publish-subscribe/etc/publish-subscribe.urm.puml deleted file mode 100644 index 2e511c92d..000000000 --- a/publish-subscribe/etc/publish-subscribe.urm.puml +++ /dev/null @@ -1,9 +0,0 @@ -@startuml -package com.iluwatar.publish.subscribe { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } -} -@enduml \ No newline at end of file diff --git a/publish-subscribe/pom.xml b/publish-subscribe/pom.xml index c9a55a3ff..688cda903 100644 --- a/publish-subscribe/pom.xml +++ b/publish-subscribe/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT publish-subscribe @@ -41,8 +41,14 @@ camel-stream - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test \ No newline at end of file diff --git a/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java b/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java index 216ba49f0..128385faf 100644 --- a/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java +++ b/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.publish.subscribe; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/queue-load-leveling/README.md b/queue-load-leveling/README.md index ca73ac34a..13821a54e 100644 --- a/queue-load-leveling/README.md +++ b/queue-load-leveling/README.md @@ -3,7 +3,6 @@ layout: pattern title: Queue based load leveling folder: queue-load-leveling permalink: /patterns/queue-load-leveling/ -pumlid: ROux3W8n30LxJW47IDnJxLLCOcM376VnP_VwX9xgZKOQwMtcg1w3RuykXQDIADztzyEU08fNRjttU8MHbYbEuhdC0PtZmfN26qzCbQmtIGUwauh1G5i0dw2Wn1DhOZg9kpGWB_zy3Xtv-FtOIEhQBm00 categories: Other tags: - Java diff --git a/queue-load-leveling/etc/queue-load-leveling.urm.puml b/queue-load-leveling/etc/queue-load-leveling.urm.puml deleted file mode 100644 index ca90842d9..000000000 --- a/queue-load-leveling/etc/queue-load-leveling.urm.puml +++ /dev/null @@ -1,44 +0,0 @@ -@startuml -package com.iluwatar.queue.load.leveling { - class App { - - LOGGER : Logger {static} - - SHUTDOWN_TIME : int {static} - + App() - + main(args : String[]) {static} - } - class Message { - - msg : String - + Message(msg : String) - + getMsg() : String - + toString() : String - } - class MessageQueue { - - LOGGER : Logger {static} - - blkQueue : BlockingQueue - + MessageQueue() - + retrieveMsg() : Message - + submitMsg(msg : Message) - } - class ServiceExecutor { - - LOGGER : Logger {static} - - msgQueue : MessageQueue - + ServiceExecutor(msgQueue : MessageQueue) - + run() - } - interface Task { - + submit(Message) {abstract} - } - class TaskGenerator { - - LOGGER : Logger {static} - - msgCount : int - - msgQueue : MessageQueue - + TaskGenerator(msgQueue : MessageQueue, msgCount : int) - + run() - + submit(msg : Message) - } -} -MessageQueue --> "-blkQueue" Message -ServiceExecutor --> "-msgQueue" MessageQueue -TaskGenerator --> "-msgQueue" MessageQueue -TaskGenerator ..|> Task -@enduml \ No newline at end of file diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml index 0841357b3..681409e96 100644 --- a/queue-load-leveling/pom.xml +++ b/queue-load-leveling/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT queue-load-leveling - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java index fc218c875..1bfc3fe35 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java @@ -31,7 +31,6 @@ public class Message { // Parameter constructor. public Message(String msg) { - super(); this.msg = msg; } diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java index d1cf75ca8..820062574 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.queue.load.leveling; -import java.io.IOException; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.IOException; /** * Application Test diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java index 30b5d7ce0..13a1db706 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.queue.load.leveling; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java index 93ef723ea..d6b0167cf 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -22,8 +22,9 @@ */ package com.iluwatar.queue.load.leveling; -import org.junit.Test; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java index a773c377e..12fb4bf33 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.queue.load.leveling; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/reactor/README.md b/reactor/README.md index 68461cfdd..ba96f9c68 100644 --- a/reactor/README.md +++ b/reactor/README.md @@ -3,7 +3,6 @@ layout: pattern title: Reactor folder: reactor permalink: /patterns/reactor/ -pumlid: DSR14OGm20NGLjO23FVj1f7Hx2Ga0nzjVxtuJc-f9YrtJM-V4vZn9NA-or5nvfQXBiEWXYAZKsrvCzZfnnUlkqOzR9qCg5jGvtX2hYmOJWfvNz9xcTdR7m00 pumlformat: svg categories: Concurrency tags: diff --git a/reactor/etc/reactor.urm.puml b/reactor/etc/reactor.urm.puml deleted file mode 100644 index 1ce92cab2..000000000 --- a/reactor/etc/reactor.urm.puml +++ /dev/null @@ -1,156 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.reactor.framework { - abstract class AbstractNioChannel { - - channel : SelectableChannel - - channelToPendingWrites : Map> - - handler : ChannelHandler - - reactor : NioReactor - + AbstractNioChannel(handler : ChannelHandler, channel : SelectableChannel) - + bind() {abstract} - # doWrite(Object, SelectionKey) {abstract} - ~ flush(key : SelectionKey) - + getHandler() : ChannelHandler - + getInterestedOps() : int {abstract} - + getJavaChannel() : SelectableChannel - + read(SelectionKey) : Object {abstract} - ~ setReactor(reactor : NioReactor) - + write(data : Object, key : SelectionKey) - } - interface ChannelHandler { - + handleChannelRead(AbstractNioChannel, Object, SelectionKey) {abstract} - } - interface Dispatcher { - + onChannelReadEvent(AbstractNioChannel, Object, SelectionKey) {abstract} - + stop() {abstract} - } - class NioDatagramChannel { - - LOGGER : Logger {static} - - port : int - + NioDatagramChannel(port : int, handler : ChannelHandler) - + bind() - # doWrite(pendingWrite : Object, key : SelectionKey) - + getInterestedOps() : int - + getJavaChannel() : DatagramChannel - + read(key : SelectionKey) : DatagramPacket - + write(data : Object, key : SelectionKey) - } - class DatagramPacket { - - data : ByteBuffer - - receiver : SocketAddress - - sender : SocketAddress - + DatagramPacket(data : ByteBuffer) - + getData() : ByteBuffer - + getReceiver() : SocketAddress - + getSender() : SocketAddress - + setReceiver(receiver : SocketAddress) - + setSender(sender : SocketAddress) - } - class NioReactor { - - LOGGER : Logger {static} - - dispatcher : Dispatcher - - pendingCommands : Queue - - reactorMain : ExecutorService - - selector : Selector - + NioReactor(dispatcher : Dispatcher) - + changeOps(key : SelectionKey, interestedOps : int) - - dispatchReadEvent(key : SelectionKey, readObject : Object) - - eventLoop() - - onChannelAcceptable(key : SelectionKey) - - onChannelReadable(key : SelectionKey) - - onChannelWritable(key : SelectionKey) {static} - - processKey(key : SelectionKey) - - processPendingCommands() - + registerChannel(channel : AbstractNioChannel) : NioReactor - + start() - + stop() - } - ~class ChangeKeyOpsCommand { - - interestedOps : int - - key : SelectionKey - + ChangeKeyOpsCommand(this$0 : SelectionKey, key : int) - + run() - + toString() : String - } - class NioServerSocketChannel { - - LOGGER : Logger {static} - - port : int - + NioServerSocketChannel(port : int, handler : ChannelHandler) - + bind() - # doWrite(pendingWrite : Object, key : SelectionKey) - + getInterestedOps() : int - + getJavaChannel() : ServerSocketChannel - + read(key : SelectionKey) : ByteBuffer - } - class SameThreadDispatcher { - + SameThreadDispatcher() - + onChannelReadEvent(channel : AbstractNioChannel, readObject : Object, key : SelectionKey) - + stop() - } - class ThreadPoolDispatcher { - - executorService : ExecutorService - + ThreadPoolDispatcher(poolSize : int) - + onChannelReadEvent(channel : AbstractNioChannel, readObject : Object, key : SelectionKey) - + stop() - } -} -package com.iluwatar.reactor.app { - class App { - - channels : List - - dispatcher : Dispatcher - - reactor : NioReactor - + App(dispatcher : Dispatcher) - + main(args : String[]) {static} - + start() - + stop() - - tcpChannel(port : int, handler : ChannelHandler) : AbstractNioChannel - - udpChannel(port : int, handler : ChannelHandler) : AbstractNioChannel - } - class AppClient { - - LOGGER : Logger {static} - - service : ExecutorService - + AppClient() - - artificialDelayOf(millis : long) {static} - + main(args : String[]) {static} - + start() - + stop() - } - ~class TcpLoggingClient { - - clientName : String - - serverPort : int - + TcpLoggingClient(clientName : String, serverPort : int) - + run() - - sendLogRequests(writer : PrintWriter, inputStream : InputStream) - } - ~class UdpLoggingClient { - - clientName : String - - remoteAddress : InetSocketAddress - + UdpLoggingClient(clientName : String, port : int) - + run() - } - class LoggingHandler { - - ACK : byte[] {static} - - LOGGER : Logger {static} - + LoggingHandler() - - doLogging(data : ByteBuffer) {static} - + handleChannelRead(channel : AbstractNioChannel, readObject : Object, key : SelectionKey) - - sendReply(channel : AbstractNioChannel, incomingPacket : DatagramPacket, key : SelectionKey) {static} - - sendReply(channel : AbstractNioChannel, key : SelectionKey) {static} - } -} -AbstractNioChannel --> "-handler" ChannelHandler -UdpLoggingClient ..+ AppClient -TcpLoggingClient ..+ AppClient -AbstractNioChannel --> "-reactor" NioReactor -NioReactor --> "-dispatcher" Dispatcher -App --> "-reactor" NioReactor -App --> "-channels" AbstractNioChannel -DatagramPacket ..+ NioDatagramChannel -App --> "-dispatcher" Dispatcher -ChangeKeyOpsCommand --+ NioReactor -LoggingHandler ..|> ChannelHandler -NioDatagramChannel --|> AbstractNioChannel -NioServerSocketChannel --|> AbstractNioChannel -SameThreadDispatcher ..|> Dispatcher -ThreadPoolDispatcher ..|> Dispatcher -@enduml diff --git a/reactor/pom.xml b/reactor/pom.xml index 2a50d5934..e8a145f7b 100644 --- a/reactor/pom.xml +++ b/reactor/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT reactor - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java index 7aa80f8cc..7b45c6053 100644 --- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java +++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -22,16 +22,14 @@ */ package com.iluwatar.reactor.app; -import java.io.IOException; - -import com.iluwatar.reactor.framework.NioReactor; -import org.junit.Test; - import com.iluwatar.reactor.framework.SameThreadDispatcher; import com.iluwatar.reactor.framework.ThreadPoolDispatcher; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; + /** * * This class tests the Distributed Logging service by starting a Reactor and then sending it diff --git a/reader-writer-lock/README.md b/reader-writer-lock/README.md index 556b9cd85..40b711361 100644 --- a/reader-writer-lock/README.md +++ b/reader-writer-lock/README.md @@ -3,7 +3,6 @@ layout: pattern title: Reader Writer Lock folder: reader-writer-lock permalink: /patterns/reader-writer-lock/ -pumlid: RSZB4S8m303HLg00MtUw4R8cCP5bZpwuVL80jttxx4gIZTFaSKOiVm4OxdhqEFETpaPJWpKgpG5TScEWmGU_M1fxFxGiZ61JXu5-1nXZOolR-gqYaoxWe3-xfeswSiWF categories: Concurrency tags: - Java diff --git a/reader-writer-lock/etc/reader-writer-lock.urm.puml b/reader-writer-lock/etc/reader-writer-lock.urm.puml deleted file mode 100644 index b71cf73f6..000000000 --- a/reader-writer-lock/etc/reader-writer-lock.urm.puml +++ /dev/null @@ -1,61 +0,0 @@ -@startuml -package com.iluwatar.reader.writer.lock { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Reader { - - LOGGER : Logger {static} - - name : String - - readLock : Lock - + Reader(name : String, readLock : Lock) - + read() - + run() - } - class ReaderWriterLock { - - currentReaderCount : int - - globalMutex : Set - - readerLock : ReadLock - - readerMutex : Object - - writerLock : WriteLock - + ReaderWriterLock() - - doesReaderOwnThisLock() : boolean - - doesWriterOwnThisLock() : boolean - - isLockFree() : boolean - + readLock() : Lock - - waitUninterruptibly(o : Object) {static} - + writeLock() : Lock - } - -class ReadLock { - - ReadLock() - + lock() - + lockInterruptibly() - + newCondition() : Condition - + tryLock() : boolean - + tryLock(time : long, unit : TimeUnit) : boolean - + unlock() - } - -class WriteLock { - - WriteLock() - + lock() - + lockInterruptibly() - + newCondition() : Condition - + tryLock() : boolean - + tryLock(time : long, unit : TimeUnit) : boolean - + unlock() - } - class Writer { - - LOGGER : Logger {static} - - name : String - - writeLock : Lock - + Writer(name : String, writeLock : Lock) - + run() - + write() - } -} -ReaderWriterLock --> "-readerLock" ReadLock -ReadLock --+ ReaderWriterLock -WriteLock --+ ReaderWriterLock -ReaderWriterLock --> "-writerLock" WriteLock -@enduml \ No newline at end of file diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml index 70ff7afc9..b0dc137e4 100644 --- a/reader-writer-lock/pom.xml +++ b/reader-writer-lock/pom.xml @@ -30,13 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT reader-writer-lock - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java index fd0cd4b27..fbdf3f846 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.reader.writer.lock; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application test diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java index adc2adae2..c8de8c511 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -24,9 +24,9 @@ package com.iluwatar.reader.writer.lock; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,7 +34,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author hongshuwei@gmail.com @@ -43,12 +43,12 @@ public class ReaderAndWriterTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java index c9b3eb72c..8fe5912ea 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -23,9 +23,9 @@ package com.iluwatar.reader.writer.lock; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +33,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; /** @@ -43,12 +43,12 @@ public class ReaderTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Reader.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java index 7c4b4148d..bb01e11b0 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -23,9 +23,9 @@ package com.iluwatar.reader.writer.lock; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +33,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; /** @@ -43,12 +43,12 @@ public class WriterTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(Writer.class); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/repository/README.md b/repository/README.md index 501f39f9c..67b3ea44e 100644 --- a/repository/README.md +++ b/repository/README.md @@ -3,7 +3,6 @@ layout: pattern title: Repository folder: repository permalink: /patterns/repository/ -pumlid: JSV13OCm30NGLM00udktCS42eyI9xE-YRjyUUtjlLQij3qblomNCU14vF-LKNBbdYDTX44EfevEsV1ZiTFERjqD2Jzic0-8Mr3b-89SvGZ7yGuBwrvBUoypUlW00 categories: Persistence Tier tags: - Java diff --git a/repository/etc/repository.urm.puml b/repository/etc/repository.urm.puml deleted file mode 100644 index 10768260c..000000000 --- a/repository/etc/repository.urm.puml +++ /dev/null @@ -1,56 +0,0 @@ -@startuml -package com.iluwatar.repository { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class AppConfig { - - LOGGER : Logger {static} - + AppConfig() - + dataSource() : DataSource - + entityManagerFactory() : LocalContainerEntityManagerFactoryBean - - jpaProperties() : Properties {static} - + main(args : String[]) {static} - + transactionManager() : JpaTransactionManager - } - class Person { - - age : int - - id : Long - - name : String - - surname : String - + Person() - + Person(name : String, surname : String, age : int) - + equals(obj : Object) : boolean - + getAge() : int - + getId() : Long - + getName() : String - + getSurname() : String - + hashCode() : int - + setAge(age : int) - + setId(id : Long) - + setName(name : String) - + setSurname(surname : String) - + toString() : String - } - interface PersonRepository { - + findByName(String) : Person {abstract} - } - class PersonSpecifications { - + PersonSpecifications() - } - class AgeBetweenSpec { - - from : int - - to : int - + AgeBetweenSpec(from : int, to : int) - + toPredicate(root : Root, query : CriteriaQuery, cb : CriteriaBuilder) : Predicate - } - class NameEqualSpec { - + name : String - + NameEqualSpec(name : String) - + toPredicate(root : Root, query : CriteriaQuery, cb : CriteriaBuilder) : Predicate - } -} -NameEqualSpec ..+ PersonSpecifications -AgeBetweenSpec ..+ PersonSpecifications -@enduml \ No newline at end of file diff --git a/repository/pom.xml b/repository/pom.xml index a167dd58c..cf08ba4a5 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -29,13 +29,14 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT repository - org.springframework - spring-test + com.github.sbrannen + spring-test-junit5 + test org.springframework.data @@ -54,8 +55,13 @@ h2 - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index cb84b1ae8..4cfb6e022 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -22,21 +22,21 @@ */ package com.iluwatar.repository; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.util.Arrays; import java.util.List; import javax.annotation.Resource; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.google.common.collect.Lists; @@ -46,7 +46,7 @@ import com.google.common.collect.Lists; * by {@link org.springframework.data.jpa.domain.Specification} are also test. * */ -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) public class AnnotationBasedRepositoryTest { @@ -63,7 +63,7 @@ public class AnnotationBasedRepositoryTest { /** * Prepare data for test */ - @Before + @BeforeEach public void setup() { repository.save(persons); @@ -123,7 +123,7 @@ public class AnnotationBasedRepositoryTest { assertEquals(terry, actual); } - @After + @AfterEach public void cleanup() { repository.deleteAll(); diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index 6d6a58e8d..882d2bef7 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -22,19 +22,19 @@ */ package com.iluwatar.repository; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; @@ -42,7 +42,7 @@ import org.springframework.transaction.annotation.Transactional; * This case is Just for test the Annotation Based configuration * */ -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) public class AppConfigTest { diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java index d3f05caaa..17052b51e 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.repository; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 3201c024c..6a347ffd4 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -22,21 +22,21 @@ */ package com.iluwatar.repository; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.util.Arrays; import java.util.List; import javax.annotation.Resource; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import com.google.common.collect.Lists; @@ -44,7 +44,7 @@ import com.google.common.collect.Lists; * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query * by {@link org.springframework.data.jpa.domain.Specification} are also test. */ -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) public class RepositoryTest { @@ -61,7 +61,7 @@ public class RepositoryTest { /** * Prepare data for test */ - @Before + @BeforeEach public void setup() { repository.save(persons); @@ -121,7 +121,7 @@ public class RepositoryTest { assertEquals(terry, actual); } - @After + @AfterEach public void cleanup() { repository.deleteAll(); diff --git a/resource-acquisition-is-initialization/README.md b/resource-acquisition-is-initialization/README.md index df7ee294b..821f220d7 100644 --- a/resource-acquisition-is-initialization/README.md +++ b/resource-acquisition-is-initialization/README.md @@ -3,7 +3,6 @@ layout: pattern title: Resource Acquisition Is Initialization folder: resource-acquisition-is-initialization permalink: /patterns/resource-acquisition-is-initialization/ -pumlid: ZShR3S8m343HLUW0YV_PnhXMQvGumOzMOdhA1lqxkhgBABLSEQqzzeZfJm33isuIUxxIsMXei4QbqK5QdXXeyCO3oyekcvQ94MpgqD4lWB6FDEA2z4bn2HbQn8leHMponNy13hgvrhHUP_Rs0m00 categories: Other tags: - Java diff --git a/resource-acquisition-is-initialization/etc/resource-acquisition-is-initialization.urm.puml b/resource-acquisition-is-initialization/etc/resource-acquisition-is-initialization.urm.puml deleted file mode 100644 index 11309f0a6..000000000 --- a/resource-acquisition-is-initialization/etc/resource-acquisition-is-initialization.urm.puml +++ /dev/null @@ -1,19 +0,0 @@ -@startuml -package com.iluwatar.resource.acquisition.is.initialization { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class SlidingDoor { - - LOGGER : Logger {static} - + SlidingDoor() - + close() - } - class TreasureChest { - - LOGGER : Logger {static} - + TreasureChest() - + close() - } -} -@enduml \ No newline at end of file diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml index ae07196b7..3d68966c5 100644 --- a/resource-acquisition-is-initialization/pom.xml +++ b/resource-acquisition-is-initialization/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT resource-acquisition-is-initialization - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java index 1d7b4137a..f2b0cdbe0 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.resource.acquisition.is.initialization; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java index 6786416fa..4bfdf4a8b 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -22,18 +22,19 @@ */ package com.iluwatar.resource.acquisition.is.initialization; -import static org.junit.Assert.assertTrue; - import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Date: 12/28/15 - 9:31 PM * @@ -43,12 +44,12 @@ public class ClosableTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/retry/README.md b/retry/README.md new file mode 100644 index 000000000..1b9987e66 --- /dev/null +++ b/retry/README.md @@ -0,0 +1,153 @@ +--- +layout: pattern +title: Retry +folder: retry +permalink: /patterns/retry/ +categories: Other +tags: + - Java + - Difficulty-Expert + - Performance +--- + +## Retry / resiliency +Enables an application to handle transient failures from external resources. + +## Intent +Transparently retry certain operations that involve communication with external +resources, particularly over the network, isolating calling code from the +retry implementation details. + +![alt text](./etc/retry.png "Retry") + +## Explanation +The `Retry` pattern consists retrying operations on remote resources over the +network a set number of times. It closely depends on both business and technical +requirements: how much time will the business allow the end user to wait while +the operation finishes? What are the performance characteristics of the +remote resource during peak loads as well as our application as more threads +are waiting for the remote resource's availability? Among the errors returned +by the remote service, which can be safely ignored in order to retry? Is the +operation [idempotent](https://en.wikipedia.org/wiki/Idempotence)? + +Another concern is the impact on the calling code by implementing the retry +mechanism. The retry mechanics should ideally be completely transparent to the +calling code (service interface remains unaltered). There are two general +approaches to this problem: from an enterprise architecture standpoint +(**strategic**), and a shared library standpoint (**tactical**). + +*(As an aside, one interesting property is that, since implementations tend to +be configurable at runtime, daily monitoring and operation of this capability +is shifted over to operations support instead of the developers themselves.)* + +From a strategic point of view, this would be solved by having requests +be redirected to a separate intermediary system, traditionally an +[ESB](https://en.wikipedia.org/wiki/Enterprise_service_bus), but more recently +a [Service Mesh](https://medium.com/microservices-in-practice/service-mesh-for-microservices-2953109a3c9a). + +From a tactical point of view, this would be solved by reusing shared libraries +like [Hystrix](https://github.com/Netflix/Hystrix)[1]. This is the type of +solution showcased in the simple example that accompanies this *README*. + +In our hypothetical application, we have a generic interface for all +operations on remote interfaces: + +```java +public interface BusinessOperation { + T perform() throws BusinessException; +} +``` + +And we have an implementation of this interface that finds our customers +by looking up a database: + +```java +public final class FindCustomer implements BusinessOperation { + @Override + public String perform() throws BusinessException { + ... + } +} +``` + +Our `FindCustomer` implementation can be configured to throw +`BusinessException`s before returning the customer's ID, thereby simulating a +'flaky' service that intermittently fails. Some exceptions, like the +`CustomerNotFoundException`, are deemed to be recoverable after some +hypothetical analysis because the root cause of the error stems from "some +database locking issue". However, the `DatabaseNotAvailableException` is +considered to be a definite showstopper - the application should not attempt +to recover from this error. + +We can model a 'recoverable' scenario by instantiating `FindCustomer` like this: + +```java +final BusinessOperation op = new FindCustomer( + "12345", + new CustomerNotFoundException("not found"), + new CustomerNotFoundException("still not found"), + new CustomerNotFoundException("don't give up yet!") +); +``` + +In this configuration, `FindCustomer` will throw `CustomerNotFoundException` +three times, after which it will consistently return the customer's ID +(`12345`). + +In our hypothetical scenario, our analysts indicate that this operation +typically fails 2-4 times for a given input during peak hours, and that each +worker thread in the database subsystem typically needs 50ms to +"recover from an error". Applying these policies would yield something like +this: + +```java +final BusinessOperation op = new Retry<>( + new FindCustomer( + "1235", + new CustomerNotFoundException("not found"), + new CustomerNotFoundException("still not found"), + new CustomerNotFoundException("don't give up yet!") + ), + 5, + 100, + e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) +); +``` + +Executing `op` *once* would automatically trigger at most 5 retry attempts, +with a 100 millisecond delay between attempts, ignoring any +`CustomerNotFoundException` thrown while trying. In this particular scenario, +due to the configuration for `FindCustomer`, there will be 1 initial attempt +and 3 additional retries before finally returning the desired result `12345`. + +If our `FindCustomer` operation were instead to throw a fatal +`DatabaseNotFoundException`, which we were instructed not to ignore, but +more importantly we did *not* instruct our `Retry` to ignore, then the operation +would have failed immediately upon receiving the error, not matter how many +attempts were left. + +

+ +[1] Please note that *Hystrix* is a complete implementation of the *Circuit +Breaker* pattern, of which the *Retry* pattern can be considered a subset of. + +## Applicability +Whenever an application needs to communicate with an external resource, +particularly in a cloud environment, and if the business requirements allow it. + +## Presentations +You can view Microsoft's article [here](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry). + +## Consequences +**Pros:** + +* Resiliency +* Provides hard data on external failures + +**Cons:** + +* Complexity +* Operations maintenance + +## Related Patterns +* [Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) diff --git a/retry/etc/retry.png b/retry/etc/retry.png new file mode 100644 index 000000000..3ef6d3800 Binary files /dev/null and b/retry/etc/retry.png differ diff --git a/retry/pom.xml b/retry/pom.xml new file mode 100644 index 000000000..9fb98d42a --- /dev/null +++ b/retry/pom.xml @@ -0,0 +1,50 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.19.0-SNAPSHOT + + retry + jar + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.hamcrest + hamcrest-core + test + + + \ No newline at end of file diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java new file mode 100644 index 000000000..376a64fbf --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/App.java @@ -0,0 +1,105 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Retry pattern enables applications to handle potentially recoverable failures from + * the environment if the business requirements and nature of the failures allow it. By retrying + * failed operations on external dependencies, the application may maintain stability and minimize + * negative impact on the user experience. + *

+ * In our example, we have the {@link BusinessOperation} interface as an abstraction over + * all operations that our application performs involving remote systems. The calling code should + * remain decoupled from implementations. + *

+ * {@link FindCustomer} is a business operation that looks up a customer's record and returns + * its ID. Imagine its job is performed by looking up the customer in our local database and + * returning its ID. We can pass {@link CustomerNotFoundException} as one of its + * {@link FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) + * constructor parameters} in order to simulate not finding the customer. + *

+ * Imagine that, lately, this operation has experienced intermittent failures due to some weird + * corruption and/or locking in the data. After retrying a few times the customer is found. The + * database is still, however, expected to always be available. While a definitive solution is + * found to the problem, our engineers advise us to retry the operation a set number + * of times with a set delay between retries, although not too many retries otherwise the end user + * will be left waiting for a long time, while delays that are too short will not allow the database + * to recover from the load. + *

+ * To keep the calling code as decoupled as possible from this workaround, we have implemented the + * retry mechanism as a {@link BusinessOperation} named {@link Retry}. + * + * @author George Aristy (george.aristy@gmail.com) + * @see Retry pattern (Microsoft Azure Docs) + */ +public final class App { + private static final Logger LOG = LoggerFactory.getLogger(App.class); + private static BusinessOperation op; + + /** + * Entry point. + * + * @param args not used + * @throws Exception not expected + */ + public static void main(String[] args) throws Exception { + noErrors(); + errorNoRetry(); + errorWithRetry(); + } + + private static void noErrors() throws Exception { + op = new FindCustomer("123"); + op.perform(); + LOG.info("Sometimes the operation executes with no errors."); + } + + private static void errorNoRetry() throws Exception { + op = new FindCustomer("123", new CustomerNotFoundException("not found")); + try { + op.perform(); + } catch (CustomerNotFoundException e) { + LOG.info("Yet the operation will throw an error every once in a while."); + } + } + + private static void errorWithRetry() throws Exception { + final Retry retry = new Retry<>( + new FindCustomer("123", new CustomerNotFoundException("not found")), + 3, //3 attempts + 100, //100 ms delay between attempts + e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) + ); + op = retry; + final String customerId = op.perform(); + LOG.info(String.format( + "However, retrying the operation while ignoring a recoverable error will eventually yield " + + "the result %s after a number of attempts %s", customerId, retry.attempts() + )); + } +} diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessException.java b/retry/src/main/java/com/iluwatar/retry/BusinessException.java new file mode 100644 index 000000000..eefbf2813 --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/BusinessException.java @@ -0,0 +1,46 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +/** + * The top-most type in our exception hierarchy that signifies that an unexpected error + * condition occurred. Its use is reserved as a "catch-all" for cases where no other subtype + * captures the specificity of the error condition in question. Calling code is not expected to + * be able to handle this error and should be reported to the maintainers immediately. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class BusinessException extends Exception { + private static final long serialVersionUID = 6235833142062144336L; + + /** + * Ctor + * + * @param message the error message + */ + public BusinessException(String message) { + super(message); + } +} diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java new file mode 100644 index 000000000..aefb589c7 --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java @@ -0,0 +1,44 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +/** + * Performs some business operation. + * + * @author George Aristy (george.aristy@gmail.com) + * @param the return type + */ +@FunctionalInterface +public interface BusinessOperation { + /** + * Performs some business operation, returning a value {@code T} if successful, otherwise throwing + * an exception if an error occurs. + * + * @return the return value + * @throws BusinessException if the operation fails. Implementations are allowed to throw more + * specific subtypes depending on the error conditions + */ + T perform() throws BusinessException; +} diff --git a/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java new file mode 100644 index 000000000..596d8584d --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java @@ -0,0 +1,46 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +/** + * Indicates that the customer was not found. + *

+ * The severity of this error is bounded by its context: was the search for the customer triggered + * by an input from some end user, or were the search parameters pulled from your database? + * + * @author George Aristy (george.aristy@gmail.com) + */ +public final class CustomerNotFoundException extends BusinessException { + private static final long serialVersionUID = -6972888602621778664L; + + /** + * Ctor. + * + * @param message the error message + */ + public CustomerNotFoundException(String message) { + super(message); + } +} diff --git a/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java new file mode 100644 index 000000000..2a93e992d --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +/** + * Catastrophic error indicating that we have lost connection to our database. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public final class DatabaseNotAvailableException extends BusinessException { + private static final long serialVersionUID = -3750769625095997799L; + + /** + * Ctor. + * + * @param message the error message + */ + public DatabaseNotAvailableException(String message) { + super(message); + } +} diff --git a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java new file mode 100644 index 000000000..421f450e5 --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; + +/** + * Finds a customer, returning its ID from our records. + *

+ * This is an imaginary operation that, for some imagined input, returns the ID for a customer. + * However, this is a "flaky" operation that is supposed to fail intermittently, but for the + * purposes of this example it fails in a programmed way depending on the constructor parameters. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public final class FindCustomer implements BusinessOperation { + private final String customerId; + private final Deque errors; + + /** + * Ctor. + * + * @param customerId the final result of the remote operation + * @param errors the errors to throw before returning {@code customerId} + */ + public FindCustomer(String customerId, BusinessException... errors) { + this.customerId = customerId; + this.errors = new ArrayDeque<>(Arrays.asList(errors)); + } + + @Override + public String perform() throws BusinessException { + if (!this.errors.isEmpty()) { + throw this.errors.pop(); + } + + return this.customerId; + } +} diff --git a/retry/src/main/java/com/iluwatar/retry/Retry.java b/retry/src/main/java/com/iluwatar/retry/Retry.java new file mode 100644 index 000000000..5ed60f98b --- /dev/null +++ b/retry/src/main/java/com/iluwatar/retry/Retry.java @@ -0,0 +1,110 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; + +/** + * Decorates {@link BusinessOperation business operation} with "retry" capabilities. + * + * @author George Aristy (george.aristy@gmail.com) + * @param the remote op's return type + */ +public final class Retry implements BusinessOperation { + private final BusinessOperation op; + private final int maxAttempts; + private final long delay; + private final AtomicInteger attempts; + private final Predicate test; + private final List errors; + + /** + * Ctor. + * + * @param op the {@link BusinessOperation} to retry + * @param maxAttempts number of times to retry + * @param delay delay (in milliseconds) between attempts + * @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions + * will be ignored if no tests are given + */ + @SafeVarargs + public Retry( + BusinessOperation op, + int maxAttempts, + long delay, + Predicate... ignoreTests + ) { + this.op = op; + this.maxAttempts = maxAttempts; + this.delay = delay; + this.attempts = new AtomicInteger(); + this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false); + this.errors = new ArrayList<>(); + } + + /** + * The errors encountered while retrying, in the encounter order. + * + * @return the errors encountered while retrying + */ + public List errors() { + return Collections.unmodifiableList(this.errors); + } + + /** + * The number of retries performed. + * + * @return the number of retries performed + */ + public int attempts() { + return this.attempts.intValue(); + } + + @Override + public T perform() throws BusinessException { + do { + try { + return this.op.perform(); + } catch (BusinessException e) { + this.errors.add(e); + + if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) { + throw e; + } + + try { + Thread.sleep(this.delay); + } catch (InterruptedException f) { + //ignore + } + } + } while (true); + } +} diff --git a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java new file mode 100644 index 000000000..46c4c62e6 --- /dev/null +++ b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -0,0 +1,90 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit tests for {@link FindCustomer}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class FindCustomerTest { + /** + * Returns the given result with no exceptions. + */ + @Test + public void noExceptions() throws Exception { + assertThat( + new FindCustomer("123").perform(), + is("123") + ); + } + + /** + * Throws the given exception. + * + * @throws Exception the expected exception + */ + @Test + public void oneException() throws Exception { + assertThrows(BusinessException.class, () -> { + new FindCustomer("123", new BusinessException("test")).perform(); + }); + } + + /** + * Should first throw the given exceptions, then return the given result. + * + * @throws Exception not an expected exception + */ + @Test + public void resultAfterExceptions() throws Exception { + final BusinessOperation op = new FindCustomer( + "123", + new CustomerNotFoundException("not found"), + new DatabaseNotAvailableException("not available") + ); + try { + op.perform(); + } catch (CustomerNotFoundException e) { + //ignore + } + try { + op.perform(); + } catch (DatabaseNotAvailableException e) { + //ignore + } + + assertThat( + op.perform(), + is("123") + ); + } +} diff --git a/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/retry/src/test/java/com/iluwatar/retry/RetryTest.java new file mode 100644 index 000000000..233e0e588 --- /dev/null +++ b/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -0,0 +1,111 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 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.retry; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Unit tests for {@link Retry}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class RetryTest { + /** + * Should contain all errors thrown. + */ + @Test + public void errors() throws Exception { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.errors(), + hasItem(e) + ); + } + + /** + * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking + * it to attempt twice. + */ + @Test + public void attempts() { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(1) + ); + } + + /** + * Final number of attempts should be equal to the number of attempts asked because we are + * asking it to ignore the exception that will be thrown. + */ + @Test + public void ignore() throws Exception { + final BusinessException e = new CustomerNotFoundException("customer not found"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0, + ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(2) + ); + } + +} \ No newline at end of file diff --git a/semaphore/README.md b/semaphore/README.md index 071e061a7..46ccd7b8e 100644 --- a/semaphore/README.md +++ b/semaphore/README.md @@ -3,7 +3,6 @@ layout: pattern title: Semaphore folder: semaphore permalink: /patterns/semaphore/ -pumlid: HSV14SCm20J0Lk82BFxf1ikCfOn06ZZizfDVVhjRjphobFJnQi2ADv7pKwwEbaU6U9q6CPGwbVh8Xy5E7xvvFoNwPVjYGDo2bEC72b5URRgGeFvNqhMirF45 categories: Concurrency tags: - Java diff --git a/semaphore/etc/semaphore.urm.puml b/semaphore/etc/semaphore.urm.puml deleted file mode 100644 index 168fd17e7..000000000 --- a/semaphore/etc/semaphore.urm.puml +++ /dev/null @@ -1,56 +0,0 @@ -@startuml -package com.iluwatar.semaphore { - class App { - + App() - + main(args : String[]) {static} - } - class Fruit { - - type : FruitType - + Fruit(type : FruitType) - + getType() : FruitType - + toString() : String - } - enum FruitType { - + APPLE {static} - + LEMON {static} - + ORANGE {static} - + valueOf(name : String) : FruitType {static} - + values() : FruitType[] {static} - } - class FruitBowl { - - fruit : List - + FruitBowl() - + countFruit() : int - + put(f : Fruit) - + take() : Fruit - + toString() : String - } - class FruitShop { - - available : boolean[] - - bowls : FruitBowl[] - - semaphore : Semaphore - + FruitShop() - + countFruit() : int - + returnBowl(bowl : FruitBowl) - + takeBowl() : FruitBowl - } - interface Lock { - + acquire() {abstract} - + release() {abstract} - } - class Semaphore { - - counter : int - - licenses : int - + Semaphore(licenses : int) - + acquire() - + getAvailableLicenses() : int - + getNumLicenses() : int - + release() - } -} -FruitType ..+ Fruit -Fruit --> "-type" FruitType -FruitShop --> "-semaphore" Semaphore -FruitBowl --> "-fruit" Fruit -Semaphore ..|> Lock -@enduml \ No newline at end of file diff --git a/semaphore/pom.xml b/semaphore/pom.xml index dbab5325e..6337951a4 100644 --- a/semaphore/pom.xml +++ b/semaphore/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT semaphore - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java index 26d274262..6ad023e5d 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java @@ -22,13 +22,14 @@ */ package com.iluwatar.semaphore; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; /** * Application Test Entrypoint */ -public class AppTest{ +public class AppTest { @Test public void test() throws IOException { String[] args = {}; diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java index 30a7dce44..7bc391478 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java @@ -22,8 +22,11 @@ */ package com.iluwatar.semaphore; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Test taking from and putting Fruit into a FruitBowl diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java index b787a3301..ad67026ae 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java @@ -22,8 +22,10 @@ */ package com.iluwatar.semaphore; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test case for acquiring and releasing a Semaphore diff --git a/servant/README.md b/servant/README.md index d14d35edf..3e82ab2cf 100644 --- a/servant/README.md +++ b/servant/README.md @@ -3,7 +3,6 @@ layout: pattern title: Servant folder: servant permalink: /patterns/servant/ -pumlid: DSkn4O0m20NGLNG0G-ys63cDbv0SV7HzRUnUy-QYkSOkONKwWU4haV6JZe8pjd2nt1MYIBatAZKU1XjTVFEoYvT3by60c3erzW_qdPiL9CY_KrXB8rfz0G00 categories: Structural tags: - Java diff --git a/servant/etc/servant.urm.puml b/servant/etc/servant.urm.puml deleted file mode 100644 index 96dee04bc..000000000 --- a/servant/etc/servant.urm.puml +++ /dev/null @@ -1,56 +0,0 @@ -@startuml -package com.iluwatar.servant { - class App { - - LOGGER : Logger {static} - ~ jenkins : Servant {static} - ~ travis : Servant {static} - + App() - + main(args : String[]) {static} - + scenario(servant : Servant, compliment : int) {static} - } - class King { - - complimentReceived : boolean - - isDrunk : boolean - - isHappy : boolean - - isHungry : boolean - + King() - + changeMood() - + getDrink() - + getFed() - + getMood() : boolean - + receiveCompliments() - } - class Queen { - - complimentReceived : boolean - - isDrunk : boolean - - isFlirty : boolean - - isHappy : boolean - - isHungry : boolean - + Queen() - + changeMood() - + getDrink() - + getFed() - + getMood() : boolean - + receiveCompliments() - + setFlirtiness(f : boolean) - } - ~interface Royalty { - + changeMood() {abstract} - + getDrink() {abstract} - + getFed() {abstract} - + getMood() : boolean {abstract} - + receiveCompliments() {abstract} - } - class Servant { - + name : String - + Servant(name : String) - + checkIfYouWillBeHanged(tableGuests : List) : boolean - + feed(r : Royalty) - + giveCompliments(r : Royalty) - + giveWine(r : Royalty) - } -} -App --> "-jenkins" Servant -King ..|> Royalty -Queen ..|> Royalty -@enduml \ No newline at end of file diff --git a/servant/pom.xml b/servant/pom.xml index 4a0c753de..220e197f1 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT servant - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/servant/src/test/java/com/iluwatar/servant/AppTest.java b/servant/src/test/java/com/iluwatar/servant/AppTest.java index 5b8908d80..6226c272d 100644 --- a/servant/src/test/java/com/iluwatar/servant/AppTest.java +++ b/servant/src/test/java/com/iluwatar/servant/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.servant; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/servant/src/test/java/com/iluwatar/servant/KingTest.java b/servant/src/test/java/com/iluwatar/servant/KingTest.java index 3ebbaf28b..969cc3d43 100644 --- a/servant/src/test/java/com/iluwatar/servant/KingTest.java +++ b/servant/src/test/java/com/iluwatar/servant/KingTest.java @@ -22,9 +22,10 @@ */ package com.iluwatar.servant; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/28/15 - 9:40 PM diff --git a/servant/src/test/java/com/iluwatar/servant/QueenTest.java b/servant/src/test/java/com/iluwatar/servant/QueenTest.java index d425886ba..17498e248 100644 --- a/servant/src/test/java/com/iluwatar/servant/QueenTest.java +++ b/servant/src/test/java/com/iluwatar/servant/QueenTest.java @@ -22,9 +22,11 @@ */ package com.iluwatar.servant; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/28/15 - 9:52 PM diff --git a/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/servant/src/test/java/com/iluwatar/servant/ServantTest.java index 900ccc418..16e1d3c00 100644 --- a/servant/src/test/java/com/iluwatar/servant/ServantTest.java +++ b/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -22,12 +22,12 @@ */ package com.iluwatar.servant; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; diff --git a/service-layer/README.md b/service-layer/README.md index af393947f..9b685d4e3 100644 --- a/service-layer/README.md +++ b/service-layer/README.md @@ -3,7 +3,6 @@ layout: pattern title: Service Layer folder: service-layer permalink: /patterns/service-layer/ -pumlid: LOl93SCm3C1MQGUmzUysgY8aAcJ5q96WszVV_aW2V8gHriRb-ZWoPxm07E--Inxrhc2dqv8jEvq3HEl6H8SFNjWs3jcjJSnaju21iG3MSmbnK_mkuwJ_qij7dpNq1m00 categories: Architectural tags: - Java diff --git a/service-layer/etc/service-layer.urm.puml b/service-layer/etc/service-layer.urm.puml deleted file mode 100644 index 6cf9b938d..000000000 --- a/service-layer/etc/service-layer.urm.puml +++ /dev/null @@ -1,161 +0,0 @@ -@startuml -left to right direction -package com.iluwatar.servicelayer.hibernate { - class HibernateUtil { - - LOGGER : Logger {static} - - sessionFactory : SessionFactory {static} - - HibernateUtil() - + dropSession() {static} - + getSessionFactory() : SessionFactory {static} - } -} -package com.iluwatar.servicelayer.common { - abstract class BaseEntity { - - version : Long - + BaseEntity() - + getId() : Long {abstract} - + getName() : String {abstract} - + setId(Long) {abstract} - + setName(String) {abstract} - } - interface Dao { - + delete(E extends BaseEntity) {abstract} - + find(Long) : E extends BaseEntity {abstract} - + findAll() : List {abstract} - + merge(E extends BaseEntity) : E extends BaseEntity {abstract} - + persist(E extends BaseEntity) {abstract} - } - abstract class DaoBaseImpl { - # persistentClass : Class - + DaoBaseImpl() - + delete(entity : E extends BaseEntity) - + find(id : Long) : E extends BaseEntity - + findAll() : List - # getSession() : Session - + merge(entity : E extends BaseEntity) : E extends BaseEntity - + persist(entity : E extends BaseEntity) - } -} -package com.iluwatar.servicelayer.magic { - interface MagicService { - + findAllSpellbooks() : List {abstract} - + findAllSpells() : List {abstract} - + findAllWizards() : List {abstract} - + findWizardsWithSpell(String) : List {abstract} - + findWizardsWithSpellbook(String) : List {abstract} - } - class MagicServiceImpl { - - spellDao : SpellDao - - spellbookDao : SpellbookDao - - wizardDao : WizardDao - + MagicServiceImpl(wizardDao : WizardDao, spellbookDao : SpellbookDao, spellDao : SpellDao) - + findAllSpellbooks() : List - + findAllSpells() : List - + findAllWizards() : List - + findWizardsWithSpell(name : String) : List - + findWizardsWithSpellbook(name : String) : List - } -} -package com.iluwatar.servicelayer.wizard { - class Wizard { - - id : Long - - name : String - - spellbooks : Set - + Wizard() - + Wizard(name : String) - + addSpellbook(spellbook : Spellbook) - + getId() : Long - + getName() : String - + getSpellbooks() : Set - + setId(id : Long) - + setName(name : String) - + setSpellbooks(spellbooks : Set) - + toString() : String - } - interface WizardDao { - + findByName(String) : Wizard {abstract} - } - class WizardDaoImpl { - + WizardDaoImpl() - + findByName(name : String) : Wizard - } -} -package com.iluwatar.servicelayer.spellbook { - class Spellbook { - - id : Long - - name : String - - spells : Set - - wizards : Set - + Spellbook() - + Spellbook(name : String) - + addSpell(spell : Spell) - + getId() : Long - + getName() : String - + getSpells() : Set - + getWizards() : Set - + setId(id : Long) - + setName(name : String) - + setSpells(spells : Set) - + setWizards(wizards : Set) - + toString() : String - } - interface SpellbookDao { - + findByName(String) : Spellbook {abstract} - } - class SpellbookDaoImpl { - + SpellbookDaoImpl() - + findByName(name : String) : Spellbook - } -} -package com.iluwatar.servicelayer.spell { - class Spell { - - id : Long - - name : String - - spellbook : Spellbook - + Spell() - + Spell(name : String) - + getId() : Long - + getName() : String - + getSpellbook() : Spellbook - + setId(id : Long) - + setName(name : String) - + setSpellbook(spellbook : Spellbook) - + toString() : String - } - interface SpellDao { - + findByName(String) : Spell {abstract} - } - class SpellDaoImpl { - + SpellDaoImpl() - + findByName(name : String) : Spell - } -} -package com.iluwatar.servicelayer.app { - class App { - - LOGGER : Logger {static} - + App() - + initData() {static} - + main(args : String[]) {static} - + queryData() {static} - } -} -MagicServiceImpl --> "-wizardDao" WizardDao -MagicServiceImpl --> "-spellbookDao" SpellbookDao -MagicServiceImpl --> "-spellDao" SpellDao -Spellbook --> "-spells" Spell -Spellbook --> "-wizards" Wizard -DaoBaseImpl ..|> Dao -MagicServiceImpl ..|> MagicService -Spell --|> BaseEntity -SpellDao --|> Dao -SpellDaoImpl ..|> SpellDao -SpellDaoImpl --|> DaoBaseImpl -Spellbook --|> BaseEntity -SpellbookDao --|> Dao -SpellbookDaoImpl ..|> SpellbookDao -SpellbookDaoImpl --|> DaoBaseImpl -Wizard --|> BaseEntity -WizardDao --|> Dao -WizardDaoImpl ..|> WizardDao -WizardDaoImpl --|> DaoBaseImpl -@enduml diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 3174e95ed..1a654e048 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT service-layer @@ -40,11 +40,16 @@ com.h2database h2 - + - junit - junit - test + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test org.mockito diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java index a667252a1..295383513 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java @@ -23,9 +23,8 @@ package com.iluwatar.servicelayer.app; import com.iluwatar.servicelayer.hibernate.HibernateUtil; - -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * @@ -40,7 +39,7 @@ public class AppTest { App.main(args); } - @After + @AfterEach public void tearDown() throws Exception { HibernateUtil.dropSession(); } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java index 694fc746d..2bc557d75 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java @@ -22,17 +22,18 @@ */ package com.iluwatar.servicelayer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Date: 12/28/15 - 10:53 PM @@ -74,7 +75,7 @@ public abstract class BaseDaoTest this.dao = dao; } - @Before + @BeforeEach public void setUp() throws Exception { for (int i = 0; i < INITIAL_COUNT; i++) { final String className = dao.persistentClass.getSimpleName(); @@ -83,7 +84,7 @@ public abstract class BaseDaoTest } } - @After + @AfterEach public void tearDown() throws Exception { HibernateUtil.dropSession(); } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java index 05ad6f887..66750c5b2 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -28,15 +28,14 @@ import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.spellbook.SpellbookDao; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDao; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.List; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java index b6b4917c8..e4a5bfa65 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java @@ -23,13 +23,12 @@ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.BaseDaoTest; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/28/15 - 11:02 PM diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java index fb7eca15a..a6f1b3ea3 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java @@ -23,13 +23,12 @@ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.BaseDaoTest; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/28/15 - 11:44 PM diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java index 64bd72c7a..d8a093319 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java @@ -23,13 +23,12 @@ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.BaseDaoTest; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/28/15 - 11:46 PM diff --git a/service-locator/README.md b/service-locator/README.md index 479c9ed0f..974a2a5fe 100644 --- a/service-locator/README.md +++ b/service-locator/README.md @@ -3,7 +3,6 @@ layout: pattern title: Service Locator folder: service-locator permalink: /patterns/service-locator/ -pumlid: NSjB3iCm203HgxG7iDdtDeIWX0fZYqzo_MRTtUX9ynOZhPtBzNLchlW0EDxza3nhgs2dQScMdUO0qRenqU6B5xQTGmvh2pFPBM1WF07FSmbnqqcOqu6J_gsNZxvgw0y0 categories: Structural tags: - Java diff --git a/service-locator/etc/service-locator.urm.puml b/service-locator/etc/service-locator.urm.puml deleted file mode 100644 index 38fe7ea1b..000000000 --- a/service-locator/etc/service-locator.urm.puml +++ /dev/null @@ -1,41 +0,0 @@ -@startuml -package com.iluwatar.servicelocator { - class App { - + App() - + main(args : String[]) {static} - } - class InitContext { - - LOGGER : Logger {static} - + InitContext() - + lookup(serviceName : String) : Object - } - interface Service { - + execute() {abstract} - + getId() : int {abstract} - + getName() : String {abstract} - } - class ServiceCache { - - LOGGER : Logger {static} - - serviceCache : Map - + ServiceCache() - + addService(newService : Service) - + getService(serviceName : String) : Service - } - class ServiceImpl { - - LOGGER : Logger {static} - - id : int - - serviceName : String - + ServiceImpl(serviceName : String) - + execute() - + getId() : int - + getName() : String - } - class ServiceLocator { - - serviceCache : ServiceCache {static} - - ServiceLocator() - + getService(serviceJndiName : String) : Service {static} - } -} -ServiceLocator --> "-serviceCache" ServiceCache -ServiceImpl ..|> Service -@enduml \ No newline at end of file diff --git a/service-locator/pom.xml b/service-locator/pom.xml index 23c54c08d..a8fc5ceb1 100644 --- a/service-locator/pom.xml +++ b/service-locator/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT service-locator - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java index 1228898f2..be844b16a 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.servicelocator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java index 5dbbcdaf7..1741f6d94 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java @@ -22,13 +22,13 @@ */ package com.iluwatar.servicelocator; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/29/15 - 19:07 PM diff --git a/singleton/README.md b/singleton/README.md index 1be304d8e..90a845846 100644 --- a/singleton/README.md +++ b/singleton/README.md @@ -3,7 +3,6 @@ layout: pattern title: Singleton folder: singleton permalink: /patterns/singleton/ -pumlid: HSV14SCm20J0Lk82BFxf1ikCh0n26ZZizfDVVhjRjwfvIhg-Bc35cyZvAQtZoYD3l4w364gTWxhcms2d3z-ydnAzsRuO4BUWmV43HRUcWcaagF-Lz55M3lq2 categories: Creational tags: - Java diff --git a/singleton/pom.xml b/singleton/pom.xml index 77226821d..f83f5e50c 100644 --- a/singleton/pom.xml +++ b/singleton/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT singleton - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java index 00ddb79ac..e4c0b26d8 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java @@ -24,6 +24,9 @@ package com.iluwatar.singleton; /** * Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18 + * + * This implementation is thread safe, however adding any other method and its thread safety + * is developers responsibility. */ public enum EnumIvoryTower { diff --git a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java index 951c5c4fd..2452b923d 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.singleton; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index f468ad0b8..ff9045339 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -22,8 +22,8 @@ */ package com.iluwatar.singleton; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -32,7 +32,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Supplier; -import org.junit.Test; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; /** * This class provides several test case that test singleton construction. @@ -80,29 +84,30 @@ public abstract class SingletonTest { /** * Test singleton instance in a concurrent setting */ - @Test(timeout = 10000) + @Test public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { + assertTimeout(ofMillis(10000), () -> { + // Create 10000 tasks and inside each callable instantiate the singleton class + final List> tasks = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + tasks.add(this.singletonInstanceMethod::get); + } - // Create 10000 tasks and inside each callable instantiate the singleton class - final List> tasks = new ArrayList<>(); - for (int i = 0; i < 10000; i++) { - tasks.add(this.singletonInstanceMethod::get); - } + // Use up to 8 concurrent threads to handle the tasks + final ExecutorService executorService = Executors.newFixedThreadPool(8); + final List> results = executorService.invokeAll(tasks); - // Use up to 8 concurrent threads to handle the tasks - final ExecutorService executorService = Executors.newFixedThreadPool(8); - final List> results = executorService.invokeAll(tasks); + // wait for all of the threads to complete + final S expectedInstance = this.singletonInstanceMethod.get(); + for (Future res : results) { + final S instance = res.get(); + assertNotNull(instance); + assertSame(expectedInstance, instance); + } - // wait for all of the threads to complete - final S expectedInstance = this.singletonInstanceMethod.get(); - for (Future res : results) { - final S instance = res.get(); - assertNotNull(instance); - assertSame(expectedInstance, instance); - } - - // tidy up the executor - executorService.shutdown(); + // tidy up the executor + executorService.shutdown(); + }); } diff --git a/specification/README.md b/specification/README.md index dc47f4970..564830653 100644 --- a/specification/README.md +++ b/specification/README.md @@ -3,7 +3,6 @@ layout: pattern title: Specification folder: specification permalink: /patterns/specification/ -pumlid: LSX14i8m20NGg-W16lRU1YcsE0d9mCTUNxVkthoxkVJQjQBVJc3bWoZuQeVXh6UbXao7EfhCGTRhOd3Gcp-yxPfs-BOOqF2amVa3vLAnbmd3ffD2_gTLZBPgz2y0 categories: Behavioral tags: - Java diff --git a/specification/etc/specification.urm.puml b/specification/etc/specification.urm.puml deleted file mode 100644 index fd3cbb20e..000000000 --- a/specification/etc/specification.urm.puml +++ /dev/null @@ -1,107 +0,0 @@ -@startuml -package com.iluwatar.specification.creature { - abstract class AbstractCreature { - - color : Color - - movement : Movement - - name : String - - size : Size - + AbstractCreature(name : String, size : Size, movement : Movement, color : Color) - + getColor() : Color - + getMovement() : Movement - + getName() : String - + getSize() : Size - + toString() : String - } - interface Creature { - + getColor() : Color {abstract} - + getMovement() : Movement {abstract} - + getName() : String {abstract} - + getSize() : Size {abstract} - } - class Dragon { - + Dragon() - } - class Goblin { - + Goblin() - } - class KillerBee { - + KillerBee() - } - class Octopus { - + Octopus() - } - class Shark { - + Shark() - } - class Troll { - + Troll() - } -} -package com.iluwatar.specification.property { - enum Color { - + DARK {static} - + GREEN {static} - + LIGHT {static} - + RED {static} - - title : String - + toString() : String - + valueOf(name : String) : Color {static} - + values() : Color[] {static} - } - enum Movement { - + FLYING {static} - + SWIMMING {static} - + WALKING {static} - - title : String - + toString() : String - + valueOf(name : String) : Movement {static} - + values() : Movement[] {static} - } - enum Size { - + LARGE {static} - + NORMAL {static} - + SMALL {static} - - title : String - + toString() : String - + valueOf(name : String) : Size {static} - + values() : Size[] {static} - } -} -package com.iluwatar.specification.selector { - class ColorSelector { - - c : Color - + ColorSelector(c : Color) - + test(t : Creature) : boolean - } - class MovementSelector { - - m : Movement - + MovementSelector(m : Movement) - + test(t : Creature) : boolean - } - class SizeSelector { - - s : Size - + SizeSelector(s : Size) - + test(t : Creature) : boolean - } -} -package com.iluwatar.specification.app { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } -} -SizeSelector --> "-s" Size -AbstractCreature --> "-color" Color -MovementSelector --> "-m" Movement -AbstractCreature --> "-movement" Movement -AbstractCreature --> "-size" Size -ColorSelector --> "-c" Color -AbstractCreature ..|> Creature -Dragon --|> AbstractCreature -Goblin --|> AbstractCreature -KillerBee --|> AbstractCreature -Octopus --|> AbstractCreature -Shark --|> AbstractCreature -Troll --|> AbstractCreature -@enduml \ No newline at end of file diff --git a/specification/pom.xml b/specification/pom.xml index 3a4fd371b..cfd28ae93 100644 --- a/specification/pom.xml +++ b/specification/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT specification - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java index a11101670..8cd648e58 100644 --- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java +++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.specification.app; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java index 1c969891b..2d43c8d59 100644 --- a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java +++ b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -25,30 +25,26 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collection; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/29/15 - 7:47 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class CreatureTest { /** * @return The tested {@link Creature} instance and its expected specs */ - @Parameterized.Parameters - public static Collection data() { + public static Collection dataProvider() { return Arrays.asList( new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED}, new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN}, @@ -59,71 +55,36 @@ public class CreatureTest { ); } - /** - * The tested creature - */ - private final Creature testedCreature; - - /** - * The expected name of the tested creature - */ - private final String name; - - /** - * The expected size of the tested creature - */ - private final Size size; - - /** - * The expected movement type of the tested creature - */ - private final Movement movement; - - /** - * The expected color of the tested creature - */ - private final Color color; - - /** - * @param testedCreature The tested creature - * @param name The expected name of the creature - * @param size The expected size of the creature - * @param movement The expected movement type of the creature - * @param color The expected color of the creature - */ - public CreatureTest(final Creature testedCreature, final String name, final Size size, - final Movement movement, final Color color) { - this.testedCreature = testedCreature; - this.name = name; - this.size = size; - this.movement = movement; - this.color = color; + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetName(Creature testedCreature, String name) throws Exception { + assertEquals(name, testedCreature.getName()); } - - @Test - public void testGetName() throws Exception { - assertEquals(this.name, this.testedCreature.getName()); + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetSize(Creature testedCreature, String name, Size size) throws Exception { + assertEquals(size, testedCreature.getSize()); } - @Test - public void testGetSize() throws Exception { - assertEquals(this.size, this.testedCreature.getSize()); + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetMovement(Creature testedCreature, String name, Size size, Movement movement) throws Exception { + assertEquals(movement, testedCreature.getMovement()); } - @Test - public void testGetMovement() throws Exception { - assertEquals(this.movement, this.testedCreature.getMovement()); + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetColor(Creature testedCreature, String name, Size size, Movement movement, + Color color) throws Exception { + assertEquals(color, testedCreature.getColor()); } - @Test - public void testGetColor() throws Exception { - assertEquals(this.color, this.testedCreature.getColor()); - } - - @Test - public void testToString() throws Exception { - final String toString = this.testedCreature.toString(); + @ParameterizedTest + @MethodSource("dataProvider") + public void testToString(Creature testedCreature, String name, Size size, Movement movement, + Color color) throws Exception { + final String toString = testedCreature.toString(); assertNotNull(toString); assertEquals( String.format("%s [size=%s, movement=%s, color=%s]", name, size, movement, color), diff --git a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java index 52b176915..5765c1c56 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -24,11 +24,10 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java index b9e86193e..8c7c0a54e 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -23,13 +23,11 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; -import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java index f2b6b80b7..c15e932bc 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -24,11 +24,10 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/state/README.md b/state/README.md index 34ad8074c..549afa61f 100644 --- a/state/README.md +++ b/state/README.md @@ -3,7 +3,6 @@ layout: pattern title: State folder: state permalink: /patterns/state/ -pumlid: 9SRH3O0m20N0LNG0ox_RO2LQqz867hg-9jxNpKLpZLt2wdG2mrSYuoST1MTiuMAvAqIHSczKQZmCDhhuvcKNBuSkWm4nTMhiNyZ141BaVocifH6jlW00 categories: Behavioral tags: - Java diff --git a/state/etc/state.urm.puml b/state/etc/state.urm.puml deleted file mode 100644 index 207a227d8..000000000 --- a/state/etc/state.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package com.iluwatar.state { - class AngryState { - - LOGGER : Logger {static} - - mammoth : Mammoth - + AngryState(mammoth : Mammoth) - + observe() - + onEnterState() - } - class App { - + App() - + main(args : String[]) {static} - } - class Mammoth { - - state : State - + Mammoth() - - changeStateTo(newState : State) - + observe() - + timePasses() - + toString() : String - } - class PeacefulState { - - LOGGER : Logger {static} - - mammoth : Mammoth - + PeacefulState(mammoth : Mammoth) - + observe() - + onEnterState() - } - interface State { - + observe() {abstract} - + onEnterState() {abstract} - } -} -PeacefulState --> "-mammoth" Mammoth -AngryState --> "-mammoth" Mammoth -Mammoth --> "-state" State -AngryState ..|> State -PeacefulState ..|> State -@enduml \ No newline at end of file diff --git a/state/pom.xml b/state/pom.xml index 44404d5a9..478e888bf 100644 --- a/state/pom.xml +++ b/state/pom.xml @@ -29,18 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT state - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.mockito - mockito-core + org.junit.jupiter + junit-jupiter-engine test diff --git a/state/src/test/java/com/iluwatar/state/AppTest.java b/state/src/test/java/com/iluwatar/state/AppTest.java index cb40d0481..16bffb2af 100644 --- a/state/src/test/java/com/iluwatar/state/AppTest.java +++ b/state/src/test/java/com/iluwatar/state/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.state; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java index 60f4b18f4..5c3bf3e69 100644 --- a/state/src/test/java/com/iluwatar/state/MammothTest.java +++ b/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -25,16 +25,16 @@ package com.iluwatar.state; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Date: 12/29/15 - 8:27 PM @@ -45,12 +45,12 @@ public class MammothTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/step-builder/README.md b/step-builder/README.md index 65d356c2e..bc636e37a 100644 --- a/step-builder/README.md +++ b/step-builder/README.md @@ -3,7 +3,6 @@ layout: pattern title: Step Builder folder: step-builder permalink: /patterns/step-builder/ -pumlid: LOZ93SCm3C1MQGQmzUysYYqaAcJ5q96i7t_x8KXkh4soKvfypeZfNm33fnuSP-xfPEtI88tQhW4i-M2WmGzlB9sS3oqJ8yZKOQ0lWOLPzcJfAoZQtwXfeyuSyW80 categories: Creational tags: - Java diff --git a/step-builder/etc/step-builder.urm.puml b/step-builder/etc/step-builder.urm.puml deleted file mode 100644 index dc6087340..000000000 --- a/step-builder/etc/step-builder.urm.puml +++ /dev/null @@ -1,91 +0,0 @@ -@startuml -package com.iluwatar.stepbuilder { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class Character { - - abilities : List - - fighterClass : String - - name : String - - spell : String - - weapon : String - - wizardClass : String - + Character(name : String) - + getAbilities() : List - + getFighterClass() : String - + getName() : String - + getSpell() : String - + getWeapon() : String - + getWizardClass() : String - + setAbilities(abilities : List) - + setFighterClass(fighterClass : String) - + setName(name : String) - + setSpell(spell : String) - + setWeapon(weapon : String) - + setWizardClass(wizardClass : String) - + toString() : String - } - class CharacterStepBuilder { - - CharacterStepBuilder() - + newBuilder() : NameStep {static} - } - interface AbilityStep { - + noAbilities() : BuildStep {abstract} - + noMoreAbilities() : BuildStep {abstract} - + withAbility(String) : AbilityStep {abstract} - } - interface BuildStep { - + build() : Character {abstract} - } - -class CharacterSteps { - - abilities : List - - fighterClass : String - - name : String - - spell : String - - weapon : String - - wizardClass : String - - CharacterSteps() - + build() : Character - + fighterClass(fighterClass : String) : WeaponStep - + name(name : String) : ClassStep - + noAbilities() : BuildStep - + noMoreAbilities() : BuildStep - + noSpell() : BuildStep - + noWeapon() : BuildStep - + withAbility(ability : String) : AbilityStep - + withSpell(spell : String) : AbilityStep - + withWeapon(weapon : String) : AbilityStep - + wizardClass(wizardClass : String) : SpellStep - } - interface ClassStep { - + fighterClass(String) : WeaponStep {abstract} - + wizardClass(String) : SpellStep {abstract} - } - interface NameStep { - + name(String) : ClassStep {abstract} - } - interface SpellStep { - + noSpell() : BuildStep {abstract} - + withSpell(String) : AbilityStep {abstract} - } - interface WeaponStep { - + noWeapon() : BuildStep {abstract} - + withWeapon(String) : AbilityStep {abstract} - } -} -WeaponStep ..+ CharacterStepBuilder -CharacterSteps ..+ CharacterStepBuilder -AbilityStep ..+ CharacterStepBuilder -SpellStep ..+ CharacterStepBuilder -ClassStep ..+ CharacterStepBuilder -NameStep ..+ CharacterStepBuilder -BuildStep ..+ CharacterStepBuilder -CharacterSteps ..|> NameStep -CharacterSteps ..|> ClassStep -CharacterSteps ..|> WeaponStep -CharacterSteps ..|> SpellStep -CharacterSteps ..|> AbilityStep -CharacterSteps ..|> BuildStep -@enduml \ No newline at end of file diff --git a/step-builder/pom.xml b/step-builder/pom.xml index fc7c7232e..00a8006de 100644 --- a/step-builder/pom.xml +++ b/step-builder/pom.xml @@ -30,13 +30,18 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT step-builder - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java index af1ddfb58..a5b7c952f 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.stepbuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java index 962feeabb..220e3f89a 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java @@ -22,14 +22,14 @@ */ package com.iluwatar.stepbuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Date: 12/29/15 - 9:21 PM diff --git a/strategy/README.md b/strategy/README.md index 74828cafc..4c7147bed 100644 --- a/strategy/README.md +++ b/strategy/README.md @@ -3,7 +3,6 @@ layout: pattern title: Strategy folder: strategy permalink: /patterns/strategy/ -pumlid: FSV13OCm30NGLM00udktCS4AGOaJsTz5tRwSkBstLiqj3WbhombC_n0PtwbKdB67Y-MX44NAerDjSJFOwE8lRuTuBRfD1iJKgRC_88SnfFn8aD-ai9vczFO7 categories: Behavioral tags: - Java diff --git a/strategy/etc/strategy.urm.puml b/strategy/etc/strategy.urm.puml deleted file mode 100644 index 8b9daabb9..000000000 --- a/strategy/etc/strategy.urm.puml +++ /dev/null @@ -1,37 +0,0 @@ -@startuml -package com.iluwatar.strategy { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class DragonSlayer { - - strategy : DragonSlayingStrategy - + DragonSlayer(strategy : DragonSlayingStrategy) - + changeStrategy(strategy : DragonSlayingStrategy) - + goToBattle() - } - interface DragonSlayingStrategy { - + execute() {abstract} - } - class MeleeStrategy { - - LOGGER : Logger {static} - + MeleeStrategy() - + execute() - } - class ProjectileStrategy { - - LOGGER : Logger {static} - + ProjectileStrategy() - + execute() - } - class SpellStrategy { - - LOGGER : Logger {static} - + SpellStrategy() - + execute() - } -} -DragonSlayer --> "-strategy" DragonSlayingStrategy -MeleeStrategy ..|> DragonSlayingStrategy -ProjectileStrategy ..|> DragonSlayingStrategy -SpellStrategy ..|> DragonSlayingStrategy -@enduml \ No newline at end of file diff --git a/strategy/pom.xml b/strategy/pom.xml index e6fc4cd53..8bae9c46a 100644 --- a/strategy/pom.xml +++ b/strategy/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT strategy - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params test diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java index 59b3a22a9..c14af1bde 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.strategy; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java index ad8b9784f..d22bf4235 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.strategy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java index 52e596e5c..c988ad2f6 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -25,11 +25,10 @@ package com.iluwatar.strategy; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; import java.util.Arrays; @@ -37,21 +36,19 @@ import java.util.Collection; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/29/15 - 10:58 PM * * @author Jeroen Meulemeester */ -@RunWith(Parameterized.class) public class DragonSlayingStrategyTest { /** * @return The test parameters for each cycle */ - @Parameterized.Parameters - public static Collection data() { + static Collection dataProvider() { return Arrays.asList( new Object[]{ new MeleeStrategy(), @@ -68,47 +65,27 @@ public class DragonSlayingStrategyTest { ); } - /** - * The tested strategy - */ - private final DragonSlayingStrategy strategy; - - /** - * The expected action in the log - */ - private final String expectedResult; - private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } - /** - * Create a new test instance for the given strategy - * - * @param strategy The tested strategy - * @param expectedResult The expected result - */ - public DragonSlayingStrategyTest(final DragonSlayingStrategy strategy, final String expectedResult) { - this.strategy = strategy; - this.expectedResult = expectedResult; - } - /** * Test if executing the strategy gives the correct response */ - @Test - public void testExecute() { - this.strategy.execute(); - assertEquals(this.expectedResult, appender.getLastMessage()); + @ParameterizedTest + @MethodSource("dataProvider") + public void testExecute(DragonSlayingStrategy strategy, String expectedResult) { + strategy.execute(); + assertEquals(expectedResult, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } diff --git a/template-method/README.md b/template-method/README.md index def168a8d..5a1402259 100644 --- a/template-method/README.md +++ b/template-method/README.md @@ -3,7 +3,6 @@ layout: pattern title: Template method folder: template-method permalink: /patterns/template-method/ -pumlid: NSZ13SCW30NGLPe1mFTkuu0Lg6n0vZjPlpttzlIEFef6bN1zDM3jDv7paw-E5cTiyJ87P22NQTGr7WOxVVZcL6NtQwJ5WFZOPBn_88WjPKWoGPkL1EN_ShZb5QPV categories: Behavioral tags: - Java diff --git a/template-method/etc/template-method.urm.puml b/template-method/etc/template-method.urm.puml deleted file mode 100644 index a6e2dc3d2..000000000 --- a/template-method/etc/template-method.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package com.iluwatar.templatemethod { - class App { - + App() - + main(args : String[]) {static} - } - class HalflingThief { - - method : StealingMethod - + HalflingThief(method : StealingMethod) - + changeMethod(method : StealingMethod) - + steal() - } - class HitAndRunMethod { - - LOGGER : Logger {static} - + HitAndRunMethod() - # confuseTarget(target : String) - # pickTarget() : String - # stealTheItem(target : String) - } - abstract class StealingMethod { - - LOGGER : Logger {static} - + StealingMethod() - # confuseTarget(String) {abstract} - # pickTarget() : String {abstract} - + steal() - # stealTheItem(String) {abstract} - } - class SubtleMethod { - - LOGGER : Logger {static} - + SubtleMethod() - # confuseTarget(target : String) - # pickTarget() : String - # stealTheItem(target : String) - } -} -HalflingThief --> "-method" StealingMethod -HitAndRunMethod --|> StealingMethod -SubtleMethod --|> StealingMethod -@enduml \ No newline at end of file diff --git a/template-method/pom.xml b/template-method/pom.xml index 0bd5bdc43..edfc2e2c6 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT template-method - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java index da85062f5..2974117ea 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.templatemethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java index 6cc80446c..86a823386 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.templatemethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java index 98ac62613..884ffe6ee 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -22,19 +22,19 @@ */ package com.iluwatar.templatemethod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Date: 12/30/15 - 18:12 PM * @param Type of StealingMethod @@ -44,12 +44,12 @@ public abstract class StealingMethodTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/thread-pool/README.md b/thread-pool/README.md index 473494ef9..9806fa8e0 100644 --- a/thread-pool/README.md +++ b/thread-pool/README.md @@ -3,7 +3,6 @@ layout: pattern title: Thread Pool folder: thread-pool permalink: /patterns/thread-pool/ -pumlid: JSV14SCW30J0Lk82GFzq8uF6a1624IUx_UIPt-xHhMXK2TTN0zP-4pa_-UfeSSOMBzCWXbpceAxnCDZfmpUdAhjVbXO3uhPfyFw1q5oufZMdag3yFuUFl6Be5m00 categories: Concurrency tags: - Java diff --git a/thread-pool/etc/thread-pool.urm.puml b/thread-pool/etc/thread-pool.urm.puml deleted file mode 100644 index 251033c81..000000000 --- a/thread-pool/etc/thread-pool.urm.puml +++ /dev/null @@ -1,37 +0,0 @@ -@startuml -package com.iluwatar.threadpool { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class CoffeeMakingTask { - - TIME_PER_CUP : int {static} - + CoffeeMakingTask(numCups : int) - + toString() : String - } - class PotatoPeelingTask { - - TIME_PER_POTATO : int {static} - + PotatoPeelingTask(numPotatoes : int) - + toString() : String - } - abstract class Task { - - ID_GENERATOR : AtomicInteger {static} - - id : int - - timeMs : int - + Task(timeMs : int) - + getId() : int - + getTimeMs() : int - + toString() : String - } - class Worker { - - LOGGER : Logger {static} - - task : Task - + Worker(task : Task) - + run() - } -} -Worker --> "-task" Task -CoffeeMakingTask --|> Task -PotatoPeelingTask --|> Task -@enduml \ No newline at end of file diff --git a/thread-pool/pom.xml b/thread-pool/pom.xml index f34238176..61701e40b 100644 --- a/thread-pool/pom.xml +++ b/thread-pool/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT thread-pool - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java index 2d21eec12..fafbce15e 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.threadpool; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application test diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java index 4a2a06de8..099cdc6e8 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java @@ -22,8 +22,7 @@ */ package com.iluwatar.threadpool; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -33,11 +32,13 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.function.Function; import java.util.function.IntFunction; -import java.util.function.ToIntFunction; import java.util.stream.Collectors; -import org.junit.Test; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; /** * Date: 12/30/15 - 18:22 PM @@ -82,30 +83,31 @@ public abstract class TaskTest { * Verify if the generated id is unique for each task, even if the tasks are created in separate * threads */ - @Test(timeout = 10000) + @Test public void testIdGeneration() throws Exception { - final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); + assertTimeout(ofMillis(10000), () -> { + final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); - final List> tasks = new ArrayList<>(); - for (int i = 0; i < TASK_COUNT; i++) { - tasks.add(() -> factory.apply(1).getId()); - } + final List> tasks = new ArrayList<>(); + for (int i = 0; i < TASK_COUNT; i++) { + tasks.add(() -> factory.apply(1).getId()); + } - final List ids = service.invokeAll(tasks) - .stream() - .map(TaskTest::get) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + final List ids = service.invokeAll(tasks) + .stream() + .map(TaskTest::get) + .filter(Objects::nonNull) + .collect(Collectors.toList()); - service.shutdownNow(); + service.shutdownNow(); - final long uniqueIdCount = ids.stream() - .distinct() - .count(); - - assertEquals(TASK_COUNT, ids.size()); - assertEquals(TASK_COUNT, uniqueIdCount); + final long uniqueIdCount = ids.stream() + .distinct() + .count(); + assertEquals(TASK_COUNT, ids.size()); + assertEquals(TASK_COUNT, uniqueIdCount); + }); } /** diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java index 81962ab2a..3b7186e98 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.threadpool; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/throttling/etc/throttling.urm.puml b/throttling/etc/throttling.urm.puml deleted file mode 100644 index 8c97da50a..000000000 --- a/throttling/etc/throttling.urm.puml +++ /dev/null @@ -1,29 +0,0 @@ -@startuml -package com.iluwatar.tls { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - - makeServiceCalls(service : B2BService) {static} - } - ~class B2BService { - - LOGGER : Logger {static} - - callsCounter : int - - tenant : Tenant - + B2BService(tenant : Tenant) - + dummyCustomerApi() : int - + getCurrentCallsCount() : int - - getRandomCustomerId() : int - } - class Tenant { - - allowedCallsPerSecond : int - - name : String - + Tenant(name : String, allowedCallsPerSecond : int) - + getAllowedCallsPerSecond() : int - + getName() : String - + setAllowedCallsPerSecond(allowedCallsPerSecond : int) - + setName(name : String) - } -} -B2BService --> "-tenant" Tenant -@enduml \ No newline at end of file diff --git a/throttling/pom.xml b/throttling/pom.xml index 2cbd7bf9e..4ac14493d 100644 --- a/throttling/pom.xml +++ b/throttling/pom.xml @@ -29,16 +29,22 @@ java-design-patterns com.iluwatar - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT 4.0.0 throttling - - junit - junit - + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + \ No newline at end of file diff --git a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java b/throttling/src/main/java/com/iluwatar/throttling/B2BService.java index c9acd4b73..51ed492eb 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java +++ b/throttling/src/main/java/com/iluwatar/throttling/B2BService.java @@ -46,7 +46,7 @@ class B2BService { */ public int dummyCustomerApi(Tenant tenant) { String tenantName = tenant.getName(); - int count = CallsCount.getCount(tenantName); + long count = CallsCount.getCount(tenantName); LOGGER.debug("Counter for {} : {} ", tenant.getName(), count); if (count >= tenant.getAllowedCallsPerSecond()) { LOGGER.error("API access per second limit reached for: {}", tenantName); diff --git a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java index 81195b074..9b274849a 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java +++ b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java @@ -22,9 +22,13 @@ */ package com.iluwatar.throttling; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; /** * A class to keep track of the counter of different Tenants @@ -32,16 +36,16 @@ import java.util.concurrent.ConcurrentHashMap; * */ public final class CallsCount { - private static Map tenantCallsCount = new ConcurrentHashMap<>(); + + private static final Logger LOGGER = LoggerFactory.getLogger(CallsCount.class); + private static Map tenantCallsCount = new ConcurrentHashMap<>(); /** * Add a new tenant to the map. * @param tenantName name of the tenant. */ public static void addTenant(String tenantName) { - if (!tenantCallsCount.containsKey(tenantName)) { - tenantCallsCount.put(tenantName, 0); - } + tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0)); } /** @@ -49,7 +53,7 @@ public final class CallsCount { * @param tenantName name of the tenant. */ public static void incrementCount(String tenantName) { - tenantCallsCount.put(tenantName, tenantCallsCount.get(tenantName) + 1); + tenantCallsCount.get(tenantName).incrementAndGet(); } /** @@ -57,16 +61,17 @@ public final class CallsCount { * @param tenantName name of the tenant. * @return the count of the tenant. */ - public static int getCount(String tenantName) { - return tenantCallsCount.get(tenantName); + public static long getCount(String tenantName) { + return tenantCallsCount.get(tenantName).get(); } /** * Resets the count of all the tenants in the map. */ public static void reset() { - for (Entry e : tenantCallsCount.entrySet()) { - tenantCallsCount.put(e.getKey(), 0); + LOGGER.debug("Resetting the map."); + for (Entry e : tenantCallsCount.entrySet()) { + tenantCallsCount.put(e.getKey(), new AtomicLong(0)); } } } diff --git a/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java b/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java index 51c5e3c28..4ff4ce246 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java +++ b/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java @@ -35,7 +35,7 @@ import com.iluwatar.throttling.CallsCount; * @author drastogi * */ -public class ThrottleTimerImpl implements Throttler{ +public class ThrottleTimerImpl implements Throttler { private int throttlePeriod; diff --git a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java index 37c8e75ec..97a54864c 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.throttling; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application test diff --git a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java index b9ca1a1d8..0c15bac6e 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java @@ -22,11 +22,11 @@ */ package com.iluwatar.throttling; -import org.junit.Assert; -import org.junit.Test; - import com.iluwatar.throttling.timer.ThrottleTimerImpl; import com.iluwatar.throttling.timer.Throttler; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * B2BServiceTest class to test the B2BService @@ -36,14 +36,13 @@ public class B2BServiceTest { @Test public void dummyCustomerApiTest() { Tenant tenant = new Tenant("testTenant", 2); - Throttler timer = new ThrottleTimerImpl(10); + Throttler timer = new ThrottleTimerImpl(100); B2BService service = new B2BService(timer); - + for (int i = 0; i < 5; i++) { service.dummyCustomerApi(tenant); } - - int counter = CallsCount.getCount(tenant.getName()); - Assert.assertTrue("Counter limit must be reached", counter == 2); + long counter = CallsCount.getCount(tenant.getName()); + assertTrue(counter == 2, "Counter limit must be reached"); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java b/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java index 2f0b5cf12..00e546d02 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java @@ -22,19 +22,21 @@ */ package com.iluwatar.throttling; -import org.junit.Test; - -import com.iluwatar.throttling.Tenant; +import org.junit.jupiter.api.Test; import java.security.InvalidParameterException; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * TenantTest to test the creation of Tenant with valid parameters. */ public class TenantTest { - @Test(expected = InvalidParameterException.class) + @Test public void constructorTest() { - Tenant tenant = new Tenant("FailTenant", -1); + assertThrows(InvalidParameterException.class, () -> { + Tenant tenant = new Tenant("FailTenant", -1); + }); } } diff --git a/tls/etc/tls.urm.puml b/tls/etc/tls.urm.puml deleted file mode 100644 index d2eedb371..000000000 --- a/tls/etc/tls.urm.puml +++ /dev/null @@ -1,23 +0,0 @@ -@startuml -package com.iluwatar.tls { - class App { - + App() - + main(args : String[]) {static} - - printAndCountDates(res : Result) : int {static} - - printAndCountExceptions(res : Result) : int {static} - } - class DateFormatCallable { - - dateValue : String - - df : ThreadLocal - + DateFormatCallable(inDateFormat : String, inDateValue : String) - + call() : Result - } - class Result { - - dateList : List - - exceptionList : List - + Result() - + getDateList() : List - + getExceptionList() : List - } -} -@enduml \ No newline at end of file diff --git a/tls/pom.xml b/tls/pom.xml index 460c5e7ea..a25904707 100644 --- a/tls/pom.xml +++ b/tls/pom.xml @@ -30,13 +30,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT tls - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tls/src/test/java/com/iluwatar/tls/AppTest.java b/tls/src/test/java/com/iluwatar/tls/AppTest.java index 073c0988a..12bb1ea3c 100644 --- a/tls/src/test/java/com/iluwatar/tls/AppTest.java +++ b/tls/src/test/java/com/iluwatar/tls/AppTest.java @@ -23,7 +23,7 @@ package com.iluwatar.tls; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that thread local storage example runs without errors. diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java index b4f24be9b..bb2dfafb7 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -32,10 +32,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -86,7 +87,7 @@ public class DateFormatCallableTest { /** * Run Callable and prepare results for usage in the test methods */ - @BeforeClass + @BeforeAll public static void setup() { // Create a callable DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java index e0a1507e9..da1b9c264 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -30,10 +30,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -84,7 +85,7 @@ public class DateFormatCallableTestIncorrectDateFormat { /** * Run Callable and prepare results for usage in the test methods */ - @BeforeClass + @BeforeAll public static void setup() { // Create a callable. Pass a string date value not matching the format string DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15.12.2015"); diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java index 635d6f25a..845ab366d 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -32,10 +32,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -90,7 +91,7 @@ public class DateFormatCallableTestMultiThread { /** * Run Callable and prepare results for usage in the test methods */ - @BeforeClass + @BeforeAll public static void setup() { // Create a callable DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); diff --git a/tolerant-reader/README.md b/tolerant-reader/README.md index 5d1cf80fd..be0085f2c 100644 --- a/tolerant-reader/README.md +++ b/tolerant-reader/README.md @@ -3,7 +3,6 @@ layout: pattern title: Tolerant Reader folder: tolerant-reader permalink: /patterns/tolerant-reader/ -pumlid: NSZ14SCm20NHLf829ExfXaYChGn26lZ4xSVdtFRjSrZJx9AkZnFOyI9olkenSEOxGxmjWnXgMvE6viLWfmz_kNI9SLZP38XRqEIuWx1Kd0t5XVjjGVj_DNtMdLD_ categories: Integration tags: - Java diff --git a/tolerant-reader/etc/tolerant-reader.urm.puml b/tolerant-reader/etc/tolerant-reader.urm.puml deleted file mode 100644 index a73394a4e..000000000 --- a/tolerant-reader/etc/tolerant-reader.urm.puml +++ /dev/null @@ -1,39 +0,0 @@ -@startuml -package com.iluwatar.tolerantreader { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class RainbowFish { - - age : int - - lengthMeters : int - - name : String - - serialVersionUID : long {static} - - weightTons : int - + RainbowFish(name : String, age : int, lengthMeters : int, weightTons : int) - + getAge() : int - + getLengthMeters() : int - + getName() : String - + getWeightTons() : int - } - class RainbowFishSerializer { - - RainbowFishSerializer() - + readV1(filename : String) : RainbowFish {static} - + writeV1(rainbowFish : RainbowFish, filename : String) {static} - + writeV2(rainbowFish : RainbowFishV2, filename : String) {static} - } - class RainbowFishV2 { - - angry : boolean - - hungry : boolean - - serialVersionUID : long {static} - - sleeping : boolean - + RainbowFishV2(name : String, age : int, lengthMeters : int, weightTons : int) - + RainbowFishV2(name : String, age : int, lengthMeters : int, weightTons : int, sleeping : boolean, hungry : boolean, angry : boolean) - + getAngry() : boolean - + getHungry() : boolean - + getSleeping() : boolean - } -} -RainbowFishV2 --|> RainbowFish -@enduml \ No newline at end of file diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml index 99a2cf880..3acc0b188 100644 --- a/tolerant-reader/pom.xml +++ b/tolerant-reader/pom.xml @@ -29,13 +29,23 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT tolerant-reader - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-migrationsupport test diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java index f24393779..07e6f6b89 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java @@ -22,9 +22,9 @@ */ package com.iluwatar.tolerantreader; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -42,8 +42,8 @@ public class AppTest { App.main(args); } - @Before - @After + @BeforeEach + @AfterEach public void cleanup() { File file1 = new File("fish1.out"); file1.delete(); diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java index a6c7fc641..2785c8374 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java @@ -23,19 +23,21 @@ package com.iluwatar.tolerantreader; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; import java.io.File; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; /** * Date: 12/30/15 - 18:39 PM * * @author Jeroen Meulemeester */ +@EnableRuleMigrationSupport public class RainbowFishSerializerTest { /** diff --git a/twin/README.md b/twin/README.md index 092032a55..3795236bb 100644 --- a/twin/README.md +++ b/twin/README.md @@ -3,7 +3,6 @@ layout: pattern title: Twin folder: twin permalink: /patterns/twin/ -pumlid: 7SR13OCm30NGLUW0n7UsCS42eyH4zdUpFbNVwNtKQij3qjjo0ICs8kTPJiMLUuPuVGnYAFNff2qdWvrk_l9wIEXfws10t88wno-4gKQ2-az9xsLaRoy0 categories: Creational tags: - Java diff --git a/twin/etc/twin.urm.puml b/twin/etc/twin.urm.puml deleted file mode 100644 index e48298f18..000000000 --- a/twin/etc/twin.urm.puml +++ /dev/null @@ -1,27 +0,0 @@ -@startuml -package com.iluwatar.twin { - class App { - + App() - + main(args : String[]) {static} - - waiting() {static} - } - class BallItem { - - LOGGER : Logger {static} - - isSuspended : boolean - - twin : BallThread - + BallItem() - + click() - + doDraw() - + move() - + setTwin(twin : BallThread) - } - abstract class GameItem { - - LOGGER : Logger {static} - + GameItem() - + click() {abstract} - + doDraw() {abstract} - + draw() - } -} -BallItem --|> GameItem -@enduml \ No newline at end of file diff --git a/twin/pom.xml b/twin/pom.xml index 013406215..ed7c9a77f 100644 --- a/twin/pom.xml +++ b/twin/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT twin - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/twin/src/test/java/com/iluwatar/twin/AppTest.java b/twin/src/test/java/com/iluwatar/twin/AppTest.java index 60e02e4c4..76f189f3f 100644 --- a/twin/src/test/java/com/iluwatar/twin/AppTest.java +++ b/twin/src/test/java/com/iluwatar/twin/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.twin; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java index 5dad02481..3c443ef62 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -22,8 +22,8 @@ */ package com.iluwatar.twin; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -33,9 +33,10 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.slf4j.LoggerFactory; @@ -48,12 +49,12 @@ public class BallItemTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); } diff --git a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java index f531a2493..010e6c7e2 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java @@ -22,10 +22,12 @@ */ package com.iluwatar.twin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.lang.Thread.UncaughtExceptionHandler; import static java.lang.Thread.sleep; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -44,68 +46,74 @@ public class BallThreadTest { /** * Verify if the {@link BallThread} can be resumed */ - @Test(timeout = 5000) + @Test public void testSuspend() throws Exception { - final BallThread ballThread = new BallThread(); + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); - final BallItem ballItem = mock(BallItem.class); - ballThread.setTwin(ballItem); + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); - ballThread.start(); + ballThread.start(); - verify(ballItem, timeout(2000).atLeastOnce()).draw(); - verify(ballItem, timeout(2000).atLeastOnce()).move(); - ballThread.suspendMe(); + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); + ballThread.suspendMe(); - sleep(1000); + sleep(1000); - ballThread.stopMe(); - ballThread.join(); + ballThread.stopMe(); + ballThread.join(); - verifyNoMoreInteractions(ballItem); + verifyNoMoreInteractions(ballItem); + }); } /** * Verify if the {@link BallThread} can be resumed */ - @Test(timeout = 5000) + @Test public void testResume() throws Exception { - final BallThread ballThread = new BallThread(); + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); - final BallItem ballItem = mock(BallItem.class); - ballThread.setTwin(ballItem); + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); - ballThread.suspendMe(); - ballThread.start(); + ballThread.suspendMe(); + ballThread.start(); - sleep(1000); + sleep(1000); - verifyZeroInteractions(ballItem); + verifyZeroInteractions(ballItem); - ballThread.resumeMe(); - verify(ballItem, timeout(2000).atLeastOnce()).draw(); - verify(ballItem, timeout(2000).atLeastOnce()).move(); + ballThread.resumeMe(); + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); - ballThread.stopMe(); - ballThread.join(); + ballThread.stopMe(); + ballThread.join(); - verifyNoMoreInteractions(ballItem); + verifyNoMoreInteractions(ballItem); + }); } /** * Verify if the {@link BallThread} is interruptible */ - @Test(timeout = 5000) + @Test public void testInterrupt() throws Exception { - final BallThread ballThread = new BallThread(); - final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); - ballThread.setUncaughtExceptionHandler(exceptionHandler); - ballThread.setTwin(mock(BallItem.class)); - ballThread.start(); - ballThread.interrupt(); - ballThread.join(); + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); + final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); + ballThread.setUncaughtExceptionHandler(exceptionHandler); + ballThread.setTwin(mock(BallItem.class)); + ballThread.start(); + ballThread.interrupt(); + ballThread.join(); - verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); - verifyNoMoreInteractions(exceptionHandler); + verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); + verifyNoMoreInteractions(exceptionHandler); + }); } } \ No newline at end of file diff --git a/unit-of-work/README.md b/unit-of-work/README.md new file mode 100644 index 000000000..b2fbde8ff --- /dev/null +++ b/unit-of-work/README.md @@ -0,0 +1,31 @@ +--- +layout: pattern +title: Unit Of Work +folder: unit-of-work +permalink: /patterns/unit-of-work/ + +categories: Architectural +tags: + - Java + - KISS + - YAGNI + - Difficulty-Beginner +--- + +## Intent +When a business transaction is completed, all the these updates are sent as one + big unit of work to be persisted in a database in one go so as to minimize database trips. + +![alt text](etc/unit-of-work.urm.png "unit-of-work") + +## Applicability +Use the Unit Of Work pattern when + +* To optimize the time taken for database transactions. +* To send changes to database as a unit of work which ensures atomicity of the transaction. +* To reduce number of database calls. + +## Credits + +* [Design Pattern - Unit Of Work Pattern](https://www.codeproject.com/Articles/581487/Unit-of-Work-Design-Pattern) +* [Unit Of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html) diff --git a/unit-of-work/etc/unit-of-work.ucls b/unit-of-work/etc/unit-of-work.ucls new file mode 100644 index 000000000..98181f805 --- /dev/null +++ b/unit-of-work/etc/unit-of-work.ucls @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/unit-of-work/etc/unit-of-work.urm.png b/unit-of-work/etc/unit-of-work.urm.png new file mode 100644 index 000000000..bb192af54 Binary files /dev/null and b/unit-of-work/etc/unit-of-work.urm.png differ diff --git a/unit-of-work/etc/unit-of-work.urm.puml b/unit-of-work/etc/unit-of-work.urm.puml new file mode 100644 index 000000000..7767a2e32 --- /dev/null +++ b/unit-of-work/etc/unit-of-work.urm.puml @@ -0,0 +1,48 @@ +@startuml +package com.iluwatar.unitofwork { + class App { + + App() + + main(args : String[]) {static} + } + interface IUnitOfWork { + + DELETE : String {static} + + INSERT : String {static} + + MODIFY : String {static} + + commit() {abstract} + + registerDeleted(T) {abstract} + + registerModified(T) {abstract} + + registerNew(T) {abstract} + } + class Student { + - address : String + - id : Integer + - name : String + + Student(id : Integer, name : String, address : String) + + getAddress() : String + + getId() : Integer + + getName() : String + } + class StudentDatabase { + + StudentDatabase() + + delete(student : Student) + + insert(student : Student) + + modify(student : Student) + } + class StudentRepository { + - LOGGER : Logger {static} + - context : Map> + - studentDatabase : StudentDatabase + + StudentRepository(context : Map>, studentDatabase : StudentDatabase) + + commit() + - commitDelete() + - commitInsert() + - commitModify() + - register(student : Student, operation : String) + + registerDeleted(student : Student) + + registerModified(student : Student) + + registerNew(student : Student) + } +} +StudentRepository --> "-studentDatabase" StudentDatabase +StudentRepository ..|> IUnitOfWork +@enduml \ No newline at end of file diff --git a/unit-of-work/pom.xml b/unit-of-work/pom.xml new file mode 100644 index 000000000..8a75b16af --- /dev/null +++ b/unit-of-work/pom.xml @@ -0,0 +1,54 @@ + + + + + java-design-patterns + com.iluwatar + 1.19.0-SNAPSHOT + + 4.0.0 + + unit-of-work + + + junit + junit + + + org.junit.vintage + junit-vintage-engine + test + + + org.mockito + mockito-core + + + + + \ No newline at end of file diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java new file mode 100644 index 000000000..9b4b2f15c --- /dev/null +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java @@ -0,0 +1,52 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +import java.util.HashMap; +import java.util.List; + +/** + * {@link App} Application for managing student data. + */ +public class App { + /** + * + * @param args no argument sent + */ + public static void main(String[] args) { + Student ram = new Student(1, "Ram", "Street 9, Cupertino"); + Student shyam = new Student(2, "Shyam", "Z bridge, Pune"); + Student gopi = new Student(3, "Gopi", "Street 10, Mumbai"); + + HashMap> context = new HashMap<>(); + StudentDatabase studentDatabase = new StudentDatabase(); + StudentRepository studentRepository = new StudentRepository(context, studentDatabase); + + studentRepository.registerNew(ram); + studentRepository.registerModified(shyam); + studentRepository.registerDeleted(gopi); + studentRepository.commit(); + } +} diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/IUnitOfWork.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/IUnitOfWork.java new file mode 100644 index 000000000..e0b453498 --- /dev/null +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/IUnitOfWork.java @@ -0,0 +1,55 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +/** + * @param Any generic entity + */ +public interface IUnitOfWork { + String INSERT = "INSERT"; + String DELETE = "DELETE"; + String MODIFY = "MODIFY"; + + /** + * Any register new operation occurring on UnitOfWork is only going to be performed on commit. + */ + void registerNew(T entity); + + /** + * Any register modify operation occurring on UnitOfWork is only going to be performed on commit. + */ + void registerModified(T entity); + + /** + * Any register delete operation occurring on UnitOfWork is only going to be performed on commit. + */ + void registerDeleted(T entity); + + /*** + * All UnitOfWork operations batched together executed in commit only. + */ + void commit(); + +} \ No newline at end of file diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java new file mode 100644 index 000000000..5a57ccdde --- /dev/null +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +/** + * {@link Student} is an entity. + */ +public class Student { + private final Integer id; + private final String name; + private final String address; + + /** + * @param id student unique id + * @param name name of student + * @param address address of student + */ + public Student(Integer id, String name, String address) { + this.id = id; + this.name = name; + this.address = address; + } + + public String getName() { + return name; + } + + public Integer getId() { + return id; + } + + public String getAddress() { + return address; + } +} diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java new file mode 100644 index 000000000..6b0e85517 --- /dev/null +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +/** + * Act as Database for student records. + */ +public class StudentDatabase { + + public void insert(Student student) { + //Some insert logic to DB + } + + public void modify(Student student) { + //Some modify logic to DB + } + + public void delete(Student student) { + //Some delete logic to DB + } +} diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java new file mode 100644 index 000000000..ff1136620 --- /dev/null +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java @@ -0,0 +1,126 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * {@link StudentRepository} Student database repository. + * supports unit of work for student data. + */ +public class StudentRepository implements IUnitOfWork { + private static final Logger LOGGER = LoggerFactory.getLogger(StudentRepository.class); + + private Map> context; + private StudentDatabase studentDatabase; + + /** + * @param context set of operations to be perform during commit. + * @param studentDatabase Database for student records. + */ + public StudentRepository(Map> context, StudentDatabase studentDatabase) { + this.context = context; + this.studentDatabase = studentDatabase; + } + + @Override + public void registerNew(Student student) { + LOGGER.info("Registering {} for insert in context.", student.getName()); + register(student, IUnitOfWork.INSERT); + } + + @Override + public void registerModified(Student student) { + LOGGER.info("Registering {} for modify in context.", student.getName()); + register(student, IUnitOfWork.MODIFY); + + } + + @Override + public void registerDeleted(Student student) { + LOGGER.info("Registering {} for delete in context.", student.getName()); + register(student, IUnitOfWork.DELETE); + } + + private void register(Student student, String operation) { + List studentsToOperate = context.get(operation); + if (studentsToOperate == null) { + studentsToOperate = new ArrayList<>(); + } + studentsToOperate.add(student); + context.put(operation, studentsToOperate); + } + + /** + * All UnitOfWork operations are batched and executed together on commit only. + */ + @Override + public void commit() { + if (context == null || context.size() == 0) { + return; + } + LOGGER.info("Commit started"); + if (context.containsKey(IUnitOfWork.INSERT)) { + commitInsert(); + } + + if (context.containsKey(IUnitOfWork.MODIFY)) { + commitModify(); + } + if (context.containsKey(IUnitOfWork.DELETE)) { + commitDelete(); + } + LOGGER.info("Commit finished."); + } + + private void commitInsert() { + List studentsToBeInserted = context.get(IUnitOfWork.INSERT); + for (Student student : studentsToBeInserted) { + LOGGER.info("Saving {} to database.", student.getName()); + studentDatabase.insert(student); + } + } + + private void commitModify() { + List modifiedStudents = context.get(IUnitOfWork.MODIFY); + for (Student student : modifiedStudents) { + LOGGER.info("Modifying {} to database.", student.getName()); + studentDatabase.modify(student); + } + } + + private void commitDelete() { + List deletedStudents = context.get(IUnitOfWork.DELETE); + for (Student student : deletedStudents) { + LOGGER.info("Deleting {} to database.", student.getName()); + studentDatabase.delete(student); + } + } +} diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java new file mode 100644 index 000000000..942db781f --- /dev/null +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +import org.junit.Test; + +import java.io.IOException; + +/** + * AppTest + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java new file mode 100644 index 000000000..ee63442a5 --- /dev/null +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java @@ -0,0 +1,147 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 Piyush Chaudhari + * + * 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.unitofwork; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +/** + * tests {@link StudentRepository} + */ +@RunWith(MockitoJUnitRunner.class) +public class StudentRepositoryTest { + private final Student student1 = new Student(1, "Ram", "street 9, cupertino"); + private final Student student2 = new Student(1, "Sham", "Z bridge, pune"); + + private Map> context; + @Mock + private StudentDatabase studentDatabase; + private StudentRepository studentRepository; + + @Before + public void setUp() throws Exception { + context = new HashMap<>(); + studentRepository = new StudentRepository(context, studentDatabase); + } + + @Test + public void shouldSaveNewStudentWithoutWritingToDb() throws Exception { + studentRepository.registerNew(student1); + studentRepository.registerNew(student2); + + assertEquals(2, context.get(IUnitOfWork.INSERT).size()); + verifyNoMoreInteractions(studentDatabase); + } + + @Test + public void shouldSaveDeletedStudentWithoutWritingToDb() throws Exception { + studentRepository.registerDeleted(student1); + studentRepository.registerDeleted(student2); + + assertEquals(2, context.get(IUnitOfWork.DELETE).size()); + verifyNoMoreInteractions(studentDatabase); + } + + @Test + public void shouldSaveModifiedStudentWithoutWritingToDb() throws Exception { + studentRepository.registerModified(student1); + studentRepository.registerModified(student2); + + assertEquals(2, context.get(IUnitOfWork.MODIFY).size()); + verifyNoMoreInteractions(studentDatabase); + } + + @Test + public void shouldSaveAllLocalChangesToDb() throws Exception { + context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); + context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); + context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + + studentRepository.commit(); + + verify(studentDatabase, times(1)).insert(student1); + verify(studentDatabase, times(1)).modify(student1); + verify(studentDatabase, times(1)).delete(student1); + } + + @Test + public void shouldNotWriteToDbIfContextIsNull() throws Exception { + StudentRepository studentRepository = new StudentRepository(null, studentDatabase); + + studentRepository.commit(); + + verifyNoMoreInteractions(studentDatabase); + } + + @Test + public void shouldNotWriteToDbIfNothingToCommit() throws Exception { + StudentRepository studentRepository = new StudentRepository(new HashMap<>(), studentDatabase); + + studentRepository.commit(); + + verifyZeroInteractions(studentDatabase); + } + + @Test + public void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() throws Exception { + context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); + context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + + studentRepository.commit(); + + verify(studentDatabase, never()).insert(student1); + } + + @Test + public void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() throws Exception { + context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); + context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + + studentRepository.commit(); + + verify(studentDatabase, never()).modify(student1); + } + + @Test + public void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() throws Exception { + context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); + context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); + + studentRepository.commit(); + + verify(studentDatabase, never()).delete(student1); + } +} \ No newline at end of file diff --git a/value-object/README.md b/value-object/README.md index a8e707b05..83223d8a2 100644 --- a/value-object/README.md +++ b/value-object/README.md @@ -3,7 +3,6 @@ layout: pattern title: Value Object folder: value-object permalink: /patterns/value-object/ -pumlid: LSZ13SCm20NGLTe1RExTXX2KECBOmfza_VRQszDxDnVBNJFiTG9pVOY2dteqdBdbqf3XK4ULqQbPFWmEklZcikjgXvV9W8Olwhn-e9ijjOpjKW4fv2zgHgypktq1 categories: Creational tags: - Java diff --git a/value-object/etc/value-object.urm.puml b/value-object/etc/value-object.urm.puml deleted file mode 100644 index 6149ead9b..000000000 --- a/value-object/etc/value-object.urm.puml +++ /dev/null @@ -1,22 +0,0 @@ -@startuml -package com.iluwatar.value.object { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class HeroStat { - - intelligence : int - - luck : int - - strength : int - - HeroStat(strength : int, intelligence : int, luck : int) - + equals(obj : Object) : boolean - + getIntelligence() : int - + getLuck() : int - + getStrength() : int - + hashCode() : int - + toString() : String - + valueOf(strength : int, intelligence : int, luck : int) : HeroStat {static} - } -} -@enduml \ No newline at end of file diff --git a/value-object/pom.xml b/value-object/pom.xml index 2db53f244..82fca9508 100644 --- a/value-object/pom.xml +++ b/value-object/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT value-object @@ -41,8 +41,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java index ff85e0e93..0274bc47f 100644 --- a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java +++ b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java @@ -37,7 +37,6 @@ public class HeroStat { // All constructors must be private. private HeroStat(int strength, int intelligence, int luck) { - super(); this.strength = strength; this.intelligence = intelligence; this.luck = luck; diff --git a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java index cd0b1354f..86dcb5be3 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.value.object; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Application test diff --git a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java index b7b65b6c6..f19382d4e 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java @@ -22,15 +22,13 @@ */ package com.iluwatar.value.object; +import com.google.common.testing.EqualsTester; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; - import static org.junit.Assert.assertThat; -import com.google.common.testing.EqualsTester; - -import org.junit.Test; - /** * Unit test for HeroStat. */ diff --git a/visitor/README.md b/visitor/README.md index 23ffc3af7..bda789a18 100644 --- a/visitor/README.md +++ b/visitor/README.md @@ -3,7 +3,6 @@ layout: pattern title: Visitor folder: visitor permalink: /patterns/visitor/ -pumlid: DSR14OGm20NGLhG0mtsxmSWeJa8oyD7sTo_xJczLgoqFIM_B1Spu43c_vLHSkMU8rs4GGwcZaxPy6UnqyyFR8Q6dRPC1SGlg7B_Gew4OJeBwVqdlPMPlNm00 categories: Behavioral tags: - Java diff --git a/visitor/etc/visitor.urm.puml b/visitor/etc/visitor.urm.puml deleted file mode 100644 index 36a67b415..000000000 --- a/visitor/etc/visitor.urm.puml +++ /dev/null @@ -1,60 +0,0 @@ -@startuml -package com.iluwatar.visitor { - class App { - + App() - + main(args : String[]) {static} - } - class Commander { - + Commander(children : Unit[]) - + accept(visitor : UnitVisitor) - + toString() : String - } - class CommanderVisitor { - - LOGGER : Logger {static} - + CommanderVisitor() - + visitCommander(commander : Commander) - + visitSergeant(sergeant : Sergeant) - + visitSoldier(soldier : Soldier) - } - class Sergeant { - + Sergeant(children : Unit[]) - + accept(visitor : UnitVisitor) - + toString() : String - } - class SergeantVisitor { - - LOGGER : Logger {static} - + SergeantVisitor() - + visitCommander(commander : Commander) - + visitSergeant(sergeant : Sergeant) - + visitSoldier(soldier : Soldier) - } - class Soldier { - + Soldier(children : Unit[]) - + accept(visitor : UnitVisitor) - + toString() : String - } - class SoldierVisitor { - - LOGGER : Logger {static} - + SoldierVisitor() - + visitCommander(commander : Commander) - + visitSergeant(sergeant : Sergeant) - + visitSoldier(soldier : Soldier) - } - abstract class Unit { - - children : Unit[] - + Unit(children : Unit[]) - + accept(visitor : UnitVisitor) - } - interface UnitVisitor { - + visitCommander(Commander) {abstract} - + visitSergeant(Sergeant) {abstract} - + visitSoldier(Soldier) {abstract} - } -} -Commander --|> Unit -CommanderVisitor ..|> UnitVisitor -Sergeant --|> Unit -SergeantVisitor ..|> UnitVisitor -Soldier --|> Unit -SoldierVisitor ..|> UnitVisitor -@enduml \ No newline at end of file diff --git a/visitor/pom.xml b/visitor/pom.xml index 7105f6ba7..01f0d4143 100644 --- a/visitor/pom.xml +++ b/visitor/pom.xml @@ -29,13 +29,18 @@ com.iluwatar java-design-patterns - 1.17.0-SNAPSHOT + 1.19.0-SNAPSHOT visitor - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java index 23c9bb48f..0fc97cc56 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -22,7 +22,7 @@ */ package com.iluwatar.visitor; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java index ab8470512..57fe19397 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -22,15 +22,16 @@ */ package com.iluwatar.visitor; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.function.Function; + import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import java.util.Arrays; -import java.util.function.Function; -import org.junit.Test; - /** * Date: 12/30/15 - 18:59 PM * Test related to Units diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index ba6705b23..68f4681c6 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -22,19 +22,20 @@ */ package com.iluwatar.visitor; -import static org.junit.Assert.assertEquals; - import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import java.util.Optional; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Date: 12/30/15 - 18:59 PM * Test case for Visitor Pattern @@ -45,12 +46,12 @@ public abstract class VisitorTest { private InMemoryAppender appender; - @Before + @BeforeEach public void setUp() { appender = new InMemoryAppender(); } - @After + @AfterEach public void tearDown() { appender.stop(); }