diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index 85215a021..54b157df6 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT abstract-document diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index e3129f6f0..d37159409 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT abstract-factory 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 82fd8acff..b6fca8b23 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -28,6 +28,9 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; +/** + * Test for abstract factory + */ public class AbstractFactoryTest { private App app = new App(); diff --git a/adapter/pom.xml b/adapter/pom.xml index 83462f28c..8cf754618 100644 --- a/adapter/pom.xml +++ b/adapter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT adapter diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml index 64b27f12d..477ce00c8 100644 --- a/aggregator-microservices/aggregator-service/pom.xml +++ b/aggregator-microservices/aggregator-service/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java index 2c14774d5..c43112c2e 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java @@ -25,6 +25,9 @@ package com.iluwatar.aggregator.microservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +/** + * Spring Boot EntryPoint Class + */ @SpringBootApplication public class App { 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 f44aa2044..2955f6781 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,18 @@ */ 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.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - +/** + * Test Aggregation of domain objects + */ public class AggregatorTest { @InjectMocks @@ -64,4 +67,4 @@ public class AggregatorTest { assertEquals(inventories, testProduct.getProductInventories()); } -} \ No newline at end of file +} diff --git a/aggregator-microservices/information-microservice/pom.xml b/aggregator-microservices/information-microservice/pom.xml index 3cb68099b..234daa25d 100644 --- a/aggregator-microservices/information-microservice/pom.xml +++ b/aggregator-microservices/information-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 diff --git a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java b/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java index ff020585c..63b6fb9d5 100644 --- a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java +++ b/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java @@ -26,6 +26,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +/** + * Controller providing endpoints to retrieve information about products + */ @RestController public class InformationController { 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 12d59aee6..127dd3956 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 @@ -25,6 +25,9 @@ package com.iluwatar.information.microservice; import org.junit.Assert; import org.junit.Test; +/** + * Test for Information Rest Controller + */ public class InformationControllerTest { @Test @@ -36,4 +39,4 @@ public class InformationControllerTest { Assert.assertEquals("The Product Title.", title); } -} \ No newline at end of file +} diff --git a/aggregator-microservices/inventory-microservice/pom.xml b/aggregator-microservices/inventory-microservice/pom.xml index 027105e7f..bdd96eec9 100644 --- a/aggregator-microservices/inventory-microservice/pom.xml +++ b/aggregator-microservices/inventory-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 diff --git a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java b/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java index 987ab0b3d..e6b2eca80 100644 --- a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java +++ b/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java @@ -26,6 +26,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +/** + * Controller providing endpoints to retrieve product inventories + */ @RestController public class InventoryController { 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 b461461d3..b04370fba 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 @@ -25,8 +25,10 @@ package com.iluwatar.inventory.microservice; import org.junit.Assert; import org.junit.Test; +/** + * Test Inventory Rest Controller + */ public class InventoryControllerTest { - @Test public void testGetProductInventories() throws Exception { InventoryController inventoryController = new InventoryController(); @@ -35,4 +37,4 @@ public class InventoryControllerTest { Assert.assertEquals(5, numberOfInventories); } -} \ No newline at end of file +} diff --git a/aggregator-microservices/pom.xml b/aggregator-microservices/pom.xml index a38975177..e08ee58f8 100644 --- a/aggregator-microservices/pom.xml +++ b/aggregator-microservices/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 aggregator-microservices diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml index 3bd2392fa..e36b09fd4 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.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 api-gateway-service diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java index 10f8625c5..ebabfe839 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -35,7 +35,7 @@ import java.io.IOException; * An adapter to communicate with the Image microservice */ @Component -public class ImageClientImpl implements ImageClient{ +public class ImageClientImpl implements ImageClient { /** * Makes a simple HTTP Get request to the Image microservice * @return The path to the image diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java index aa2686845..87f44761c 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -35,7 +35,7 @@ import java.io.IOException; * An adapter to communicate with the Price microservice */ @Component -public class PriceClientImpl implements PriceClient{ +public class PriceClientImpl implements PriceClient { /** * Makes a simple HTTP Get request to the Price microservice * @return The price of the product 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 fe8e76db4..6a79e5d00 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,18 @@ */ 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.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - +/** + * Test API Gateway Pattern + */ public class ApiGatewayTest { @InjectMocks diff --git a/api-gateway/image-microservice/pom.xml b/api-gateway/image-microservice/pom.xml index d42b31933..b9430ff69 100644 --- a/api-gateway/image-microservice/pom.xml +++ b/api-gateway/image-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 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 3f4154b58..1b934014a 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 @@ -25,6 +25,9 @@ package com.iluwatar.image.microservice; import org.junit.Assert; import org.junit.Test; +/** + * Test for Image Rest Controller + */ public class ImageControllerTest { @Test public void testGetImagePath() { diff --git a/api-gateway/pom.xml b/api-gateway/pom.xml index de2b3f099..7fdc54f8a 100644 --- a/api-gateway/pom.xml +++ b/api-gateway/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 api-gateway diff --git a/api-gateway/price-microservice/pom.xml b/api-gateway/price-microservice/pom.xml index 8a9a6f379..68dc75640 100644 --- a/api-gateway/price-microservice/pom.xml +++ b/api-gateway/price-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 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 634a60b04..b1fe66d42 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 @@ -25,6 +25,10 @@ package com.iluwatar.price.microservice; import org.junit.Assert; import org.junit.Test; + +/** + * Test for Price Rest Controller + */ public class PriceControllerTest { @Test public void testgetPrice() { diff --git a/async-method-invocation/pom.xml b/async-method-invocation/pom.xml index dc5b64404..1dc9a6b73 100644 --- a/async-method-invocation/pom.xml +++ b/async-method-invocation/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT async-method-invocation diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java index 3fa99cc27..f7fd9ab61 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java @@ -25,8 +25,8 @@ package com.iluwatar.async.method.invocation; import java.util.concurrent.ExecutionException; /** - * * AsyncResult interface + * @param parameter returned when getValue is invoked */ public interface AsyncResult { diff --git a/balking/README.md b/balking/README.md new file mode 100644 index 000000000..1ca7ccfb1 --- /dev/null +++ b/balking/README.md @@ -0,0 +1,27 @@ +--- +layout: pattern +title: Balking +folder: balking +permalink: /patterns/balking/ +categories: Concurrency +tags: + - Java + - Difficulty-Beginner +--- + +## Intent +Balking Pattern is used to prevent an object from executing certain code if it is an +incomplete or inappropriate state + +![alt text](./etc/balking.png "Balking") + +## 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 +but for an unknown amount of time + +## Related patterns +* Guarded Suspendion Pattern +* Double Checked Locking Pattern \ No newline at end of file diff --git a/balking/etc/balking.png b/balking/etc/balking.png new file mode 100644 index 000000000..f409eaacb Binary files /dev/null and b/balking/etc/balking.png differ diff --git a/balking/etc/balking.ucls b/balking/etc/balking.ucls new file mode 100644 index 000000000..e750f888a --- /dev/null +++ b/balking/etc/balking.ucls @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/balking/etc/balking.urm.puml b/balking/etc/balking.urm.puml new file mode 100644 index 000000000..b0296b925 --- /dev/null +++ b/balking/etc/balking.urm.puml @@ -0,0 +1,24 @@ +@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 new file mode 100644 index 000000000..2e27d9332 --- /dev/null +++ b/balking/pom.xml @@ -0,0 +1,46 @@ + + + + + java-design-patterns + com.iluwatar + 1.16.0-SNAPSHOT + + 4.0.0 + + balking + + + junit + junit + test + + + + + \ No newline at end of file diff --git a/balking/src/main/java/com/iluwatar/balking/App.java b/balking/src/main/java/com/iluwatar/balking/App.java new file mode 100644 index 000000000..47b10cd46 --- /dev/null +++ b/balking/src/main/java/com/iluwatar/balking/App.java @@ -0,0 +1,65 @@ +/** + * 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.balking; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * In Balking Design Pattern if an object’s method is invoked when it is in an inappropriate state, + * then the method will return without doing anything. Objects that use this pattern are generally only in a + * state that is prone to balking temporarily but for an unknown amount of time + * + * In this example implementation WashingMachine is an object that has two states + * in which it can be: ENABLED and WASHING. If the machine is ENABLED + * the state is changed into WASHING that any other thread can't invoke this action on this and then do the job. + * On the other hand if it have been already washing and any other thread execute wash() + * it can't do that once again and returns doing nothing. + */ + +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * @param args the command line arguments - not used + */ + public static void main(String... args) { + final WashingMachine washingMachine = new WashingMachine(); + ExecutorService executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + } + } + +} diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java new file mode 100644 index 000000000..e4f1259ad --- /dev/null +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java @@ -0,0 +1,76 @@ +/** + * 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.balking; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Washing machine class + */ +public class WashingMachine { + + private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class); + + private WashingMachineState washingMachineState; + + public WashingMachine() { + washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + /** + * Method responsible for washing + * if the object is in appropriate state + */ + public void wash() { + synchronized (this) { + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState()); + if (washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("ERROR: Cannot wash if the machine has been already washing!"); + return; + } + washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + try { + Thread.sleep(50); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + endOfWashing(); + } + + /** + * Method responsible of ending the washing + * by changing machine state + */ + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } + +} diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java new file mode 100644 index 000000000..40a5b2f38 --- /dev/null +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java @@ -0,0 +1,32 @@ +/** + * 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.balking; + +/** + * WashingMachineState enum describes in which state machine is, + * it can be enabled and ready to work as well as during washing + */ + +public enum WashingMachineState { + ENABLED, WASHING +} diff --git a/balking/src/test/java/com/iluwatar/balking/AppTest.java b/balking/src/test/java/com/iluwatar/balking/AppTest.java new file mode 100644 index 000000000..df104b901 --- /dev/null +++ b/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -0,0 +1,39 @@ +/** + * 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.balking; + +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void main() throws Exception { + String[] args = {}; + App.main(args); + } + +} \ No newline at end of file diff --git a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java new file mode 100644 index 000000000..ecf81f409 --- /dev/null +++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -0,0 +1,65 @@ +/** + * 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.balking; + +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +/** + * Tests for {@link WashingMachine} + */ +public class WashingMachineTest { + + private volatile WashingMachineState machineStateGlobal; + + @Test + public void wash() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.execute(washingMachine::wash); + executorService.execute(() -> { + washingMachine.wash(); + machineStateGlobal = washingMachine.getWashingMachineState(); + }); + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + assertEquals(WashingMachineState.WASHING, machineStateGlobal); + } + + @Test + public void endOfWashing() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + washingMachine.wash(); + assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState()); + } + +} \ No newline at end of file diff --git a/bridge/pom.xml b/bridge/pom.xml index ec04ff395..7c60f8ef8 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT bridge diff --git a/builder/pom.xml b/builder/pom.xml index 305de70bd..806d61b0a 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT builder diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index d5fde8ea3..6ac3d9f4f 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT business-delegate diff --git a/caching/pom.xml b/caching/pom.xml index 6d866eb03..6ec90234d 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT caching diff --git a/callback/pom.xml b/callback/pom.xml index 2b8d1fec6..a64ddac51 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT callback diff --git a/chain/pom.xml b/chain/pom.xml index 81aaf7e1f..7b283b012 100644 --- a/chain/pom.xml +++ b/chain/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT chain diff --git a/checkstyle.xml b/checkstyle.xml index 46b1aa354..37db7e711 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -32,10 +32,10 @@ Source = https://github.com/checkstyle/checkstyle/tree/master/src/main/resources Checkstyle configurartion that checks the Google coding conventions from: - + - Google Java Style https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html - + Checkstyle is very configurable. Be sure to read the documentation at http://checkstyle.sf.net (or in your downloaded distribution). @@ -44,12 +44,12 @@ To completely disable a check, just comment it out or delete it from the file. Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov. - + --> - + @@ -77,7 +77,6 @@ - @@ -120,7 +119,7 @@ - + @@ -185,6 +184,10 @@ + + + + com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT command diff --git a/composite/pom.xml b/composite/pom.xml index 107502963..f3b1a38b5 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT composite diff --git a/converter/README.md b/converter/README.md new file mode 100644 index 000000000..190ae8bfc --- /dev/null +++ b/converter/README.md @@ -0,0 +1,29 @@ +--- +layout: pattern +title: Converter +folder: converter +permalink: /patterns/converter/ +categories: +tags: + - Java + - Difficulty-Beginner +--- + +## Intent +The purpose of the Converter Pattern is to provide a generic, common way of bidirectional +conversion between corresponding types, allowing a clean implementation in which the types do not +need to be aware of each other. Moreover, the Converter Pattern introduces bidirectional collection +mapping, reducing a boilerplate code to minimum. + +![alt text](./etc/converter.png "Converter Pattern") + +## Applicability +Use the Converter Pattern in the following situations: + +* When you have types that logically correspond which other and you need to convert entities between them +* When you want to provide different ways of types conversions depending on a context +* Whenever you introduce a DTO (Data transfer object), you will probably need to convert it into the domain equivalence + +## Credits + +* [Converter](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) diff --git a/converter/etc/Converter.png b/converter/etc/Converter.png new file mode 100644 index 000000000..01435ef5a Binary files /dev/null and b/converter/etc/Converter.png differ diff --git a/converter/etc/Converter.ucls b/converter/etc/Converter.ucls new file mode 100644 index 000000000..368657430 --- /dev/null +++ b/converter/etc/Converter.ucls @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/converter/etc/converter.urm.puml b/converter/etc/converter.urm.puml new file mode 100644 index 000000000..5e0acf191 --- /dev/null +++ b/converter/etc/converter.urm.puml @@ -0,0 +1,49 @@ +@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 new file mode 100644 index 000000000..569899f1d --- /dev/null +++ b/converter/pom.xml @@ -0,0 +1,49 @@ + + + + + java-design-patterns + com.iluwatar + 1.16.0-SNAPSHOT + + 4.0.0 + + + junit + junit + test + + + com.google.guava + guava + + + converter + + + diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java new file mode 100644 index 000000000..fbae0309d --- /dev/null +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -0,0 +1,63 @@ +/** + * 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. + */ +package com.iluwatar.converter; + + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.List; + +/** + * The Converter pattern is a behavioral design pattern which allows a common way of bidirectional + * conversion between corresponding types (e.g. DTO and domain representations of the logically + * isomorphic types). Moreover, the pattern introduces a common way of converting a collection of + * objects between types. + */ +public class App { + /** + * Program entry point + * + * @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())); + + UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); + User user = userConverter.convertFromDto(dtoUser); + System.out.println("Entity converted from DTO:" + user); + + ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); + System.out.println("Domain entities:"); + users.forEach(System.out::println); + + System.out.println("DTO entities converted from domain:"); + List dtoEntities = userConverter.createFromEntities(users); + dtoEntities.forEach(System.out::println); + + } +} diff --git a/converter/src/main/java/com/iluwatar/converter/Converter.java b/converter/src/main/java/com/iluwatar/converter/Converter.java new file mode 100644 index 000000000..eeabc4102 --- /dev/null +++ b/converter/src/main/java/com/iluwatar/converter/Converter.java @@ -0,0 +1,86 @@ +/** + * 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. + */ + +package com.iluwatar.converter; + +import java.util.Collection; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Generic converter, thanks to Java8 features not only provides a way of generic bidirectional + * conversion between coresponding types, but also a common way of converting a collection of objects + * of the same type, reducing boilerplate code to the absolute minimum. + * @param DTO representation's type + * @param Domain representation's type + */ +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + /** + * @param fromDto Function that converts given dto entity into the domain entity. + * @param fromEntity Function that converts given domain entity into the dto entity. + */ + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + /** + * @param userDto DTO entity + * @return The domain representation - the result of the converting function application on dto entity. + */ + public final U convertFromDto(final T userDto) { + return fromDto.apply(userDto); + } + + /** + * @param user domain entity + * @return The DTO representation - the result of the converting function application on domain entity. + */ + public final T convertFromEntity(final U user) { + return fromEntity.apply(user); + } + + /** + * @param dtoUsers collection of DTO entities + * @return List of domain representation of provided entities retrieved by + * mapping each of them with the convertion function + */ + public final List createFromDtos(final Collection dtoUsers) { + return dtoUsers.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + /** + * @param users collection of domain entities + * @return List of domain representation of provided entities retrieved by + * mapping each of them with the convertion function + */ + public final List createFromEntities(final Collection users) { + return users.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } + +} diff --git a/converter/src/main/java/com/iluwatar/converter/User.java b/converter/src/main/java/com/iluwatar/converter/User.java new file mode 100644 index 000000000..62903a931 --- /dev/null +++ b/converter/src/main/java/com/iluwatar/converter/User.java @@ -0,0 +1,86 @@ +/** + * 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. + */ + +package com.iluwatar.converter; + +import java.util.Objects; + +/** + * User class + */ +public class User { + private String firstName; + private String lastName; + private boolean isActive; + private String userId; + + /** + * @param firstName user's first name + * @param lastName user's last name + * @param isActive flag indicating whether the user is active + * @param userId user's identificator + */ + public User(String firstName, String lastName, boolean isActive, String userId) { + this.firstName = firstName; + this.lastName = lastName; + this.isActive = isActive; + this.userId = userId; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public boolean isActive() { + return isActive; + } + + public String getUserId() { + return userId; + } + + @Override public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects + .equals(lastName, user.lastName) && Objects.equals(userId, user.userId); + } + + @Override public int hashCode() { + return Objects.hash(firstName, lastName, isActive, userId); + } + + @Override public String toString() { + return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + + ", isActive=" + isActive + ", userId='" + userId + '\'' + '}'; + } +} diff --git a/converter/src/main/java/com/iluwatar/converter/UserConverter.java b/converter/src/main/java/com/iluwatar/converter/UserConverter.java new file mode 100644 index 000000000..9ef1d03c2 --- /dev/null +++ b/converter/src/main/java/com/iluwatar/converter/UserConverter.java @@ -0,0 +1,40 @@ +/** + * 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. + */ + +package com.iluwatar.converter; + +/** + * Example implementation of the simple User converter. + */ +public class UserConverter extends Converter { + + /** + * Constructor. + */ + public UserConverter() { + super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + userDto.getEmail()), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getUserId())); + } +} diff --git a/converter/src/main/java/com/iluwatar/converter/UserDto.java b/converter/src/main/java/com/iluwatar/converter/UserDto.java new file mode 100644 index 000000000..8eacc0b3b --- /dev/null +++ b/converter/src/main/java/com/iluwatar/converter/UserDto.java @@ -0,0 +1,88 @@ +/** + * 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. + */ + +package com.iluwatar.converter; + + +import java.util.Objects; + +/** + * User DTO class + */ +public class UserDto { + + private String firstName; + private String lastName; + private boolean isActive; + private String email; + + /** + * @param firstName user's first name + * @param lastName user's last name + * @param isActive flag indicating whether the user is active + * @param email user's email address + */ + public UserDto(String firstName, String lastName, boolean isActive, String email) { + this.firstName = firstName; + this.lastName = lastName; + this.isActive = isActive; + this.email = email; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public boolean isActive() { + return isActive; + } + + public String getEmail() { + return email; + } + + @Override public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserDto userDto = (UserDto) o; + return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects + .equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email); + } + + @Override public int hashCode() { + return Objects.hash(firstName, lastName, isActive, email); + } + + @Override public String toString() { + return "UserDto{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + + ", isActive=" + isActive + ", email='" + email + '\'' + '}'; + } +} diff --git a/converter/src/test/java/com/iluwatar/converter/AppTest.java b/converter/src/test/java/com/iluwatar/converter/AppTest.java new file mode 100644 index 000000000..091fbe2ca --- /dev/null +++ b/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -0,0 +1,38 @@ +/** + * 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. + */ +package com.iluwatar.converter; + +import org.junit.Test; + +/** + * App running test + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java new file mode 100644 index 000000000..9fc2e2a0c --- /dev/null +++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.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.converter; + +import com.google.common.collect.Lists; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static junit.framework.TestCase.assertEquals; + +/** + * Tests for {@link Converter} + */ +public class ConverterTest { + + private UserConverter userConverter = new UserConverter(); + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test public void testConversionsStartingFromDomain() { + User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); + User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); + assertEquals(u1, u2); + } + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test public void testConversionsStartingFromDto() { + UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); + UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); + assertEquals(u1, u2); + } + + /** + * 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() { + Converter converter = new Converter<>( + userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + String.valueOf(new Random().nextInt())), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); + User u1 = new User("John", "Doe", false, "12324"); + UserDto userDto = converter.convertFromEntity(u1); + assertEquals(userDto.getEmail(), "johndoe@whatever.com"); + } + + /** + * 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() { + 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)); + assertEquals(fromDtos, users); + } +} diff --git a/dao/pom.xml b/dao/pom.xml index 374a1c14c..b7de27bd4 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT dao diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java index e81e415fe..cce967dc8 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java @@ -22,13 +22,16 @@ */ package com.iluwatar.dao; +/** + * Customer Schema SQL Class + */ public final class CustomerSchemaSql { private CustomerSchemaSql() {} - public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + "LNAME VARCHAR(100))"; - + public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS"; - + } diff --git a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java index a0f9035ab..8122c369f 100644 --- a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java +++ b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -29,6 +29,9 @@ import static org.junit.Assert.assertNotEquals; import org.junit.Before; import org.junit.Test; +/** + * Tests {@link Customer}. + */ public class CustomerTest { private Customer customer; diff --git a/data-bus/.gitignore b/data-bus/.gitignore new file mode 100644 index 000000000..ea8c4bf7f --- /dev/null +++ b/data-bus/.gitignore @@ -0,0 +1 @@ +/target diff --git a/data-bus/README.md b/data-bus/README.md new file mode 100644 index 000000000..257192e25 --- /dev/null +++ b/data-bus/README.md @@ -0,0 +1,33 @@ +--- +layout: pattern +title: Data Bus +folder: data-bus +permalink: /patterns/data-bus/ + +categories: Architectural +tags: + - Java + - Difficulty-Intermediate +--- + +## Intent + +Allows send of messages/events between components of an application +without them needing to know about each other. They only need to know +about the type of the message/event being sent. + +![data bus pattern uml diagram](./etc/data-bus.urm.png "Data Bus pattern") + +## Applicability +Use Data Bus pattern when + +* you want your components to decide themselves which messages/events they want to receive +* you want to have many-to-many communication +* you want your components to know nothing about each other + +## Related Patterns +Data Bus is similar to + +* Mediator pattern with Data Bus Members deciding for themselves if they want to accept any given message +* Observer pattern but supporting many-to-many communication +* Publish/Subscribe pattern with the Data Bus decoupling the publisher and the subscriber diff --git a/data-bus/etc/data-bus.urm.png b/data-bus/etc/data-bus.urm.png new file mode 100644 index 000000000..8bd214817 Binary files /dev/null and b/data-bus/etc/data-bus.urm.png differ diff --git a/data-bus/etc/data-bus.urm.puml b/data-bus/etc/data-bus.urm.puml new file mode 100644 index 000000000..9ca0ab602 --- /dev/null +++ b/data-bus/etc/data-bus.urm.puml @@ -0,0 +1,77 @@ +@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 new file mode 100644 index 000000000..68065f00a --- /dev/null +++ b/data-bus/pom.xml @@ -0,0 +1,51 @@ + + + + 4.0.0 + + 1.16.14 + + + com.iluwatar + java-design-patterns + 1.16.0-SNAPSHOT + + data-bus + + + junit + junit + test + + + org.mockito + mockito-core + test + + + diff --git a/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java new file mode 100644 index 000000000..5ba6653de --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java @@ -0,0 +1,45 @@ +/* +The MIT License (MIT) + +Copyright (c) 2016 Paul Campbell + +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.databus; + +/** + * Base for data to send via the Data-Bus. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class AbstractDataType implements DataType { + + private DataBus dataBus; + + @Override + public DataBus getDataBus() { + return dataBus; + } + + @Override + public void setDataBus(DataBus dataBus) { + this.dataBus = dataBus; + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/App.java b/data-bus/src/main/java/com/iluwatar/databus/App.java new file mode 100644 index 000000000..748bb6af0 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/App.java @@ -0,0 +1,79 @@ +/** + * 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. + */ + +package com.iluwatar.databus; + +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import com.iluwatar.databus.data.StoppingData; +import com.iluwatar.databus.members.MessageCollectorMember; +import com.iluwatar.databus.members.StatusMember; + +import java.time.LocalDateTime; + +/** + * The Data Bus pattern + *

+ *

{@see http://wiki.c2.com/?DataBusPattern}

+ *

+ *

The Data-Bus pattern provides a method where different parts of an application may + * pass messages between each other without needing to be aware of the other's existence.

+ *

Similar to the {@code ObserverPattern}, members register themselves with the {@link DataBus} + * and may then receive each piece of data that is published to the Data-Bus. The member + * may react to any given message or not.

+ *

It allows for Many-to-Many distribution of data, as there may be any number of + * publishers to a Data-Bus, and any number of members receiving the data. All members + * will receive the same data, the order each receives a given piece of data, is an + * implementation detail.

+ *

Members may unsubscribe from the Data-Bus to stop receiving data.

+ *

This example of the pattern implements a Synchronous Data-Bus, meaning that + * when data is published to the Data-Bus, the publish method will not return until + * all members have received the data and returned.

+ *

The {@link DataBus} class is a Singleton.

+ *

Members of the Data-Bus must implement the {@link Member} interface.

+ *

Data to be published via the Data-Bus must implement the {@link DataType} interface.

+ *

The {@code data} package contains example {@link DataType} implementations.

+ *

The {@code members} package contains example {@link Member} implementations.

+ *

The {@link StatusMember} demonstrates using the DataBus to publish a message + * to the Data-Bus when it receives a message.

+ * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +class App { + + public static void main(String[] args) { + final DataBus bus = DataBus.getInstance(); + bus.subscribe(new StatusMember(1)); + bus.subscribe(new StatusMember(2)); + final MessageCollectorMember foo = new MessageCollectorMember("Foo"); + final MessageCollectorMember bar = new MessageCollectorMember("Bar"); + bus.subscribe(foo); + bus.publish(StartingData.of(LocalDateTime.now())); + bus.publish(MessageData.of("Only Foo should see this")); + bus.subscribe(bar); + bus.publish(MessageData.of("Foo and Bar should see this")); + bus.unsubscribe(foo); + bus.publish(MessageData.of("Only Bar should see this")); + bus.publish(StoppingData.of(LocalDateTime.now())); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataBus.java b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java new file mode 100644 index 000000000..edaefe623 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java @@ -0,0 +1,73 @@ +/** + * 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. + */ + +package com.iluwatar.databus; + +import java.util.HashSet; +import java.util.Set; + +/** + * The Data-Bus implementation. + * + *

This implementation uses a Singleton.

+ * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class DataBus { + + private static final DataBus INSTANCE = new DataBus(); + + private final Set listeners = new HashSet<>(); + + public static DataBus getInstance() { + return INSTANCE; + } + + /** + * Register a member with the data-bus to start receiving events. + * + * @param member The member to register + */ + public void subscribe(final Member member) { + this.listeners.add(member); + } + + /** + * Deregister a member to stop receiving events. + * + * @param member The member to deregister + */ + public void unsubscribe(final Member member) { + this.listeners.remove(member); + } + + /** + * Publish and event to all members. + * + * @param event The event + */ + public void publish(final DataType event) { + event.setDataBus(this); + listeners.forEach(listener -> listener.accept(event)); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataType.java b/data-bus/src/main/java/com/iluwatar/databus/DataType.java new file mode 100644 index 000000000..e5729c19d --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/DataType.java @@ -0,0 +1,48 @@ +/* +The MIT License (MIT) + +Copyright (c) 2016 Paul Campbell + +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.databus; + +/** + * Events are sent via the Data-Bus. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ + +public interface DataType { + + /** + * Returns the data-bus the event is being sent on. + * + * @return The data-bus + */ + DataBus getDataBus(); + + /** + * Set the data-bus the event will be sent on. + * + * @param dataBus The data-bus + */ + void setDataBus(DataBus dataBus); +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/Member.java b/data-bus/src/main/java/com/iluwatar/databus/Member.java new file mode 100644 index 000000000..d5ecb0152 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/Member.java @@ -0,0 +1,37 @@ +/* +The MIT License (MIT) + +Copyright (c) 2016 Paul Campbell + +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.databus; + +import java.util.function.Consumer; + +/** + * Members receive events from the Data-Bus. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public interface Member extends Consumer { + + void accept(DataType event); +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java b/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java new file mode 100644 index 000000000..ac541cf20 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java @@ -0,0 +1,49 @@ +/** + * 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. + */ + +package com.iluwatar.databus.data; + +import com.iluwatar.databus.AbstractDataType; +import com.iluwatar.databus.DataType; + +/** + * An event raised when a string message is sent. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class MessageData extends AbstractDataType { + + private final String message; + + public MessageData(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public static DataType of(final String message) { + return new MessageData(message); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java new file mode 100644 index 000000000..ac7391f1a --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java @@ -0,0 +1,51 @@ +/** + * 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. + */ + +package com.iluwatar.databus.data; + +import com.iluwatar.databus.AbstractDataType; +import com.iluwatar.databus.DataType; + +import java.time.LocalDateTime; + +/** + * An event raised when applications starts, containing the start time of the application. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StartingData extends AbstractDataType { + + private final LocalDateTime when; + + public StartingData(LocalDateTime when) { + this.when = when; + } + + public LocalDateTime getWhen() { + return when; + } + + public static DataType of(final LocalDateTime when) { + return new StartingData(when); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java new file mode 100644 index 000000000..976fdc4e9 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java @@ -0,0 +1,51 @@ +/** + * 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. + */ + +package com.iluwatar.databus.data; + +import com.iluwatar.databus.AbstractDataType; +import com.iluwatar.databus.DataType; + +import java.time.LocalDateTime; + +/** + * An event raised when applications stops, containing the stop time of the application. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StoppingData extends AbstractDataType { + + private final LocalDateTime when; + + public StoppingData(LocalDateTime when) { + this.when = when; + } + + public LocalDateTime getWhen() { + return when; + } + + public static DataType of(final LocalDateTime when) { + return new StoppingData(when); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java new file mode 100644 index 000000000..a8ee94ad5 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java @@ -0,0 +1,67 @@ +/** + * 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. + */ + +package com.iluwatar.databus.members; + +import com.iluwatar.databus.DataType; +import com.iluwatar.databus.Member; +import com.iluwatar.databus.data.MessageData; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +/** + * Receiver of Data-Bus events that collects the messages from each {@link MessageData}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class MessageCollectorMember implements Member { + + private static final Logger LOGGER = Logger.getLogger(MessageCollectorMember.class.getName()); + + private final String name; + + private List messages = new ArrayList<>(); + + public MessageCollectorMember(String name) { + this.name = name; + } + + @Override + public void accept(final DataType data) { + if (data instanceof MessageData) { + handleEvent((MessageData) data); + } + } + + private void handleEvent(MessageData data) { + LOGGER.info(String.format("%s sees message %s", name, data.getMessage())); + messages.add(data.getMessage()); + } + + public List getMessages() { + return Collections.unmodifiableList(messages); + } +} diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java new file mode 100644 index 000000000..803e2df20 --- /dev/null +++ b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java @@ -0,0 +1,82 @@ +/** + * 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. + */ + +package com.iluwatar.databus.members; + +import com.iluwatar.databus.DataType; +import com.iluwatar.databus.Member; +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import com.iluwatar.databus.data.StoppingData; + +import java.time.LocalDateTime; +import java.util.logging.Logger; + +/** + * Receiver of Data-Bus events. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StatusMember implements Member { + + private static final Logger LOGGER = Logger.getLogger(StatusMember.class.getName()); + + private final int id; + + private LocalDateTime started; + + private LocalDateTime stopped; + + public StatusMember(int id) { + this.id = id; + } + + @Override + public void accept(final DataType data) { + if (data instanceof StartingData) { + handleEvent((StartingData) data); + } else if (data instanceof StoppingData) { + handleEvent((StoppingData) data); + } + } + + private void handleEvent(StartingData data) { + started = data.getWhen(); + LOGGER.info(String.format("Receiver #%d sees application started at %s", id, started)); + } + + private void handleEvent(StoppingData data) { + stopped = data.getWhen(); + LOGGER.info(String.format("Receiver #%d sees application stopping at %s", id, stopped)); + LOGGER.info(String.format("Receiver #%d sending goodbye message", id)); + data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id))); + } + + public LocalDateTime getStarted() { + return started; + } + + public LocalDateTime getStopped() { + return stopped; + } +} diff --git a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java new file mode 100644 index 000000000..90c326ebf --- /dev/null +++ b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -0,0 +1,52 @@ +package com.iluwatar.databus; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.never; + +/** + * Tests for {@link DataBus}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class DataBusTest { + + @Mock + private Member member; + + @Mock + private DataType event; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void publishedEventIsReceivedBySubscribedMember() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + //when + dataBus.publish(event); + //then + then(member).should().accept(event); + } + + @Test + public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + dataBus.unsubscribe(member); + //when + dataBus.publish(event); + //then + then(member).should(never()).accept(event); + } + +} 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 new file mode 100644 index 000000000..96fc090ee --- /dev/null +++ b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -0,0 +1,40 @@ +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 java.time.LocalDateTime; + +/** + * Tests for {@link MessageCollectorMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class MessageCollectorMemberTest { + + @Test + public void collectMessageFromMessageData() { + //given + final String message = "message"; + final MessageData messageData = new MessageData(message); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(messageData); + //then + Assert.assertTrue(collector.getMessages().contains(message)); + } + + @Test + public void collectIgnoresMessageFromOtherDataTypes() { + //given + final StartingData startingData = new StartingData(LocalDateTime.now()); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(startingData); + //then + Assert.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 new file mode 100644 index 000000000..e5983dcea --- /dev/null +++ b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -0,0 +1,57 @@ +package com.iluwatar.databus.members; + +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 java.time.LocalDateTime; +import java.time.Month; + +/** + * Tests for {@link StatusMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StatusMemberTest { + + @Test + public void statusRecordsTheStartTime() { + //given + final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); + final StartingData startingData = new StartingData(startTime); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(startingData); + //then + Assert.assertEquals(startTime, statusMember.getStarted()); + } + + @Test + public void statusRecordsTheStopTime() { + //given + final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); + final StoppingData stoppingData = new StoppingData(stop); + stoppingData.setDataBus(DataBus.getInstance()); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(stoppingData); + //then + Assert.assertEquals(stop, statusMember.getStopped()); + } + + @Test + public void statusIgnoresMessageData() { + //given + final MessageData messageData = new MessageData("message"); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(messageData); + //then + Assert.assertNull(statusMember.getStarted()); + Assert.assertNull(statusMember.getStopped()); + } + +} diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index c23868a4e..878f02fed 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT data-mapper 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 0164533c8..d709833aa 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java @@ -21,6 +21,9 @@ package com.iluwatar.datamapper; import java.io.Serializable; +/** + * Class defining Student + */ public final class Student implements Serializable { private static final long serialVersionUID = 1L; @@ -32,7 +35,7 @@ public final class Student implements Serializable { /** * Use this constructor to create a Student with all details - * + * * @param studentId as unique student id * @param name as student name * @param grade as respective grade of student @@ -46,7 +49,7 @@ public final class Student implements Serializable { } /** - * + * * @return the student id */ public int getStudentId() { @@ -54,7 +57,7 @@ public final class Student implements Serializable { } /** - * + * * @param studentId as unique student id */ public void setStudentId(final int studentId) { @@ -62,7 +65,7 @@ public final class Student implements Serializable { } /** - * + * * @return name of student */ public String getName() { @@ -70,7 +73,7 @@ public final class Student implements Serializable { } /** - * + * * @param name as 'name' of student */ public void setName(final String name) { @@ -78,7 +81,7 @@ public final class Student implements Serializable { } /** - * + * * @return grade of student */ public char getGrade() { @@ -86,7 +89,7 @@ public final class Student implements Serializable { } /** - * + * * @param grade as 'grade of student' */ public void setGrade(final char grade) { @@ -94,7 +97,7 @@ public final class Student implements Serializable { } /** - * + * */ @Override public boolean equals(final Object inputObject) { @@ -120,7 +123,7 @@ public final class Student implements Serializable { } /** - * + * */ @Override public int hashCode() { @@ -130,7 +133,7 @@ public final class Student implements Serializable { } /** - * + * */ @Override public String toString() { diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java index 40f0c5c72..cb93f4697 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java @@ -20,6 +20,9 @@ package com.iluwatar.datamapper; import java.util.Optional; +/** + * Interface lists out the possible behaviour for all possible student mappers + */ public interface StudentDataMapper { Optional find(int studentId); diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java index 7ecd9e7f8..685a439ac 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java @@ -22,6 +22,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +/** + * Implementation of Actions on Students Data + */ public final class StudentDataMapperImpl implements StudentDataMapper { /* Note: Normally this would be in the form of an actual database */ 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 a3c0e46c1..ec35b21de 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -18,17 +18,21 @@ */ package com.iluwatar.datamapper; -import org.junit.Test; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +/** + * Tests {@link Student}. + */ public final class StudentTest { @Test /** * This API tests the equality behaviour of Student object * Object Equality should work as per logic defined in equals method - * + * * @throws Exception if any execution error during test */ public void testEquality() throws Exception { diff --git a/decorator/pom.xml b/decorator/pom.xml index 51684065c..5b6d24723 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT decorator diff --git a/delegation/pom.xml b/delegation/pom.xml index cf0349024..befd02a59 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java index 86b841a28..c54f611ee 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java @@ -22,6 +22,12 @@ */ package com.iluwatar.delegation.simple; +/** + * Delegator Class to delegate the implementation of the Printer. + * This ensures two things: + * - when the actual implementation of the Printer class changes the delegation will still be operational + * - the actual benefit is observed when there are more than one implementors and they share a delegation control + */ public class PrinterController implements Printer { private final Printer printer; 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 a8fae59e3..434d94baa 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -23,7 +23,9 @@ package com.iluwatar.delegation.simple; import org.junit.Test; - +/** + * Application Test Entry + */ public class AppTest { @Test 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 b27539def..fd99a30dd 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -22,22 +22,24 @@ */ 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 java.util.LinkedList; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - +/** + * Test for Delegation Pattern + */ public class DelegateTest { private InMemoryAppender appender; @@ -78,6 +80,9 @@ public class DelegateTest { assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); } + /** + * Logging Appender + */ private class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 603bb2c05..ccbbea9a2 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT dependency-injection diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java index 76d1cc1dd..b79bf3d40 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java @@ -30,6 +30,10 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; + +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index 0b0541b8f..7e19561de 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT double-checked-locking diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index b15e76f88..c87efc185 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT double-dispatch 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 5e9a001e7..3dc32905a 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -22,13 +22,14 @@ */ package com.iluwatar.doubledispatch; -import java.util.Objects; - import static org.junit.Assert.assertEquals; +import java.util.Objects; + /** * Date: 12/10/15 - 8:37 PM - * + * Test for Collision + * @param Type of GameObject * @author Jeroen Meulemeester */ public abstract class CollisionTest { diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index 3bf8c281b..276aecd0c 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT event-aggregator 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 ba7ecbc2d..a67272789 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,22 +22,22 @@ */ package com.iluwatar.event.aggregator; -import org.junit.Test; - -import java.util.Objects; -import java.util.function.Function; -import java.util.function.Supplier; - import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; +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 - * + * Tests for Event Emitter + * @param Type of Event Emitter * @author Jeroen Meulemeester */ public abstract class EventEmitterTest { @@ -115,7 +115,7 @@ public abstract class EventEmitterTest { // The observers should not have received any additional events after the week verifyNoMoreInteractions(observers); } - + /** * Go over every day of the month, and check if the event is emitted on the given day. Use an * event emitter without a default observer diff --git a/event-asynchronous/README.md b/event-asynchronous/README.md index ef35d0b38..4c26e0a3c 100644 --- a/event-asynchronous/README.md +++ b/event-asynchronous/README.md @@ -12,11 +12,12 @@ tags: ## Intent The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many -of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to:- -(1) Perform time-consuming tasks, such as downloads and database operations, "in the background," without interrupting your application. -(2) Execute multiple operations simultaneously, receiving notifications when each completes. -(3) Wait for resources to become available without stopping ("hanging") your application. -(4) Communicate with pending asynchronous operations using the familiar events-and-delegates model. +of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to: + +1. Perform time-consuming tasks, such as downloads and database operations, "in the background," without interrupting your application. +2. Execute multiple operations simultaneously, receiving notifications when each completes. +3. Wait for resources to become available without stopping ("hanging") your application. +4. Communicate with pending asynchronous operations using the familiar events-and-delegates model. ![alt text](./etc/event-asynchronous.png "Event-based Asynchronous") diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml index 9fecfa606..a10fec55d 100644 --- a/event-asynchronous/pom.xml +++ b/event-asynchronous/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT event-asynchronous diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java index 85edaa815..e7a5e75b6 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java @@ -16,6 +16,9 @@ */ package com.iluwatar.event.asynchronous; +/** + * Custom Exception Class for Non Existent Event + */ public class EventDoesNotExistException extends Exception { private static final long serialVersionUID = -3398463738273811509L; diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java index 296a312a3..bfb5d4f04 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java @@ -16,6 +16,10 @@ */ package com.iluwatar.event.asynchronous; +/** + * Events that fulfill the start stop and list out current status behaviour + * follow this interface + */ public interface IEvent { void start(); diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java index 3c930d935..7ca5cfc9a 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java @@ -16,6 +16,9 @@ */ package com.iluwatar.event.asynchronous; +/** + * Type of Exception raised when the Operation being invoked is Invalid + */ public class InvalidOperationException extends Exception { private static final long serialVersionUID = -6191545255213410803L; diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java index 7c9091a15..b11f1a335 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java @@ -16,6 +16,9 @@ */ package com.iluwatar.event.asynchronous; +/** + * Type of Exception raised when the Operation being invoked is Long Running + */ public class LongRunningEventException extends Exception { private static final long serialVersionUID = -483423544320148809L; diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java index 2b8f2221c..17b46fd88 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java @@ -16,6 +16,9 @@ */ package com.iluwatar.event.asynchronous; +/** + * Type of Exception raised when the max number of allowed events is exceeded + */ public class MaxNumOfEventsAllowedException extends Exception { private static final long serialVersionUID = -8430876973516292695L; diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java index be4ecf93b..7a37f7614 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java @@ -16,6 +16,9 @@ */ package com.iluwatar.event.asynchronous; +/** + * Interface with listener behaviour related to Thread Completion. + */ public interface ThreadCompleteListener { void completedEventHandler(final int eventId); } diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index 2ced1abda..f021f4023 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT event-driven-architecture diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java index e2b58cd49..3208e1edf 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java @@ -25,6 +25,7 @@ package com.iluwatar.eda.framework; /** * This interface can be implemented to handle different types of messages. * Every handler is responsible for a single of type message + * @param Handler can handle events of type E */ public interface Handler { @@ -35,4 +36,4 @@ public interface Handler { * @param event the {@link Event} object to be handled. */ void onEvent(E event); -} \ No newline at end of file +} diff --git a/execute-around/pom.xml b/execute-around/pom.xml index acc36b4b4..765b52846 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT execute-around diff --git a/facade/pom.xml b/facade/pom.xml index 0f1fa8688..a9a1ed226 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT facade diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index f356fc3b8..0fef94e84 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT factory-kit diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java index 96ce73a35..429728cbc 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java @@ -22,6 +22,9 @@ */ package com.iluwatar.factorykit; +/** + * Class representing Axe + */ public class Axe implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java index b9b2708c9..c655c3be8 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java @@ -22,6 +22,9 @@ */ package com.iluwatar.factorykit; +/** + * Class representing Bows + */ public class Bow implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java index 080007093..15ff8b246 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java @@ -21,7 +21,9 @@ * THE SOFTWARE. */ package com.iluwatar.factorykit; - +/** + * Class representing Spear + */ public class Spear implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java index 504ddb397..42ab53799 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java @@ -21,7 +21,9 @@ * THE SOFTWARE. */ package com.iluwatar.factorykit; - +/** + * Class representing Swords + */ public class Sword implements Weapon { @Override public String toString() { 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 add378296..4d8691ef0 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 @@ -25,6 +25,9 @@ package com.iluwatar.factorykit.app; import com.iluwatar.factorykit.App; import org.junit.Test; +/** + * Application Test Entrypoint + */ public class AppTest { @Test 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 da39caa8f..3f732546d 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 @@ -1,4 +1,4 @@ -/** + /** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * @@ -22,12 +22,19 @@ */ package com.iluwatar.factorykit.factorykit; -import com.iluwatar.factorykit.*; -import org.junit.Before; -import org.junit.Test; - 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; +/** + * Test Factory Kit Pattern + */ public class FactoryKitTest { private WeaponFactory factory; diff --git a/factory-method/pom.xml b/factory-method/pom.xml index d6359ff03..8cc506c62 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT factory-method diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index e2635f228..7fbb085f2 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 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 def53b97c..846b46bcf 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,16 +23,18 @@ package com.iluwatar.featuretoggle.pattern.propertiesversion; -import com.iluwatar.featuretoggle.pattern.Service; -import com.iluwatar.featuretoggle.user.User; -import org.junit.Test; - -import java.util.Properties; - 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 java.util.Properties; +import org.junit.Test; + +/** + * Test Properties Toggle + */ public class PropertiesFeatureToggleVersionTest { @Test(expected = IllegalArgumentException.class) @@ -66,4 +68,4 @@ public class PropertiesFeatureToggleVersionTest { final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); assertEquals("Welcome to the application.", welcomeMessage); } -} \ No newline at end of file +} 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 6c33b260c..3966032d5 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,15 +22,18 @@ */ 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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +/** + * Test Tiered Feature Toggle + */ public class TieredFeatureToggleVersionTest { final User paidUser = new User("Jamie Coder"); @@ -61,4 +64,4 @@ public class TieredFeatureToggleVersionTest { public void testIsEnhancedAlwaysTrueAsTiered() throws Exception { assertTrue(service.isEnhanced()); } -} \ No newline at end of file +} 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 c6ff30855..b2c6e5859 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,11 +22,14 @@ */ package com.iluwatar.featuretoggle.user; -import org.junit.Test; - import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Test; + +/** + * Test User Group specific feature + */ public class UserGroupTest { @Test @@ -56,4 +59,4 @@ public class UserGroupTest { UserGroup.addUserToPaidGroup(user); UserGroup.addUserToFreeGroup(user); } -} \ No newline at end of file +} diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml index 8d815079c..cc243123b 100644 --- a/fluentinterface/pom.xml +++ b/fluentinterface/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT 4.0.0 diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java index 54d367c20..389904bff 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java @@ -27,6 +27,7 @@ import java.util.Iterator; /** * This class is used to realize LazyFluentIterables. It decorates a given iterator. Does not * support consecutive hasNext() calls. + * @param Iterable Collection of Elements of Type E */ public abstract class DecoratingIterator implements Iterator { @@ -43,7 +44,7 @@ public abstract class DecoratingIterator implements Iterator { /** * Precomputes and saves the next element of the Iterable. null is considered as end of data. - * + * * @return true if a next element is available */ @Override @@ -54,7 +55,7 @@ public abstract class DecoratingIterator implements Iterator { /** * Returns the next element of the Iterable. - * + * * @return the next element of the Iterable, or null if not present. */ @Override @@ -71,7 +72,7 @@ public abstract class DecoratingIterator implements Iterator { /** * Computes the next object of the Iterable. Can be implemented to realize custom behaviour for an * iteration process. null is considered as end of data. - * + * * @return the next element of the Iterable. */ public abstract E computeNext(); 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 6d6420d55..11740bf1a 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -23,7 +23,9 @@ package com.iluwatar.fluentinterface.app; import org.junit.Test; - +/** + * Application Test Entry + */ public class AppTest { @Test diff --git a/flux/pom.xml b/flux/pom.xml index aa0c95796..158ca8c65 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT flux diff --git a/flyweight/pom.xml b/flyweight/pom.xml index 2c210a0ca..d9574b589 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT flyweight diff --git a/front-controller/pom.xml b/front-controller/pom.xml index 11802d2f5..082fe27c0 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT front-controller diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java index 62a234d0d..2e6f26c0c 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java @@ -30,6 +30,9 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/guarded-suspension/README.md b/guarded-suspension/README.md index 35044f9b2..3e00539a2 100644 --- a/guarded-suspension/README.md +++ b/guarded-suspension/README.md @@ -3,6 +3,7 @@ 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 index f99607d82..45a7d3790 100644 --- a/guarded-suspension/etc/guarded-suspension.urm.puml +++ b/guarded-suspension/etc/guarded-suspension.urm.puml @@ -1,5 +1,9 @@ @startuml package com.iluwatar.guarded.suspension { + class App { + + App() + + main(args : String[]) {static} + } class GuardedQueue { - LOGGER : Logger {static} - sourceList : Queue diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index b51de54e1..b7423d1eb 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT jar guarded-suspension diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java index 89b330bfb..bf6142dd9 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java @@ -28,7 +28,12 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.Queue; - +/** + * Guarded Queue is an implementation for Guarded Suspension Pattern + * Guarded suspension pattern is used to handle a situation when you want to execute a method + * on an object which is not in a proper state. + * @see http://java-design-patterns.com/patterns/guarded-suspension/ + */ public class GuardedQueue { private static final Logger LOGGER = LoggerFactory.getLogger(GuardedQueue.class); private final Queue sourceList; 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 41eaccd49..5a741d399 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 @@ -29,6 +29,9 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +/** + * Test for Guarded Queue + */ public class GuardedQueueTest { private volatile Integer value; @@ -55,4 +58,4 @@ public class GuardedQueueTest { } -} \ No newline at end of file +} diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index 4b3285ff1..2952f8d54 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT half-sync-half-async diff --git a/hexagonal/README.md b/hexagonal/README.md index 88908421d..dc1566625 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -4,6 +4,7 @@ title: Hexagonal Architecture folder: hexagonal permalink: /patterns/hexagonal/ pumlid: HSTB4W8X30N0g-W1XkozpPD90LO8L3wEnzUTk-xxq2fvSfhSUiJs1v7XAcr4psSwMrqQh57gcZGaBmICNdZZEDb7qsCZWasT9lm7wln1MmeXZlfVIPjbvvGl +pumlformat: svg categories: Architectural tags: - Java diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml index 2cf88b626..9af418fbb 100644 --- a/hexagonal/pom.xml +++ b/hexagonal/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT hexagonal diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java index babbd6d03..a5b455354 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -23,12 +23,15 @@ package com.iluwatar.hexagonal.domain; /** - * + * * Represents lottery ticket check result. * */ public class LotteryTicketCheckResult { + /** + * Enumeration of Type of Outcomes of a Lottery + */ public enum CheckResult { WIN_PRIZE, NO_PRIZE, TICKET_NOT_SUBMITTED } private final CheckResult checkResult; @@ -41,7 +44,7 @@ public class LotteryTicketCheckResult { checkResult = result; prizeAmount = 0; } - + /** * Constructor. */ @@ -56,7 +59,7 @@ public class LotteryTicketCheckResult { public CheckResult getResult() { return checkResult; } - + /** * @return prize amount */ 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 8aaa83681..a83f9033c 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -30,6 +30,9 @@ import java.util.HashSet; import org.junit.Test; +/** + * Test Lottery Tickets for equality + */ public class LotteryTicketTest { @Test diff --git a/intercepting-filter/etc/intercepting-filter.urm.puml b/intercepting-filter/etc/intercepting-filter.urm.puml index 5c1e79ee4..74444c2d0 100644 --- a/intercepting-filter/etc/intercepting-filter.urm.puml +++ b/intercepting-filter/etc/intercepting-filter.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.intercepting.filter { abstract class AbstractFilter { - next : Filter @@ -79,10 +80,10 @@ AbstractFilter --> "-next" Filter DListener --+ Target FilterChain --> "-chain" Filter FilterManager --> "-filterChain" FilterChain -AbstractFilter ..|> Filter -AddressFilter --|> AbstractFilter -ContactFilter --|> AbstractFilter -DepositFilter --|> AbstractFilter -NameFilter --|> AbstractFilter -OrderFilter --|> AbstractFilter -@enduml \ No newline at end of file +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 2c23edff2..e5082ef00 100644 --- a/intercepting-filter/pom.xml +++ b/intercepting-filter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT intercepting-filter diff --git a/interpreter/etc/interpreter.urm.puml b/interpreter/etc/interpreter.urm.puml index e79ad1989..e1286a2a9 100644 --- a/interpreter/etc/interpreter.urm.puml +++ b/interpreter/etc/interpreter.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.interpreter { class App { - LOGGER : Logger {static} @@ -44,8 +45,8 @@ package com.iluwatar.interpreter { MultiplyExpression --> "-leftExpression" Expression MinusExpression --> "-leftExpression" Expression PlusExpression --> "-leftExpression" Expression -MinusExpression --|> Expression -MultiplyExpression --|> Expression -NumberExpression --|> Expression -PlusExpression --|> Expression -@enduml \ No newline at end of file +MinusExpression --|> Expression +MultiplyExpression --|> Expression +NumberExpression --|> Expression +PlusExpression --|> Expression +@enduml diff --git a/interpreter/pom.xml b/interpreter/pom.xml index a932e10b4..a9c4126d4 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT interpreter diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index 95a65e82c..2d444373c 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -22,18 +22,19 @@ */ package com.iluwatar.interpreter; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; /** * Date: 12/14/15 - 11:48 AM * + * Test Case for Expressions + * @param Type of Expression * @author Jeroen Meulemeester */ public abstract class ExpressionTest { diff --git a/iterator/pom.xml b/iterator/pom.xml index 3fcdd9852..c05c78d3c 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT iterator diff --git a/layers/README.md b/layers/README.md index d62c6b6b7..8eac62412 100644 --- a/layers/README.md +++ b/layers/README.md @@ -4,6 +4,7 @@ title: Layers folder: layers permalink: /patterns/layers/ pumlid: BSR13OCm30NGLSe0n7UsCS62L8w9x6yGszD3t-bDpQhc9kdwEO0H2v7pNVQ68zSCyNeQn53gsQbftWns-lB5yoRHTfi70-8Mr3b-8UL7F4XG_otflOpi-W80 +pumlformat: svg categories: Architectural tags: - Java diff --git a/layers/pom.xml b/layers/pom.xml index 13604cb0e..621facbea 100644 --- a/layers/pom.xml +++ b/layers/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT com.iluwatar.layers layers diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index 2ed0a1020..4e95046bf 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT lazy-loading diff --git a/mediator/pom.xml b/mediator/pom.xml index b9fda50a5..b48324472 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT mediator diff --git a/memento/pom.xml b/memento/pom.xml index e6cd095d9..0990844f7 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT memento diff --git a/message-channel/README.md b/message-channel/README.md index aa357ac0c..09361dd4a 100644 --- a/message-channel/README.md +++ b/message-channel/README.md @@ -3,9 +3,8 @@ layout: pattern title: Message Channel folder: message-channel permalink: /patterns/message-channel/ -pumlid: NSZB3SCm203GLTe1RExTXX1akm9YyMdMRy-zFRtdCf8wkLmUCtF72y3nxcFbhAE2dIvBjknqAIof6nCTtlZ1TdAiOMrZ9hi5ACOFe1o1WnjDD6C1Jlg_NgvzbyeN categories: Integration -tags: +tags: - Java - EIP - Apache Camel™ @@ -24,4 +23,4 @@ Use the Message Channel pattern when ## Real world examples -* [akka-camel](http://doc.akka.io/docs/akka/snapshot/scala/camel.html) \ No newline at end of file +* [akka-camel](http://doc.akka.io/docs/akka/snapshot/scala/camel.html) diff --git a/message-channel/pom.xml b/message-channel/pom.xml index 98b2a0c2e..91c631313 100644 --- a/message-channel/pom.xml +++ b/message-channel/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT message-channel diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 29823d9e8..bf7ace403 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT model-view-controller 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 ba72fea1a..ec0aabd15 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,20 +22,19 @@ */ package com.iluwatar.model.view.controller; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + 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.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - /** * Date: 12/20/15 - 2:04 PM * @@ -70,6 +69,9 @@ public class GiantViewTest { assertEquals(1, appender.getLogSize()); } + /** + * Logging Appender Implementation + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index 6c43a0048..2eeedc6df 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT model-view-presenter model-view-presenter 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 c9b023925..01af677ae 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 @@ -48,8 +48,7 @@ public class FileLoader { * Loads the data of the file specified. */ public String loadData() { - try { - BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName))); + try (BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)))) { StringBuilder sb = new StringBuilder(); String line; @@ -58,7 +57,6 @@ public class FileLoader { } this.loaded = true; - br.close(); return sb.toString(); } catch (Exception e) { diff --git a/module/pom.xml b/module/pom.xml index 8920916cb..caa66cb54 100644 --- a/module/pom.xml +++ b/module/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT module diff --git a/monad/pom.xml b/monad/pom.xml index 63d6431db..694ba71ed 100644 --- a/monad/pom.xml +++ b/monad/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT monad diff --git a/monad/src/main/java/com/iluwatar/monad/Sex.java b/monad/src/main/java/com/iluwatar/monad/Sex.java index 3cbe22971..6c6d6eff6 100644 --- a/monad/src/main/java/com/iluwatar/monad/Sex.java +++ b/monad/src/main/java/com/iluwatar/monad/Sex.java @@ -22,6 +22,9 @@ */ package com.iluwatar.monad; +/** + * Enumeration of Types of Sex + */ public enum Sex { MALE, FEMALE } diff --git a/monad/src/main/java/com/iluwatar/monad/User.java b/monad/src/main/java/com/iluwatar/monad/User.java index 53cf759cf..406407fea 100644 --- a/monad/src/main/java/com/iluwatar/monad/User.java +++ b/monad/src/main/java/com/iluwatar/monad/User.java @@ -22,6 +22,9 @@ */ package com.iluwatar.monad; +/** + * User Definition + */ public class User { private String name; diff --git a/monad/src/test/java/com/iluwatar/monad/AppTest.java b/monad/src/test/java/com/iluwatar/monad/AppTest.java index f661ee1c6..69464ff87 100644 --- a/monad/src/test/java/com/iluwatar/monad/AppTest.java +++ b/monad/src/test/java/com/iluwatar/monad/AppTest.java @@ -24,6 +24,9 @@ package com.iluwatar.monad; import org.junit.Test; +/** + * Application Test + */ public class AppTest { @Test diff --git a/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/monad/src/test/java/com/iluwatar/monad/MonadTest.java index 2676e6e80..a34243978 100644 --- a/monad/src/test/java/com/iluwatar/monad/MonadTest.java +++ b/monad/src/test/java/com/iluwatar/monad/MonadTest.java @@ -30,6 +30,9 @@ import org.junit.rules.ExpectedException; import java.util.Objects; +/** + * Test for Monad Pattern + */ public class MonadTest { @Rule diff --git a/monostate/pom.xml b/monostate/pom.xml index bc025fdeb..be7ba99a4 100644 --- a/monostate/pom.xml +++ b/monostate/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT monostate diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java index 301beea3e..3e88b3bf2 100644 --- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java +++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java @@ -24,6 +24,9 @@ package com.iluwatar.monostate; import org.junit.Test; +/** + * Application Test Entry + */ public class AppTest { @Test diff --git a/multiton/pom.xml b/multiton/pom.xml index 34cc4ae8d..b4dd361ae 100644 --- a/multiton/pom.xml +++ b/multiton/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT multiton diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml index d68b016f9..0fedbf901 100644 --- a/mute-idiom/pom.xml +++ b/mute-idiom/pom.xml @@ -21,7 +21,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT mute-idiom 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 698395cc2..7e1d2e1af 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -35,47 +35,50 @@ import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Test for the mute-idiom pattern + */ public class MuteTest { private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class); private static final String MESSAGE = "should not occur"; - + @Rule public ExpectedException exception = ExpectedException.none(); - + @Test public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { Mute.mute(() -> methodNotThrowingAnyException()); } - + @Test public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception { exception.expect(AssertionError.class); exception.expectMessage(MESSAGE); - + Mute.mute(() -> methodThrowingException()); } - + @Test public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { Mute.loggedMute(() -> methodNotThrowingAnyException()); } - + @Test public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); System.setErr(new PrintStream(stream)); - + Mute.loggedMute(() -> methodThrowingException()); - + assertTrue(new String(stream.toByteArray()).contains(MESSAGE)); } - - + + private void methodNotThrowingAnyException() { LOGGER.info("Executed successfully"); } - + private void methodThrowingException() throws Exception { throw new Exception(MESSAGE); } diff --git a/mutex/pom.xml b/mutex/pom.xml index d42a2fdab..0a3ad9e93 100644 --- a/mutex/pom.xml +++ b/mutex/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT mutex diff --git a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java index dfc0de124..f224a56f5 100644 --- a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java +++ b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java @@ -25,10 +25,13 @@ package com.iluwatar.mutex; import org.junit.Test; import java.io.IOException; +/** + * Application Test Entrypoint + */ public class AppTest{ @Test public void test() throws IOException { String[] args = {}; App.main(args); } -} \ No newline at end of file +} diff --git a/naked-objects/README.md b/naked-objects/README.md index 14391dd40..66e6ac2b0 100644 --- a/naked-objects/README.md +++ b/naked-objects/README.md @@ -3,7 +3,6 @@ layout: pattern title: Naked Objects folder: naked-objects permalink: /patterns/naked-objects/ -pumlid: LSX15i8W30N0g-W187jlaq9igH1uoO_r-BfrDs_kJKkFAc7zTW3B7qJ6LzuRZjZ2nSfKY2ANEQZrk1XiTFARKnLlkwR5W9Ww3VOVIFabDStjb08dGVcVz6mVX4aE6td5w5y0 categories: Architectural tags: - Java diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 39560b5c0..9b98700b8 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT naked-objects-dom diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java index 162cd3bb4..30469ba8e 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -21,6 +21,10 @@ import org.apache.isis.applib.annotation.HomePage; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.SemanticsOf; +/** + * HomePage Domain Service + * @see HomePageViewModel linked view to HomePage + */ @DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY) public class HomePageService { diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java index f367a39fd..dfb499f0f 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -21,6 +21,11 @@ import org.apache.isis.applib.annotation.ViewModel; import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObjects; +/** + * Model linked to the HomePage + * The underlying layout is specified by json + * @see HomePageService - Service Linked to the HomePage + */ @ViewModel public class HomePageViewModel { diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java index bbbd54b00..c7972ab84 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -33,6 +33,9 @@ import org.apache.isis.applib.services.eventbus.ActionDomainEvent; import org.apache.isis.applib.services.i18n.TranslatableString; import org.apache.isis.applib.util.ObjectContracts; +/** + * Definition of a Simple Object + */ @javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple", table = "SimpleObject") @javax.jdo.annotations.DatastoreIdentity( @@ -53,7 +56,7 @@ public class SimpleObject implements Comparable { // region > name (property) private String name; - + // region > identificatiom public TranslatableString title() { return TranslatableString.tr("Object: {name}", "name", getName()); @@ -74,6 +77,9 @@ public class SimpleObject implements Comparable { // region > updateName (action) + /** + * Event used to update the Name in the Domain + */ public static class UpdateNameDomainEvent extends ActionDomainEvent { public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier, final Object... arguments) { diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java index 5ebad0159..249fbb1f0 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -30,6 +30,9 @@ import org.apache.isis.applib.query.QueryDefault; import org.apache.isis.applib.services.eventbus.ActionDomainEvent; import org.apache.isis.applib.services.i18n.TranslatableString; +/** + * Domain Service for Simple Objects + */ @DomainService(repositoryFor = SimpleObject.class) @DomainServiceLayout(menuOrder = "10") public class SimpleObjects { @@ -69,6 +72,9 @@ public class SimpleObjects { // endregion + /** + * Create Domain Event on SimpleObjects + */ // region > create (action) public static class CreateDomainEvent extends ActionDomainEvent { public CreateDomainEvent(final SimpleObjects source, final Identifier identifier, diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java index fc62239c2..d80d0786a 100644 --- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java +++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java @@ -14,11 +14,14 @@ */ package domainapp.dom.modules.simple; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Before; import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Test for SimpleObject + */ public class SimpleObjectTest { SimpleObject simpleObject; @@ -28,6 +31,9 @@ public class SimpleObjectTest { simpleObject = new SimpleObject(); } + /** + * Test for Names for SimpleObjects + */ public static class Name extends SimpleObjectTest { @Test diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java index 47cad61b8..91fe3d715 100644 --- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java +++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java @@ -14,10 +14,13 @@ */ package domainapp.dom.modules.simple; -import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.Lists; - +import java.util.List; +import org.apache.isis.applib.DomainObjectContainer; +import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2; +import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2.Mode; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.auto.Mock; @@ -25,12 +28,9 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.apache.isis.applib.DomainObjectContainer; -import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2; -import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2.Mode; - -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Test for SimpleObjects + */ public class SimpleObjectsTest { @Rule @@ -47,6 +47,9 @@ public class SimpleObjectsTest { simpleObjects.container = mockContainer; } + /** + * Test Creation of Simple Objects + */ public static class Create extends SimpleObjectsTest { @Test @@ -77,6 +80,9 @@ public class SimpleObjectsTest { } + /** + * Test Listing of Simple Objects + */ public static class ListAll extends SimpleObjectsTest { @Test diff --git a/naked-objects/fixture/pom.xml b/naked-objects/fixture/pom.xml index a96c24626..e48ec5b30 100644 --- a/naked-objects/fixture/pom.xml +++ b/naked-objects/fixture/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT naked-objects-fixture diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java index f0617fea2..58b656a98 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -20,6 +20,9 @@ import org.apache.isis.applib.fixturescripts.FixtureScript; import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObjects; +/** + * Fixture to create a simple object + */ public class SimpleObjectCreate extends FixtureScript { // endregion @@ -45,7 +48,7 @@ public class SimpleObjectCreate extends FixtureScript { this.name = name; return this; } - + /** * The created simple object (output). */ @@ -65,5 +68,5 @@ public class SimpleObjectCreate extends FixtureScript { // also make available to UI ec.addResult(this, simpleObject); } - + } diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java index 7000bf4c0..c0319d953 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -18,6 +18,9 @@ package domainapp.fixture.modules.simple; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.services.jdosupport.IsisJdoSupport; +/** + * TearDown/Cleanup for SimpleObjects + */ public class SimpleObjectsTearDown extends FixtureScript { @javax.inject.Inject @@ -27,5 +30,5 @@ public class SimpleObjectsTearDown extends FixtureScript { protected void execute(ExecutionContext executionContext) { isisJdoSupport.executeUpdate("delete from \"simple\".\"SimpleObject\""); } - + } diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java index 62ad0405a..be891158a 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -27,6 +27,10 @@ import domainapp.dom.modules.simple.SimpleObject; import domainapp.fixture.modules.simple.SimpleObjectCreate; import domainapp.fixture.modules.simple.SimpleObjectsTearDown; + +/** + * Create a bunch of simple Objects + */ public class RecreateSimpleObjects extends FixtureScript { public final List names = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz", @@ -43,7 +47,7 @@ public class RecreateSimpleObjects extends FixtureScript { public RecreateSimpleObjects() { withDiscoverability(Discoverability.DISCOVERABLE); } - + /** * The number of objects to create, up to 10; optional, defaults to 3. */ @@ -55,7 +59,7 @@ public class RecreateSimpleObjects extends FixtureScript { this.number = number; return this; } - + /** * The simpleobjects created by this fixture (output). */ diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index 32ec4cd6b..7389e5cef 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT naked-objects-integtests diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java index b7c76d0ed..3ac5a1d75 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java @@ -4,9 +4,9 @@ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -19,6 +19,9 @@ import org.apache.isis.core.integtestsupport.IsisSystemForTest; import org.apache.isis.objectstore.jdo.datanucleus.DataNucleusPersistenceMechanismInstaller; import org.apache.isis.objectstore.jdo.datanucleus.IsisConfigurationForJdoIntegTests; +/** + * Initializer for the Simple App + */ public final class SimpleAppSystemInitializer { private SimpleAppSystemInitializer() { diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java index 190e1f5bb..e41399fdd 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java @@ -21,6 +21,9 @@ import cucumber.api.java.After; import cucumber.api.java.Before; import domainapp.integtests.bootstrap.SimpleAppSystemInitializer; +/** + * BootStrapping IntegrationTesting Before and After Steps + */ public class BootstrappingGlue extends CukeGlueAbstract { @Before(value = {"@integration"}, order = 100) diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java index 2fcb7cca7..7a75a0381 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java @@ -19,6 +19,9 @@ import org.apache.isis.core.specsupport.specs.CukeGlueAbstract; import cucumber.api.java.Before; import domainapp.fixture.scenarios.RecreateSimpleObjects; +/** + * Test Execution to append a fixture of SimpleObjects + */ public class CatalogOfFixturesGlue extends CukeGlueAbstract { @Before(value = {"@integration", "@SimpleObjectsFixture"}, order = 20000) diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java index 2ea375b4a..b7af9f052 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java @@ -14,18 +14,20 @@ */ package domainapp.integtests.specglue.modules.simple; -import java.util.List; -import java.util.UUID; - -import org.apache.isis.core.specsupport.specs.CukeGlueAbstract; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObjects; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import java.util.List; +import java.util.UUID; +import org.apache.isis.core.specsupport.specs.CukeGlueAbstract; +/** + * Test Simple Object Operations + */ public class SimpleObjectGlue extends CukeGlueAbstract { @Given("^there are.* (\\d+) simple objects$") diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java index 7a7ad91b2..66deaeb84 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java @@ -25,6 +25,9 @@ import org.apache.isis.core.integtestsupport.scenarios.ScenarioExecutionForInteg import domainapp.integtests.bootstrap.SimpleAppSystemInitializer; +/** + * SimpleApp Integration Tests will implement this Abstract Class. + */ public abstract class SimpleAppIntegTest extends IntegrationTestAbstract { @BeforeClass @@ -35,5 +38,4 @@ public abstract class SimpleAppIntegTest extends IntegrationTestAbstract { // instantiating will install onto ThreadLocal new ScenarioExecutionForIntegration(); } - } diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java index 872aff7a3..f2cbb1723 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java @@ -18,21 +18,22 @@ */ package domainapp.integtests.tests.modules.simple; -import javax.inject.Inject; - -import org.junit.Before; -import org.junit.Test; - -import org.apache.isis.applib.DomainObjectContainer; -import org.apache.isis.applib.fixturescripts.FixtureScripts; -import org.apache.isis.applib.services.wrapper.DisabledException; -import org.apache.isis.applib.services.wrapper.InvalidException; +import static org.assertj.core.api.Assertions.assertThat; import domainapp.dom.modules.simple.SimpleObject; import domainapp.fixture.scenarios.RecreateSimpleObjects; import domainapp.integtests.tests.SimpleAppIntegTest; -import static org.assertj.core.api.Assertions.assertThat; +import javax.inject.Inject; +import org.apache.isis.applib.DomainObjectContainer; +import org.apache.isis.applib.fixturescripts.FixtureScripts; +import org.apache.isis.applib.services.wrapper.DisabledException; +import org.apache.isis.applib.services.wrapper.InvalidException; +import org.junit.Before; +import org.junit.Test; +/** + * Test Fixtures with Simple Objects + */ public class SimpleObjectIntegTest extends SimpleAppIntegTest { @Inject @@ -54,6 +55,9 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest { simpleObjectWrapped = wrap(simpleObjectPojo); } + /** + * Test Object Name accessibility + */ public static class Name extends SimpleObjectIntegTest { @Test @@ -75,6 +79,9 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest { } } + /** + * Test Validation of SimpleObject Names + */ public static class UpdateName extends SimpleObjectIntegTest { @Test @@ -99,6 +106,9 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest { } } + /** + * Test ContainerTitle generation based on SimpleObject Name + */ public static class Title extends SimpleObjectIntegTest { @Inject @@ -117,4 +127,4 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest { assertThat(title).isEqualTo("Object: " + name); } } -} \ No newline at end of file +} diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java index 332213542..d57454dc1 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java @@ -18,28 +18,27 @@ */ package domainapp.integtests.tests.modules.simple; -import java.sql.SQLIntegrityConstraintViolationException; -import java.util.List; - -import javax.inject.Inject; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.base.Throwables; - -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Test; - -import org.apache.isis.applib.fixturescripts.FixtureScript; -import org.apache.isis.applib.fixturescripts.FixtureScripts; - import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObjects; import domainapp.fixture.modules.simple.SimpleObjectsTearDown; import domainapp.fixture.scenarios.RecreateSimpleObjects; import domainapp.integtests.tests.SimpleAppIntegTest; -import static org.assertj.core.api.Assertions.assertThat; +import java.sql.SQLIntegrityConstraintViolationException; +import java.util.List; +import javax.inject.Inject; +import org.apache.isis.applib.fixturescripts.FixtureScript; +import org.apache.isis.applib.fixturescripts.FixtureScripts; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.Test; +/** + * Fixture Pattern Integration Test + */ public class SimpleObjectsIntegTest extends SimpleAppIntegTest { @Inject @@ -47,6 +46,9 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest { @Inject SimpleObjects simpleObjects; + /** + * Test Listing of All Simple Objects + */ public static class ListAll extends SimpleObjectsIntegTest { @Test @@ -83,6 +85,10 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest { } } + + /** + * Test Creation of Simple Objects + */ public static class Create extends SimpleObjectsIntegTest { @Test @@ -140,4 +146,4 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest { } } -} \ No newline at end of file +} diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml index d8acdc745..d2cf69296 100644 --- a/naked-objects/pom.xml +++ b/naked-objects/pom.xml @@ -15,7 +15,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT naked-objects @@ -367,17 +367,17 @@ ${project.groupId} naked-objects-dom - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT ${project.groupId} naked-objects-fixture - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT ${project.groupId} naked-objects-webapp - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT diff --git a/naked-objects/webapp/pom.xml b/naked-objects/webapp/pom.xml index 7e6d3ffcd..c415050bc 100644 --- a/naked-objects/webapp/pom.xml +++ b/naked-objects/webapp/pom.xml @@ -16,7 +16,7 @@ com.iluwatar naked-objects - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT naked-objects-webapp diff --git a/null-object/pom.xml b/null-object/pom.xml index 2c494e3b7..6f96d777c 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT null-object diff --git a/object-mother/README.md b/object-mother/README.md index 9188c8b41..cda3336cf 100644 --- a/object-mother/README.md +++ b/object-mother/README.md @@ -3,7 +3,7 @@ layout: pattern title: Object Mother folder: object-mother permalink: /patterns/object-mother/ -pumlid: +pumlid: LOr13iCW30JlVKNx0E3UKxxYW9KGWK7sklb-wR6dtLbfj9k15DxRurKbDo_isfudCEsTaj8TZuhJTpVMF0GiY7dqL9lVjDHqqOT2OQk7X4a0grZgPAkaiL-S4Vh0kOYH_vVeskFyVMyiPUKN categories: Creational tags: - Java @@ -28,4 +28,4 @@ Use the Object Mother pattern when * [c2wiki - Object Mother](http://c2.com/cgi/wiki?ObjectMother) -* [Nat Pryce - Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html) \ No newline at end of file +* [Nat Pryce - Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html) diff --git a/object-mother/pom.xml b/object-mother/pom.xml index fc7d96a85..f2f933e49 100644 --- a/object-mother/pom.xml +++ b/object-mother/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT object-mother diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/King.java b/object-mother/src/main/java/com/iluwatar/objectmother/King.java index 544b0bacb..b1b5f3610 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/King.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/King.java @@ -22,6 +22,9 @@ */ package com.iluwatar.objectmother; +/** + * Defines all attributes and behaviour related to the King + */ public class King implements Royalty { boolean isDrunk = false; boolean isHappy = false; @@ -45,11 +48,11 @@ public class King implements Royalty { public void makeUnhappy() { isHappy = false; } - + public boolean isHappy() { return isHappy; } - + /** * Method to flirt to a queen. * @param queen Queen which should be flirted. @@ -61,6 +64,6 @@ public class King implements Royalty { } else { this.makeHappy(); } - + } } diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java index 3e18fbf3a..e7e488602 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java @@ -22,6 +22,9 @@ */ package com.iluwatar.objectmother; +/** + * Defines all attributes and behaviour related to the Queen + */ public class Queen implements Royalty { private boolean isDrunk = false; private boolean isHappy = false; @@ -46,7 +49,7 @@ public class Queen implements Royalty { public void makeUnhappy() { isHappy = false; } - + public boolean isFlirty() { return isFlirty; } @@ -54,7 +57,7 @@ public class Queen implements Royalty { public void setFlirtiness(boolean flirtiness) { this.isFlirty = flirtiness; } - + /** * Method which is called when the king is flirting to a queen. * @param king King who initialized the flirt. diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java b/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java index 2bebc0939..42271a21d 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java @@ -22,12 +22,15 @@ */ package com.iluwatar.objectmother; +/** + * Interface contracting Royalty Behaviour + */ public interface Royalty { void makeDrunk(); - + void makeSober(); - + void makeHappy(); - + void makeUnhappy(); } diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java b/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java index 624a29132..118253d56 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java @@ -22,8 +22,11 @@ */ package com.iluwatar.objectmother; +/** + * Object Mother Pattern generating Royalty Types + */ public final class RoyaltyObjectMother { - + /** * Method to create a sober and unhappy king. The standard paramters are set. * @return An instance of {@link com.iluwatar.objectmother.King} with the standard properties. @@ -31,7 +34,7 @@ public final class RoyaltyObjectMother { public static King createSoberUnhappyKing() { return new King(); } - + /** * Method of the object mother to create a drunk king. * @return A drunk {@link com.iluwatar.objectmother.King}. @@ -41,7 +44,7 @@ public final class RoyaltyObjectMother { king.makeDrunk(); return king; } - + /** * Method to create a happy king. * @return A happy {@link com.iluwatar.objectmother.King}. @@ -51,7 +54,7 @@ public final class RoyaltyObjectMother { king.makeHappy(); return king; } - + /** * Method to create a happy and drunk king. * @return A drunk and happy {@link com.iluwatar.objectmother.King}. @@ -62,7 +65,7 @@ public final class RoyaltyObjectMother { king.makeDrunk(); return king; } - + /** * Method to create a flirty queen. * @return A flirty {@link com.iluwatar.objectmother.Queen}. @@ -72,7 +75,7 @@ public final class RoyaltyObjectMother { queen.setFlirtiness(true); return queen; } - + /** * Method to create a not flirty queen. * @return A not flirty {@link com.iluwatar.objectmother.Queen}. 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 ebe536d24..cc5af45aa 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 @@ -33,8 +33,11 @@ import com.iluwatar.objectmother.Queen; import com.iluwatar.objectmother.Royalty; import com.iluwatar.objectmother.RoyaltyObjectMother; +/** + * Test Generation of Royalty Types using the object-mother + */ public class RoyaltyObjectMotherTest { - + @Test public void unsuccessfulKingFlirt() { King soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing(); @@ -42,7 +45,7 @@ public class RoyaltyObjectMotherTest { soberUnhappyKing.flirt(flirtyQueen); assertFalse(soberUnhappyKing.isHappy()); } - + @Test public void queenIsBlockingFlirtCauseDrunkKing() { King drunkUnhappyKing = RoyaltyObjectMother.createDrunkKing(); @@ -50,7 +53,7 @@ public class RoyaltyObjectMotherTest { drunkUnhappyKing.flirt(notFlirtyQueen); assertFalse(drunkUnhappyKing.isHappy()); } - + @Test public void queenIsBlockingFlirt() { King soberHappyKing = RoyaltyObjectMother.createHappyKing(); @@ -58,7 +61,7 @@ public class RoyaltyObjectMotherTest { soberHappyKing.flirt(notFlirtyQueen); assertFalse(soberHappyKing.isHappy()); } - + @Test public void successfullKingFlirt() { King soberHappyKing = RoyaltyObjectMother.createHappyKing(); @@ -66,7 +69,7 @@ public class RoyaltyObjectMotherTest { soberHappyKing.flirt(flirtyQueen); assertTrue(soberHappyKing.isHappy()); } - + @Test public void testQueenType() { Royalty flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); @@ -74,7 +77,7 @@ public class RoyaltyObjectMotherTest { assertEquals(flirtyQueen.getClass(), Queen.class); assertEquals(notFlirtyQueen.getClass(), Queen.class); } - + @Test public void testKingType() { Royalty drunkKing = RoyaltyObjectMother.createDrunkKing(); diff --git a/object-pool/pom.xml b/object-pool/pom.xml index 19ac48956..bf2e3d4ae 100644 --- a/object-pool/pom.xml +++ b/object-pool/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT object-pool diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java index 510d9dc88..df6e887b8 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java @@ -26,8 +26,8 @@ import java.util.HashSet; import java.util.Set; /** - * * Generic object pool + * @param Type T of Object in the Pool */ public abstract class ObjectPool { @@ -40,7 +40,7 @@ public abstract class ObjectPool { * Checkout object from pool */ public synchronized T checkOut() { - if (available.size() <= 0) { + if (available.isEmpty()) { available.add(create()); } T instance = available.iterator().next(); diff --git a/observer/etc/observer.urm.puml b/observer/etc/observer.urm.puml index bea9aab53..5d046d880 100644 --- a/observer/etc/observer.urm.puml +++ b/observer/etc/observer.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.observer { class App { - LOGGER : Logger {static} @@ -71,10 +72,10 @@ package com.iluwatar.observer.generic { Weather --> "-currentWeather" WeatherType GWeather --> "-currentWeather" WeatherType Weather --> "-observers" WeatherObserver -Hobbits ..|> WeatherObserver -Orcs ..|> WeatherObserver -GHobbits ..|> Race -GOrcs ..|> Race -GWeather --|> Observable -Race --|> Observer -@enduml \ No newline at end of file +Hobbits ..|> WeatherObserver +Orcs ..|> WeatherObserver +GHobbits ..|> Race +GOrcs ..|> Race +GWeather --|> Observable +Race --|> Observer +@enduml diff --git a/observer/pom.xml b/observer/pom.xml index bb313552c..a854aaada 100644 --- a/observer/pom.xml +++ b/observer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT observer diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java b/observer/src/main/java/com/iluwatar/observer/generic/Observer.java index b427aae2c..f8c30853b 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/Observer.java @@ -23,8 +23,10 @@ package com.iluwatar.observer.generic; /** - * * Observer + * @param Observable + * @param Observer + * @param Action */ public interface Observer, O extends Observer, A> { diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java index 7120a31e0..70a7922c5 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -22,18 +22,18 @@ */ 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 java.util.function.Supplier; - -import static org.junit.Assert.assertEquals; - /** * Date: 12/27/15 - 11:44 AM - * + * Weather Observer Tests + * @param Type of WeatherObserver * @author Jeroen Meulemeester */ public abstract class WeatherObserverTest { 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 eef89da62..930f7533f 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -22,19 +22,19 @@ */ package com.iluwatar.observer.generic; +import static org.junit.Assert.assertEquals; + import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; +import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.function.Supplier; - -import static org.junit.Assert.assertEquals; - /** * Date: 12/27/15 - 11:44 AM - * + * Test for Observers + * @param Type of Observer * @author Jeroen Meulemeester */ public abstract class ObserverTest { diff --git a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java index b0503a4a1..07d5726d0 100644 --- a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java +++ b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java @@ -30,6 +30,9 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/page-object/README.md b/page-object/README.md index 2219a077c..16c021dfb 100644 --- a/page-object/README.md +++ b/page-object/README.md @@ -3,7 +3,6 @@ layout: pattern title: Page Object folder: page-object permalink: /patterns/page-object/ -pumlid: JSV14OGW30NGLjO28FVj9iOCua1Wme-sxnxtzjvMJLeS6ju-9p3NbyZvoQNYZ3sMkWo36hACJhN5ms2dYszEXwvQB4q6r6rHv_K3JIwQndwfW1Jo_npUyupUNW00 categories: Testing tags: - Java @@ -12,7 +11,7 @@ tags: ## Intent -Page Object encapsulates the UI, hiding the underlying UI widgetry of an application (commonly a web application) and providing an application-specific API to allow the manipulation of UI components required for tests. In doing so, it allows the test class itself to focus on the test logic instead. +Page Object encapsulates the UI, hiding the underlying UI widgetry of an application (commonly a web application) and providing an application-specific API to allow the manipulation of UI components required for tests. In doing so, it allows the test class itself to focus on the test logic instead. ![alt text](./etc/page-object.png "Page Object") @@ -22,11 +21,10 @@ Page Object encapsulates the UI, hiding the underlying UI widgetry of an applica Use the Page Object pattern when -* You are writing automated tests for your web application and you want to separate the UI manipulation required for the tests from the actual test logic. +* You are writing automated tests for your web application and you want to separate the UI manipulation required for the tests from the actual test logic. * Make your tests less brittle, and more readable and robust ## Credits * [Martin Fowler - PageObject](http://martinfowler.com/bliki/PageObject.html) * [Selenium - Page Objects](https://github.com/SeleniumHQ/selenium/wiki/PageObjects) - diff --git a/page-object/pom.xml b/page-object/pom.xml index 35ee916a5..748342d99 100644 --- a/page-object/pom.xml +++ b/page-object/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT page-object 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 f41a79760..79101f3d3 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -23,15 +23,17 @@ 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 static org.junit.Assert.assertTrue; - - +/** + * Test Album Selection and Album Listing + */ public class AlbumListPageTest { private AlbumListPage albumListPage = new AlbumListPage(new WebClient()); 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 248a0ddf8..cb07a8293 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -22,14 +22,17 @@ */ 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 static org.junit.Assert.assertTrue; - +/** + * Test Album Page Operations + */ public class AlbumPageTest { private AlbumPage albumPage = new AlbumPage(new WebClient()); 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 a0483ae40..ad10a1927 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -22,14 +22,17 @@ */ 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 static org.junit.Assert.assertTrue; - +/** + * Test Login Page Object + */ public class LoginPageTest { private LoginPage loginPage = new LoginPage(new WebClient()); diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index e518649cf..c1c8432a1 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT poison-pill diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java index cb89f5f5f..cd2d2da6a 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java @@ -63,6 +63,9 @@ public interface Message { }; + /** + * Enumeration of Type of Headers + */ public enum Headers { DATE, SENDER } diff --git a/pom.xml b/pom.xml index d2ea715a7..a45f0e1f3 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 4.0.0 com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT pom 2014 @@ -50,6 +50,7 @@ abstract-factory + tls builder factory-method prototype @@ -134,8 +135,10 @@ event-asynchronous queue-load-leveling object-mother + data-bus + converter guarded-suspension - + balking @@ -468,4 +471,4 @@ - \ No newline at end of file + diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml index 957e18033..de75796dc 100644 --- a/private-class-data/pom.xml +++ b/private-class-data/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT private-class-data diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java index 37a5458b5..bea71ab15 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java @@ -30,6 +30,9 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml index dbc80614f..ccdfc135a 100644 --- a/producer-consumer/pom.xml +++ b/producer-consumer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT producer-consumer diff --git a/promise/README.md b/promise/README.md index 638bb3ef5..65d463550 100644 --- a/promise/README.md +++ b/promise/README.md @@ -3,6 +3,7 @@ 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 index 45cae7ff1..8aabc1d2a 100644 --- a/promise/etc/promise.urm.puml +++ b/promise/etc/promise.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.promise { class App { - DEFAULT_URL : String {static} @@ -70,9 +71,9 @@ package com.iluwatar.promise { + lowestFrequencyChar(charFrequency : Map) : Character {static} } } -TransformAction --> "-src" Promise TransformAction --+ Promise +TransformAction --> "-src" Promise ConsumeAction --+ Promise ConsumeAction --> "-src" Promise Promise --|> PromiseSupport -@enduml \ No newline at end of file +@enduml diff --git a/promise/pom.xml b/promise/pom.xml index a93ef2ba5..1b20fd784 100644 --- a/promise/pom.xml +++ b/promise/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT promise diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java index 525cda338..41e07be45 100644 --- a/promise/src/main/java/com/iluwatar/promise/Utility.java +++ b/promise/src/main/java/com/iluwatar/promise/Utility.java @@ -39,6 +39,9 @@ import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; +/** + * Utility to perform various operations + */ public class Utility { private static final Logger LOGGER = LoggerFactory.getLogger(Utility.class); diff --git a/property/pom.xml b/property/pom.xml index 4b28b9f54..b488f8e57 100644 --- a/property/pom.xml +++ b/property/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT property diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java index db5de2b64..37552fdc8 100644 --- a/property/src/main/java/com/iluwatar/property/Character.java +++ b/property/src/main/java/com/iluwatar/property/Character.java @@ -30,6 +30,9 @@ import java.util.Map; */ public class Character implements Prototype { + /** + * Enumeration of Character types + */ public enum Type { WARRIOR, MAGE, ROGUE } diff --git a/prototype/pom.xml b/prototype/pom.xml index 995757d5a..a73223b9c 100644 --- a/prototype/pom.xml +++ b/prototype/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT prototype diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java index c17d08772..add5617b1 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -22,21 +22,20 @@ */ package com.iluwatar.prototype; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.Arrays; -import java.util.Collection; - 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 java.util.Arrays; +import java.util.Collection; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + /** * Date: 12/28/15 - 8:45 PM - * + * @param

Prototype * @author Jeroen Meulemeester */ @RunWith(Parameterized.class) diff --git a/proxy/pom.xml b/proxy/pom.xml index f12db724c..293f3098d 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT proxy diff --git a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java index b0c48167d..d78fdc93f 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java +++ b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java @@ -30,6 +30,10 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; + +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/publish-subscribe/README.md b/publish-subscribe/README.md index 3265e42ea..462209074 100644 --- a/publish-subscribe/README.md +++ b/publish-subscribe/README.md @@ -3,9 +3,8 @@ layout: pattern title: Publish Subscribe folder: publish-subscribe permalink: /patterns/publish-subscribe/ -pumlid: PSZB3SCm203GLTe1RExT1XCKKs5YyMdMR--zFRsd66aTNAwFcRdZ1U1uzrDorgXWfykIBJjT2qJhnaI7Dtwm7HnoMjkOoMu12-C7s3LKOhQe4UGo63ZfVtlvwhkMVW40 categories: Integration -tags: +tags: - Java - EIP - Apache Camel™ diff --git a/publish-subscribe/pom.xml b/publish-subscribe/pom.xml index 1586815c1..3f969eac9 100644 --- a/publish-subscribe/pom.xml +++ b/publish-subscribe/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT publish-subscribe diff --git a/queue-load-leveling/README.md b/queue-load-leveling/README.md index 126d19176..ca73ac34a 100644 --- a/queue-load-leveling/README.md +++ b/queue-load-leveling/README.md @@ -3,7 +3,7 @@ layout: pattern title: Queue based load leveling folder: queue-load-leveling permalink: /patterns/queue-load-leveling/ -pumlid: +pumlid: ROux3W8n30LxJW47IDnJxLLCOcM376VnP_VwX9xgZKOQwMtcg1w3RuykXQDIADztzyEU08fNRjttU8MHbYbEuhdC0PtZmfN26qzCbQmtIGUwauh1G5i0dw2Wn1DhOZg9kpGWB_zy3Xtv-FtOIEhQBm00 categories: Other tags: - Java @@ -34,4 +34,4 @@ for both the task and the service. ## Credits -* [Microsoft Cloud Design Patterns: Queue-Based Load Leveling Pattern](https://msdn.microsoft.com/en-us/library/dn589783.aspx) \ No newline at end of file +* [Microsoft Cloud Design Patterns: Queue-Based Load Leveling Pattern](https://msdn.microsoft.com/en-us/library/dn589783.aspx) diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml index 351f94906..3966dd4db 100644 --- a/queue-load-leveling/pom.xml +++ b/queue-load-leveling/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT queue-load-leveling diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java index 63dbec69f..2b423ffaf 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java @@ -35,27 +35,27 @@ import org.slf4j.LoggerFactory; public class ServiceExecutor implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - + private final MessageQueue msgQueue; public ServiceExecutor(MessageQueue msgQueue) { this.msgQueue = msgQueue; } - + /** * The ServiceExecutor thread will retrieve each message and process it. */ public void run() { try { - while (true) { + while (!Thread.currentThread().isInterrupted()) { Message msg = msgQueue.retrieveMsg(); - + if (null != msg) { LOGGER.info(msg.toString() + " is served."); } else { LOGGER.info("Service Executor: Waiting for Messages to serve .. "); } - + Thread.sleep(1000); } } catch (InterruptedException ie) { diff --git a/reactor/README.md b/reactor/README.md index 7fd3982ad..68461cfdd 100644 --- a/reactor/README.md +++ b/reactor/README.md @@ -4,8 +4,9 @@ title: Reactor folder: reactor permalink: /patterns/reactor/ pumlid: DSR14OGm20NGLjO23FVj1f7Hx2Ga0nzjVxtuJc-f9YrtJM-V4vZn9NA-or5nvfQXBiEWXYAZKsrvCzZfnnUlkqOzR9qCg5jGvtX2hYmOJWfvNz9xcTdR7m00 +pumlformat: svg categories: Concurrency -tags: +tags: - Java - Difficulty-Expert - I/O diff --git a/reactor/etc/reactor.urm.puml b/reactor/etc/reactor.urm.puml index cc56eae7a..1ce92cab2 100644 --- a/reactor/etc/reactor.urm.puml +++ b/reactor/etc/reactor.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.reactor.framework { abstract class AbstractNioChannel { - channel : SelectableChannel @@ -147,9 +148,9 @@ App --> "-channels" AbstractNioChannel DatagramPacket ..+ NioDatagramChannel App --> "-dispatcher" Dispatcher ChangeKeyOpsCommand --+ NioReactor -LoggingHandler ..|> ChannelHandler -NioDatagramChannel --|> AbstractNioChannel -NioServerSocketChannel --|> AbstractNioChannel -SameThreadDispatcher ..|> Dispatcher -ThreadPoolDispatcher ..|> Dispatcher -@enduml \ No newline at end of file +LoggingHandler ..|> ChannelHandler +NioDatagramChannel --|> AbstractNioChannel +NioServerSocketChannel --|> AbstractNioChannel +SameThreadDispatcher ..|> Dispatcher +ThreadPoolDispatcher ..|> Dispatcher +@enduml diff --git a/reactor/pom.xml b/reactor/pom.xml index 1d3aa22e7..ca6440318 100644 --- a/reactor/pom.xml +++ b/reactor/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT reactor diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml index a46f6f5b2..7a873c551 100644 --- a/reader-writer-lock/pom.xml +++ b/reader-writer-lock/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT reader-writer-lock diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java index c22040418..30624a650 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java @@ -30,6 +30,9 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +/** + * InMemory Log Appender Util. + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/repository/pom.xml b/repository/pom.xml index 5cae0466f..cbb431e39 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT repository diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java index 0bab0950a..3da46e2ee 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java @@ -34,6 +34,9 @@ import org.springframework.data.jpa.domain.Specification; */ public class PersonSpecifications { + /** + * Specifications stating the Between (From - To) Age Specification + */ public static class AgeBetweenSpec implements Specification { private int from; diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml index ecf304ad2..fae94e91c 100644 --- a/resource-acquisition-is-initialization/pom.xml +++ b/resource-acquisition-is-initialization/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT resource-acquisition-is-initialization 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 38649cd96..6786416fa 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,19 +22,18 @@ */ 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.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertTrue; - /** * Date: 12/28/15 - 9:31 PM * @@ -64,6 +63,9 @@ public class ClosableTest { assertTrue(appender.logContains("Sliding door closes.")); } + /** + * Logging Appender Implementation + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/semaphore/pom.xml b/semaphore/pom.xml index 34b6bf629..1d606ae6c 100644 --- a/semaphore/pom.xml +++ b/semaphore/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT semaphore diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java b/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java index fc01b8329..88255997f 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java @@ -23,36 +23,39 @@ package com.iluwatar.semaphore; /** - * Fruit is a resource stored in a FruitBowl. + * Fruit is a resource stored in a FruitBowl. */ public class Fruit { + /** + * Enumeration of Fruit Types + */ public static enum FruitType { ORANGE, APPLE, LEMON } - + private FruitType type; - + public Fruit(FruitType type) { this.type = type; } - + public FruitType getType() { return type; } - + /** * toString method - */ + */ public String toString() { switch (type) { case ORANGE: return "Orange"; - case APPLE: + case APPLE: return "Apple"; - case LEMON: + case LEMON: return "Lemon"; - default: + default: return ""; } } diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java index 25dba2a6d..26d274262 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java @@ -25,10 +25,13 @@ package com.iluwatar.semaphore; import org.junit.Test; import java.io.IOException; +/** + * Application Test Entrypoint + */ public class AppTest{ @Test public void test() throws IOException { String[] args = {}; App.main(args); } -} \ No newline at end of file +} diff --git a/servant/pom.xml b/servant/pom.xml index fc59c795b..185076b59 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT servant diff --git a/service-layer/etc/service-layer.urm.puml b/service-layer/etc/service-layer.urm.puml index ff870a5e9..6cf9b938d 100644 --- a/service-layer/etc/service-layer.urm.puml +++ b/service-layer/etc/service-layer.urm.puml @@ -1,4 +1,5 @@ @startuml +left to right direction package com.iluwatar.servicelayer.hibernate { class HibernateUtil { - LOGGER : Logger {static} @@ -143,18 +144,18 @@ 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 \ No newline at end of file +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 3d9e5e26f..8028bcaea 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT service-layer diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java index 70feb1a00..401c4170c 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java @@ -27,6 +27,7 @@ import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; @@ -45,13 +46,17 @@ public abstract class DaoBaseImpl implements Dao { protected Class persistentClass = (Class) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; - protected Session getSession() { - return HibernateUtil.getSessionFactory().openSession(); + /* + * Making this getSessionFactory() instead of getSession() so that it is the responsibility + * of the caller to open as well as close the session (prevents potential resource leak). + */ + protected SessionFactory getSessionFactory() { + return HibernateUtil.getSessionFactory(); } @Override public E find(Long id) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; E result = null; try { @@ -73,7 +78,7 @@ public abstract class DaoBaseImpl implements Dao { @Override public void persist(E entity) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); @@ -91,7 +96,7 @@ public abstract class DaoBaseImpl implements Dao { @Override public E merge(E entity) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; E result = null; try { @@ -111,7 +116,7 @@ public abstract class DaoBaseImpl implements Dao { @Override public void delete(E entity) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); @@ -129,7 +134,7 @@ public abstract class DaoBaseImpl implements Dao { @Override public List findAll() { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; List result = null; try { diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java index b280b1250..81b3b6189 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java @@ -38,7 +38,7 @@ public class SpellDaoImpl extends DaoBaseImpl implements SpellDao { @Override public Spell findByName(String name) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; Spell result = null; try { diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java index 7724583ab..c7131b843 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java @@ -38,7 +38,7 @@ public class SpellbookDaoImpl extends DaoBaseImpl implements Spellboo @Override public Spellbook findByName(String name) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; Spellbook result = null; try { diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java index 67a37e969..0014bf921 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java @@ -39,7 +39,7 @@ public class WizardDaoImpl extends DaoBaseImpl implements WizardDao { @Override public Wizard findByName(String name) { - Session session = getSession(); + Session session = getSessionFactory().openSession(); Transaction tx = null; Wizard result = null; try { 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 79c7a0f86..694fc746d 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,23 +22,23 @@ */ package com.iluwatar.servicelayer.common; -import com.iluwatar.servicelayer.hibernate.HibernateUtil; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; - 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 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; + /** * Date: 12/28/15 - 10:53 PM - * + * Test for Base Data Access Objects + * @param Type of Base Entity + * @param Type of Dao Base Implementation * @author Jeroen Meulemeester */ public abstract class BaseDaoTest> { @@ -142,4 +142,4 @@ public abstract class BaseDaoTest assertEquals(expectedName, entity.toString()); } -} \ No newline at end of file +} diff --git a/service-locator/pom.xml b/service-locator/pom.xml index 397955f8e..3c9551770 100644 --- a/service-locator/pom.xml +++ b/service-locator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT service-locator diff --git a/singleton/pom.xml b/singleton/pom.xml index 8ddcb2131..672807527 100644 --- a/singleton/pom.xml +++ b/singleton/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT singleton diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index e8040ee99..f468ad0b8 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -22,7 +22,8 @@ */ package com.iluwatar.singleton; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.List; @@ -31,9 +32,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Supplier; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import org.junit.Test; /** * This class provides several test case that test singleton construction. @@ -43,7 +42,7 @@ import static org.junit.Assert.assertSame; * the same when called in the DIFFERENT thread. * * Date: 12/29/15 - 19:25 PM - * + * @param Supplier method generating singletons * @author Jeroen Meulemeester * @author Richard Jones */ diff --git a/specification/pom.xml b/specification/pom.xml index 40584b7ca..33cc0f1e5 100644 --- a/specification/pom.xml +++ b/specification/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT specification diff --git a/state/pom.xml b/state/pom.xml index 18a2608cd..7c0e9ab3f 100644 --- a/state/pom.xml +++ b/state/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT state diff --git a/step-builder/pom.xml b/step-builder/pom.xml index b33f48fb7..e98069d60 100644 --- a/step-builder/pom.xml +++ b/step-builder/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT step-builder diff --git a/strategy/pom.xml b/strategy/pom.xml index c47281228..d29f4b2ba 100644 --- a/strategy/pom.xml +++ b/strategy/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT strategy diff --git a/template-method/pom.xml b/template-method/pom.xml index 4a40c89fb..a2ceadc10 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT template-method 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 70cb23bfe..98ac62613 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -22,23 +22,22 @@ */ 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.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * Date: 12/30/15 - 18:12 PM - * + * @param Type of StealingMethod * @author Jeroen Meulemeester */ public abstract class StealingMethodTest { diff --git a/thread-pool/pom.xml b/thread-pool/pom.xml index a3b8d1fe6..2efd4cb50 100644 --- a/thread-pool/pom.xml +++ b/thread-pool/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT thread-pool 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 8f061575e..b3f253056 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java @@ -22,7 +22,8 @@ */ package com.iluwatar.threadpool; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; @@ -34,13 +35,12 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Function; import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; /** * Date: 12/30/15 - 18:22 PM - * + * Test for Tasks using a Thread Pool + * @param Type of Task * @author Jeroen Meulemeester */ public abstract class TaskTest { @@ -140,4 +140,4 @@ public abstract class TaskTest { } } -} \ No newline at end of file +} diff --git a/tls/README.md b/tls/README.md new file mode 100644 index 000000000..904d7ee05 --- /dev/null +++ b/tls/README.md @@ -0,0 +1,22 @@ +--- +layout: pattern +title: Thread Local Storage +folder: tls +permalink: /patterns/tls/ +pumlid: +categories: Concurrency +tags: + - Java + - Difficulty-Intermediate +--- + +## Intent +Securing variables global to a thread against being spoiled by other threads. That is needed if you use class variables or static variables in your Callable object or Runnable object that are not read-only. + +![alt text](./etc/tls.png "Thread Local Storage") + +## Applicability +Use the Thread Local Storage in any of the following situations + +* when you use class variables in your Callable / Runnalbe object that are not read-only and you use the same Callable instance in more than one thread running in parallel +* when you use static variables in your Callable / Runnable object that are not read-only and more than one instances of the Callable / Runnalbe may run in parallel threads. diff --git a/tls/etc/tls.png b/tls/etc/tls.png new file mode 100644 index 000000000..442f39a0c Binary files /dev/null and b/tls/etc/tls.png differ diff --git a/tls/etc/tls.ucls b/tls/etc/tls.ucls new file mode 100644 index 000000000..bd238346d --- /dev/null +++ b/tls/etc/tls.ucls @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tls/etc/tls.urm.puml b/tls/etc/tls.urm.puml new file mode 100644 index 000000000..d2eedb371 --- /dev/null +++ b/tls/etc/tls.urm.puml @@ -0,0 +1,23 @@ +@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 new file mode 100644 index 000000000..99849bf22 --- /dev/null +++ b/tls/pom.xml @@ -0,0 +1,43 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.16.0-SNAPSHOT + + tls + + + junit + junit + test + + + diff --git a/tls/src/main/java/com/iluwatar/tls/App.java b/tls/src/main/java/com/iluwatar/tls/App.java new file mode 100644 index 000000000..634d36d26 --- /dev/null +++ b/tls/src/main/java/com/iluwatar/tls/App.java @@ -0,0 +1,146 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import java.util.Calendar; +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * ThreadLocal pattern + *

+ * This App shows how to create an isolated space per each thread. In this + * example the usage of SimpleDateFormat is made to be thread-safe. This is an + * example of the ThreadLocal pattern. + *

+ * By applying the ThreadLocal pattern you can keep track of application + * instances or locale settings throughout the handling of a request. The + * ThreadLocal class works like a static variable, with the exception that it is + * only bound to the current thread! This allows us to use static variables in a + * thread-safe way. + *

+ * In Java, thread-local variables are implemented by the ThreadLocal class + * object. ThreadLocal holds a variable of type T, which is accessible via get/set + * methods. + *

+ * SimpleDateFormat is one of the basic Java classes and is not thread-safe. If + * you do not isolate the instance of SimpleDateFormat per each thread then + * problems arise. + *

+ * App converts the String date value 15/12/2015 to the Date format using the + * Java class SimpleDateFormat. It does this 20 times using 4 threads, each doing + * it 5 times. With the usage of as ThreadLocal in DateFormatCallable everything + * runs well. But if you comment out the ThreadLocal variant (marked with "//TLTL") + * and comment in the non ThreadLocal variant (marked with "//NTLNTL") you can + * see what will happen without the ThreadLocal. Most likely you will get incorrect + * date values and / or exceptions. + *

+ * This example clearly show what will happen when using non thread-safe classes + * in a thread. In real life this may happen one in of 1.000 or 10.000 conversions + * and those are really hard to find errors. + * + * @author Thomas Bauer, 2017 + */ +public class App { + /** + * Program entry point + * + * @param args + * command line args + */ + public static void main(String[] args) { + int counterDateValues = 0; + int counterExceptions = 0; + + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start 4 threads, each using the same Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + + Future futureResult1 = executor.submit(callableDf); + Future futureResult2 = executor.submit(callableDf); + Future futureResult3 = executor.submit(callableDf); + Future futureResult4 = executor.submit(callableDf); + try { + Result[] result = new Result[4]; + result[0] = futureResult1.get(); + result[1] = futureResult2.get(); + result[2] = futureResult3.get(); + result[3] = futureResult4.get(); + + // Print results of thread executions (converted dates and raised exceptions) + // and count them + for (int i = 0; i < result.length; i++) { + counterDateValues = counterDateValues + printAndCountDates(result[i]); + counterExceptions = counterExceptions + printAndCountExceptions(result[i]); + } + + // a correct run should deliver 20 times 15.12.2015 + // and a correct run shouldn't deliver any exception + System.out.println("The List dateList contains " + counterDateValues + " date values"); + System.out.println("The List exceptionList contains " + counterExceptions + " exceptions"); + + } catch (Exception e) { + System.out.println("Abnormal end of program. Program throws exception: " + e); + } + executor.shutdown(); + } + + /** + * Print result (date values) of a thread execution and count dates + * + * @param res contains results of a thread execution + */ + private static int printAndCountDates(Result res) { + // a correct run should deliver 5 times 15.12.2015 per each thread + int counter = 0; + for (Date dt : res.getDateList()) { + counter++; + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + // Formatted output of the date value: DD.MM.YYYY + System.out.println( + cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal.get(Calendar.YEAR)); + } + return counter; + } + + /** + * Print result (exceptions) of a thread execution and count exceptions + * + * @param res contains results of a thread execution + * @return number of dates + */ + private static int printAndCountExceptions(Result res) { + // a correct run shouldn't deliver any exception + int counter = 0; + for (String ex : res.getExceptionList()) { + counter++; + System.out.println(ex); + } + return counter; + } +} diff --git a/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java new file mode 100644 index 000000000..a28e24d4e --- /dev/null +++ b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java @@ -0,0 +1,98 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.concurrent.Callable; + +/** + * DateFormatCallable converts string dates to a date format using + * SimpleDateFormat. The date format and the date value will be passed to the + * Callable by the constructor. The constructor creates a instance of + * SimpleDateFormat and stores it in a ThreadLocal class variable. For the + * complete description of the example see {@link App} + * + * You can comment out the code marked with //TLTL and comment in the + * code marked //NTLNTL. Then you can see what will happen if you do not + * use the ThreadLocal. For details see the description of {@link App} + * + * @author Thomas Bauer, 2017 + */ +public class DateFormatCallable implements Callable { + // class variables (members) + private ThreadLocal df; //TLTL + // private DateFormat df; //NTLNTL + + private String dateValue; // for dateValue Thread Local not needed + + + /** + * The date format and the date value are passed to the constructor + * + * @param inDateFormat + * string date format string, e.g. "dd/MM/yyyy" + * @param inDateValue + * string date value, e.g. "21/06/2016" + */ + public DateFormatCallable(String inDateFormat, String inDateValue) { + final String idf = inDateFormat; //TLTL + this.df = new ThreadLocal() { //TLTL + @Override //TLTL + protected DateFormat initialValue() { //TLTL + return new SimpleDateFormat(idf); //TLTL + } //TLTL + }; //TLTL + // this.df = new SimpleDateFormat(inDateFormat); //NTLNTL + this.dateValue = inDateValue; + } + + /** + * @see java.util.concurrent.Callable#call() + */ + @Override + public Result call() { + System.out.println(Thread.currentThread() + " started executing..."); + Result result = new Result(); + + // Convert date value to date 5 times + for (int i = 1; i <= 5; i++) { + try { + // this is the statement where it is important to have the + // instance of SimpleDateFormat locally + // Create the date value and store it in dateList + result.getDateList().add(this.df.get().parse(this.dateValue)); //TLTL +// result.getDateList().add(this.df.parse(this.dateValue)); //NTLNTL + } catch (Exception e) { + // write the Exception to a list and continue work + result.getExceptionList().add(e.getClass() + ": " + e.getMessage()); + } + + } + + System.out.println(Thread.currentThread() + " finished processing part of the thread"); + + return result; + } +} diff --git a/tls/src/main/java/com/iluwatar/tls/Result.java b/tls/src/main/java/com/iluwatar/tls/Result.java new file mode 100644 index 000000000..69ec5c502 --- /dev/null +++ b/tls/src/main/java/com/iluwatar/tls/Result.java @@ -0,0 +1,62 @@ +/** + * 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. + */ +/* + * Fiducia IT AG, All rights reserved. Use is subject to license terms. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Result object that will be returned by the Callable {@link DateFormatCallable} + * used in {@link App} + * + * @author Thomas Bauer, 2017 + */ +public class Result { + // A list to collect the date values created in one thread + private List dateList = new ArrayList(); + + // A list to collect Exceptions thrown in one threads (should be none in + // this example) + private List exceptionList = new ArrayList(); + + /** + * + * @return List of date values collected within an thread execution + */ + public List getDateList() { + return dateList; + } + + /** + * + * @return List of exceptions thrown within an thread execution + */ + public List getExceptionList() { + return exceptionList; + } +} diff --git a/tls/src/test/java/com/iluwatar/tls/AppTest.java b/tls/src/test/java/com/iluwatar/tls/AppTest.java new file mode 100644 index 000000000..073c0988a --- /dev/null +++ b/tls/src/test/java/com/iluwatar/tls/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import org.junit.Test; + +/** + * Tests that thread local storage example runs without errors. + * + * @author Thomas Bauer, January 2017 + * + */ +public class AppTest { + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java new file mode 100644 index 000000000..b4f24be9b --- /dev/null +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -0,0 +1,144 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +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; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * After a successful run 5 date values should be in the result object. All dates should have + * the same value (15.11.2015). To avoid problems with time zone not the date instances themselves + * are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTest { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdDateValues = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by the run of DateFormatRunnalbe + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + createdDateValues = convertDatesToString(result); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new ArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + */ + @Test + public void testDateValues() { + assertEquals(expectedDateValues, createdDateValues); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver 5 date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should deliver + * no exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java new file mode 100644 index 000000000..e0a1507e9 --- /dev/null +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -0,0 +1,127 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +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; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * An incorrect formatted date is passed to the Callable + * After a successful run 0 date values and 5 exceptions should be in the result object. + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestIncorrectDateFormat { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdExceptions = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 0; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 5; + + /** + * Expected content of the list containing the exceptions created by the run of DateFormatRunnalbe + */ + List expectedExceptions = Arrays.asList("class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\""); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + 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"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + /** + * Test Exceptions after the run of DateFormatRunnalbe. A correct run should deliver 5 times the + * same exception + */ + @Test + public void testExecptions() { + assertEquals(expectedExceptions, result.getExceptionList()); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver no date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java new file mode 100644 index 000000000..635d6f25a --- /dev/null +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -0,0 +1,164 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * 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.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +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; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is used by 4 threads in parallel + *

+ * After a successful run 5 date values should be in the result object of each thread. All dates + * should have the same value (15.11.2015). To avoid problems with time zone not the date instances + * themselves are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestMultiThread { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable, one for each thread + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result[] result = new Result[4]; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + @SuppressWarnings("serial") + static class StringArrayList extends ArrayList { + /* nothing needed here */ + } + static List[] createdDateValues = new StringArrayList[4]; + + /** + * Expected number of date values in the date value list created by each thread + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by each thread + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by each thread + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult1 = executor.submit(callableDf); + Future futureResult2 = executor.submit(callableDf); + Future futureResult3 = executor.submit(callableDf); + Future futureResult4 = executor.submit(callableDf); + try { + result[0] = futureResult1.get(); + result[1] = futureResult2.get(); + result[2] = futureResult3.get(); + result[3] = futureResult4.get(); + for (int i = 0; i < result.length; i++) { + createdDateValues[i] = convertDatesToString(result[i]); + } + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new StringArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + * by each thread + */ + @Test + public void testDateValues() { + for (int i = 0; i < createdDateValues.length; i++) { + assertEquals(expectedDateValues, createdDateValues[i]); + } + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 date values by each thread + */ + @Test + public void testCounterDateValues() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterDateValues, result[i].getDateList().size()); + } + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver no exceptions + */ + @Test + public void testCounterExceptions() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterExceptions, result[i].getExceptionList().size()); + } + } +} diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml index da580631d..4e614e44c 100644 --- a/tolerant-reader/pom.xml +++ b/tolerant-reader/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT tolerant-reader diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java index d0ad5d798..7445dec4d 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java @@ -52,11 +52,10 @@ public final class RainbowFishSerializer { map.put("age", String.format("%d", rainbowFish.getAge())); map.put("lengthMeters", String.format("%d", rainbowFish.getLengthMeters())); map.put("weightTons", String.format("%d", rainbowFish.getWeightTons())); - FileOutputStream fileOut = new FileOutputStream(filename); - ObjectOutputStream objOut = new ObjectOutputStream(fileOut); - objOut.writeObject(map); - objOut.close(); - fileOut.close(); + try (FileOutputStream fileOut = new FileOutputStream(filename); + ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) { + objOut.writeObject(map); + } } /** @@ -71,23 +70,24 @@ public final class RainbowFishSerializer { map.put("angry", Boolean.toString(rainbowFish.getAngry())); map.put("hungry", Boolean.toString(rainbowFish.getHungry())); map.put("sleeping", Boolean.toString(rainbowFish.getSleeping())); - FileOutputStream fileOut = new FileOutputStream(filename); - ObjectOutputStream objOut = new ObjectOutputStream(fileOut); - objOut.writeObject(map); - objOut.close(); - fileOut.close(); + try (FileOutputStream fileOut = new FileOutputStream(filename); + ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) { + objOut.writeObject(map); + } } /** * Read V1 RainbowFish from file */ public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { - FileInputStream fileIn = new FileInputStream(filename); - ObjectInputStream objIn = new ObjectInputStream(fileIn); - Map map = (Map) objIn.readObject(); - objIn.close(); - fileIn.close(); - return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map - .get("lengthMeters")), Integer.parseInt(map.get("weightTons"))); + Map map = null; + + try (FileInputStream fileIn = new FileInputStream(filename); + ObjectInputStream objIn = new ObjectInputStream(fileIn)) { + map = (Map) objIn.readObject(); + } + + return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map.get("lengthMeters")), + Integer.parseInt(map.get("weightTons"))); } } diff --git a/twin/pom.xml b/twin/pom.xml index b9f6fb6ee..15b2e3094 100644 --- a/twin/pom.xml +++ b/twin/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT twin diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java index 8dfe9515c..5dad02481 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -22,22 +22,23 @@ */ package com.iluwatar.twin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoMoreInteractions; + 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.mockito.InOrder; 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.mockito.Mockito.*; - /** * Date: 12/30/15 - 18:44 PM * @@ -103,6 +104,9 @@ public class BallItemTest { assertEquals(1, appender.getLogSize()); } + /** + * Logging Appender Implementation + */ public class InMemoryAppender extends AppenderBase { private List log = new LinkedList<>(); diff --git a/value-object/pom.xml b/value-object/pom.xml index ae18ed94a..90716fbcc 100644 --- a/value-object/pom.xml +++ b/value-object/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT value-object diff --git a/visitor/pom.xml b/visitor/pom.xml index 2aeeb73b0..9acd24003 100644 --- a/visitor/pom.xml +++ b/visitor/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.15.0-SNAPSHOT + 1.16.0-SNAPSHOT visitor diff --git a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java index 98f0f66dc..ab8470512 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -22,19 +22,19 @@ */ package com.iluwatar.visitor; -import org.junit.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 + * @param Type of Unit * @author Jeroen Meulemeester */ public abstract class UnitTest { @@ -79,4 +79,4 @@ public abstract class UnitTest { */ abstract void verifyVisit(final U unit, final UnitVisitor mockedVisitor); -} \ No newline at end of file +} diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index dbcae196f..ba6705b23 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -22,23 +22,23 @@ */ 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.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -import static org.junit.Assert.assertEquals; - /** * Date: 12/30/15 - 18:59 PM - * + * Test case for Visitor Pattern + * @param Type of UnitVisitor * @author Jeroen Meulemeester */ public abstract class VisitorTest {